Dre4m Shell
Server IP : 85.214.239.14  /  Your IP : 18.224.69.44
Web Server : Apache/2.4.62 (Debian)
System : Linux h2886529.stratoserver.net 4.9.0 #1 SMP Tue Jan 9 19:45:01 MSK 2024 x86_64
User : www-data ( 33)
PHP Version : 7.4.18
Disable Function : pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
MySQL : OFF  |  cURL : OFF  |  WGET : ON  |  Perl : ON  |  Python : ON  |  Sudo : ON  |  Pkexec : OFF
Directory :  /proc/3/cwd/usr/share/doc/nodejs/api/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ HOME SHELL ]     

Current File : /proc/3/cwd/usr/share/doc/nodejs/api/all.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <meta name="nodejs.org:node-version" content="v20.18.0">
  <title>Node.js v20.18.0 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">
  <script async defer src="assets/api.js" type="text/javascript"></script>
  <script>
      const storedTheme = localStorage.getItem('theme');

      // Follow operating system theme preference
      if (storedTheme === null && window.matchMedia) {
        const mq = window.matchMedia('(prefers-color-scheme: dark)');
        if (mq.matches) {
          document.documentElement.classList.add('dark-mode');
        }
      } else if (storedTheme === 'dark') {
        document.documentElement.classList.add('dark-mode');
      }
  </script>
  <style>@media(max-width:598px){.with-47-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:582px){.with-45-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:526px){.with-38-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:542px){.with-40-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:622px){.with-50-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:1080px){.with-73-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:686px){.with-58-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:1072px){.with-72-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:654px){.with-54-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:606px){.with-48-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:1048px){.with-69-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:1144px){.with-81-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:590px){.with-46-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:638px){.with-52-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:1176px){.with-85-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:558px){.with-42-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:718px){.with-62-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:646px){.with-53-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:750px){.with-66-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:734px){.with-64-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:1088px){.with-74-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:630px){.with-51-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:662px){.with-55-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:702px){.with-60-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:478px){.with-32-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:574px){.with-44-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:294px){.with-9-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:374px){.with-19-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:518px){.with-37-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:742px){.with-65-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:326px){.with-13-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:446px){.with-28-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:566px){.with-43-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:398px){.with-22-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:670px){.with-56-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:334px){.with-14-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:366px){.with-18-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:318px){.with-12-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:342px){.with-15-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:550px){.with-41-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:486px){.with-33-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:758px){.with-67-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:1152px){.with-82-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:726px){.with-63-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:1096px){.with-75-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:534px){.with-39-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:462px){.with-30-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:286px){.with-8-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:614px){.with-49-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:694px){.with-59-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:510px){.with-36-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:502px){.with-35-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:494px){.with-34-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:678px){.with-57-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:766px){.with-68-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:1120px){.with-78-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:430px){.with-26-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:454px){.with-29-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:1064px){.with-71-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}@media(max-width:358px){.with-17-chars>.js-flavor-toggle{float:none;margin:0 0 1em auto;}}</style>
</head>
<body class="alt apidoc" id="api-section-all">
  <div id="content" class="clearfix">
    <div role="navigation" 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 this documentation</a></li>
<li><a href="synopsis.html" class="nav-synopsis">Usage and example</a></li>
</ul>
<hr class="line">
<ul>
<li><a href="assert.html" class="nav-assert">Assertion testing</a></li>
<li><a href="async_context.html" class="nav-async_context">Asynchronous context tracking</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 Node-API</a></li>
<li><a href="embedding.html" class="nav-embedding">C++ embedder 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="corepack.html" class="nav-corepack">Corepack</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="diagnostics_channel.html" class="nav-diagnostics_channel">Diagnostics Channel</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="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: CommonJS modules</a></li>
<li><a href="esm.html" class="nav-esm">Modules: ECMAScript modules</a></li>
<li><a href="module.html" class="nav-module">Modules: <code>node:module</code> API</a></li>
<li><a href="packages.html" class="nav-packages">Modules: Packages</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="permissions.html" class="nav-permissions">Permissions</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="single-executable-applications.html" class="nav-single-executable-applications">Single executable applications</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="test.html" class="nav-test">Test runner</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="webcrypto.html" class="nav-webcrypto">Web Crypto API</a></li>
<li><a href="webstreams.html" class="nav-webstreams">Web Streams API</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>
<hr class="line">
<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 class="header">
        <div class="header-container">
          <h1>Node.js v20.18.0 documentation</h1>
          <button class="theme-toggle-btn" id="theme-toggle-btn" title="Toggle dark mode/light mode" aria-label="Toggle dark mode/light mode" hidden>
            <svg xmlns="http://www.w3.org/2000/svg" class="icon dark-icon" height="24" width="24">
              <path fill="none" d="M0 0h24v24H0z" />
              <path d="M11.1 12.08c-2.33-4.51-.5-8.48.53-10.07C6.27 2.2 1.98 6.59 1.98 12c0 .14.02.28.02.42.62-.27 1.29-.42 2-.42 1.66 0 3.18.83 4.1 2.15A4.01 4.01 0 0111 18c0 1.52-.87 2.83-2.12 3.51.98.32 2.03.5 3.11.5 3.5 0 6.58-1.8 8.37-4.52-2.36.23-6.98-.97-9.26-5.41z"/>
              <path d="M7 16h-.18C6.4 14.84 5.3 14 4 14c-1.66 0-3 1.34-3 3s1.34 3 3 3h3c1.1 0 2-.9 2-2s-.9-2-2-2z"/>
            </svg>
            <svg xmlns="http://www.w3.org/2000/svg" class="icon light-icon" height="24" width="24">
              <path d="M0 0h24v24H0z" fill="none" />
              <path d="M6.76 4.84l-1.8-1.79-1.41 1.41 1.79 1.79 1.42-1.41zM4 10.5H1v2h3v-2zm9-9.95h-2V3.5h2V.55zm7.45 3.91l-1.41-1.41-1.79 1.79 1.41 1.41 1.79-1.79zm-3.21 13.7l1.79 1.8 1.41-1.41-1.8-1.79-1.4 1.4zM20 10.5v2h3v-2h-3zm-8-5c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6-2.69-6-6-6zm-1 16.95h2V19.5h-2v2.95zm-7.45-3.91l1.41 1.41 1.79-1.8-1.41-1.41-1.79 1.8z"/>
            </svg>
          </button>
        </div>
        <div id="gtoc">
          <ul>
            <li class="pinned-header">Node.js v20.18.0</li>
            
            
            
    <li class="picker-header">
      <a href="#">
        <span class="picker-arrow"></span>
        Other versions
      </a>
      <div class="picker"><ol id="alt-docs"><li><a href="https://nodejs.org/docs/latest-v22.x/api/all.html">22.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v21.x/api/all.html">21.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v20.x/api/all.html">20.x <b>LTS</b></a></li>
<li><a href="https://nodejs.org/docs/latest-v19.x/api/all.html">19.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v18.x/api/all.html">18.x <b>LTS</b></a></li>
<li><a href="https://nodejs.org/docs/latest-v17.x/api/all.html">17.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v16.x/api/all.html">16.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v15.x/api/all.html">15.x</a></li>
<li><a href="https://nodejs.org/docs/latest-v14.x/api/all.html">14.x</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</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</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></div>
    </li>
  
            <li class="picker-header">
              <a href="#">
                <span class="picker-arrow"></span>
                Options
              </a>
        
              <div class="picker">
                <ul>
                  <li>
                    <a href="index.html">View on single page</a>
                  </li>
                  <li>
                    <a href="all.json">View as JSON</a>
                  </li>
                      
                </ul>
              </div>
            </li>
          </ul>
        </div>
        <hr>
      </header>

      <!-- TOC --><details id="toc" open><summary>Table of contents</summary>
<ul>
<li><a href="#all_documentation_about-this-documentation">About this documentation</a>
<ul>
<li><a href="#all_documentation_contributing">Contributing</a></li>
<li><a href="#all_documentation_stability-index">Stability index</a></li>
<li><a href="#all_documentation_stability-overview">Stability overview</a></li>
<li><a href="#all_documentation_json-output">JSON output</a></li>
<li><a href="#all_documentation_system-calls-and-man-pages">System calls and man pages</a></li>
</ul>
</li>
<li><a href="#all_synopsis_usage-and-example">Usage and example</a>
<ul>
<li><a href="#all_synopsis_usage">Usage</a></li>
<li><a href="#all_synopsis_example">Example</a></li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_assert_assert">Assert</a></span>
<ul>
<li><a href="#all_assert_strict-assertion-mode">Strict assertion mode</a></li>
<li><a href="#all_assert_legacy-assertion-mode">Legacy assertion mode</a></li>
<li><a href="#all_assert_class-assertassertionerror">Class: assert.AssertionError</a>
<ul>
<li><a href="#all_assert_new-assertassertionerroroptions"><code>new assert.AssertionError(options)</code></a></li>
</ul>
</li>
<li><span class="stability_0"><a href="#all_assert_class-assertcalltracker">Class: <code>assert.CallTracker</code></a></span>
<ul>
<li><a href="#all_assert_new-assertcalltracker"><code>new assert.CallTracker()</code></a></li>
<li><a href="#all_assert_trackercallsfn-exact"><code>tracker.calls([fn][, exact])</code></a></li>
<li><a href="#all_assert_trackergetcallsfn"><code>tracker.getCalls(fn)</code></a></li>
<li><a href="#all_assert_trackerreport"><code>tracker.report()</code></a></li>
<li><a href="#all_assert_trackerresetfn"><code>tracker.reset([fn])</code></a></li>
<li><a href="#all_assert_trackerverify"><code>tracker.verify()</code></a></li>
</ul>
</li>
<li><a href="#all_assert_assertvalue-message"><code>assert(value[, message])</code></a></li>
<li><a href="#all_assert_assertdeepequalactual-expected-message"><code>assert.deepEqual(actual, expected[, message])</code></a>
<ul>
<li><a href="#all_assert_comparison-details">Comparison details</a></li>
</ul>
</li>
<li><a href="#all_assert_assertdeepstrictequalactual-expected-message"><code>assert.deepStrictEqual(actual, expected[, message])</code></a>
<ul>
<li><a href="#all_assert_comparison-details_1">Comparison details</a></li>
</ul>
</li>
<li><a href="#all_assert_assertdoesnotmatchstring-regexp-message"><code>assert.doesNotMatch(string, regexp[, message])</code></a></li>
<li><a href="#all_assert_assertdoesnotrejectasyncfn-error-message"><code>assert.doesNotReject(asyncFn[, error][, message])</code></a></li>
<li><a href="#all_assert_assertdoesnotthrowfn-error-message"><code>assert.doesNotThrow(fn[, error][, message])</code></a></li>
<li><a href="#all_assert_assertequalactual-expected-message"><code>assert.equal(actual, expected[, message])</code></a></li>
<li><a href="#all_assert_assertfailmessage"><code>assert.fail([message])</code></a></li>
<li><span class="stability_0"><a href="#all_assert_assertfailactual-expected-message-operator-stackstartfn"><code>assert.fail(actual, expected[, message[, operator[, stackStartFn]]])</code></a></span></li>
<li><a href="#all_assert_assertiferrorvalue"><code>assert.ifError(value)</code></a></li>
<li><a href="#all_assert_assertmatchstring-regexp-message"><code>assert.match(string, regexp[, message])</code></a></li>
<li><a href="#all_assert_assertnotdeepequalactual-expected-message"><code>assert.notDeepEqual(actual, expected[, message])</code></a></li>
<li><a href="#all_assert_assertnotdeepstrictequalactual-expected-message"><code>assert.notDeepStrictEqual(actual, expected[, message])</code></a></li>
<li><a href="#all_assert_assertnotequalactual-expected-message"><code>assert.notEqual(actual, expected[, message])</code></a></li>
<li><a href="#all_assert_assertnotstrictequalactual-expected-message"><code>assert.notStrictEqual(actual, expected[, message])</code></a></li>
<li><a href="#all_assert_assertokvalue-message"><code>assert.ok(value[, message])</code></a></li>
<li><a href="#all_assert_assertrejectsasyncfn-error-message"><code>assert.rejects(asyncFn[, error][, message])</code></a></li>
<li><a href="#all_assert_assertstrictequalactual-expected-message"><code>assert.strictEqual(actual, expected[, message])</code></a></li>
<li><a href="#all_assert_assertthrowsfn-error-message"><code>assert.throws(fn[, error][, message])</code></a></li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_async_context_asynchronous-context-tracking">Asynchronous context tracking</a></span>
<ul>
<li><a href="#all_async_context_introduction">Introduction</a></li>
<li><a href="#all_async_context_class-asynclocalstorage">Class: <code>AsyncLocalStorage</code></a>
<ul>
<li><a href="#all_async_context_new-asynclocalstorage"><code>new AsyncLocalStorage()</code></a></li>
<li><span class="stability_1"><a href="#all_async_context_static-method-asynclocalstoragebindfn">Static method: <code>AsyncLocalStorage.bind(fn)</code></a></span></li>
<li><span class="stability_1"><a href="#all_async_context_static-method-asynclocalstoragesnapshot">Static method: <code>AsyncLocalStorage.snapshot()</code></a></span></li>
<li><span class="stability_1"><a href="#all_async_context_asynclocalstoragedisable"><code>asyncLocalStorage.disable()</code></a></span></li>
<li><a href="#all_async_context_asynclocalstoragegetstore"><code>asyncLocalStorage.getStore()</code></a></li>
<li><span class="stability_1"><a href="#all_async_context_asynclocalstorageenterwithstore"><code>asyncLocalStorage.enterWith(store)</code></a></span></li>
<li><a href="#all_async_context_asynclocalstoragerunstore-callback-args"><code>asyncLocalStorage.run(store, callback[, ...args])</code></a></li>
<li><span class="stability_1"><a href="#all_async_context_asynclocalstorageexitcallback-args"><code>asyncLocalStorage.exit(callback[, ...args])</code></a></span></li>
<li><a href="#all_async_context_usage-with-asyncawait">Usage with <code>async/await</code></a></li>
<li><a href="#all_async_context_troubleshooting-context-loss">Troubleshooting: Context loss</a></li>
</ul>
</li>
<li><a href="#all_async_context_class-asyncresource">Class: <code>AsyncResource</code></a>
<ul>
<li><a href="#all_async_context_new-asyncresourcetype-options"><code>new AsyncResource(type[, options])</code></a></li>
<li><a href="#all_async_context_static-method-asyncresourcebindfn-type-thisarg">Static method: <code>AsyncResource.bind(fn[, type[, thisArg]])</code></a></li>
<li><a href="#all_async_context_asyncresourcebindfn-thisarg"><code>asyncResource.bind(fn[, thisArg])</code></a></li>
<li><a href="#all_async_context_asyncresourceruninasyncscopefn-thisarg-args"><code>asyncResource.runInAsyncScope(fn[, thisArg, ...args])</code></a></li>
<li><a href="#all_async_context_asyncresourceemitdestroy"><code>asyncResource.emitDestroy()</code></a></li>
<li><a href="#all_async_context_asyncresourceasyncid"><code>asyncResource.asyncId()</code></a></li>
<li><a href="#all_async_context_asyncresourcetriggerasyncid"><code>asyncResource.triggerAsyncId()</code></a></li>
<li><a href="#all_async_context_using-asyncresource-for-a-worker-thread-pool">Using <code>AsyncResource</code> for a <code>Worker</code> thread pool</a></li>
<li><a href="#all_async_context_integrating-asyncresource-with-eventemitter">Integrating <code>AsyncResource</code> with <code>EventEmitter</code></a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_async_hooks_async-hooks">Async hooks</a></span>
<ul>
<li><a href="#all_async_hooks_terminology">Terminology</a></li>
<li><a href="#all_async_hooks_overview">Overview</a></li>
<li><a href="#all_async_hooks_async_hookscreatehookcallbacks"><code>async_hooks.createHook(callbacks)</code></a>
<ul>
<li><a href="#all_async_hooks_error-handling">Error handling</a></li>
<li><a href="#all_async_hooks_printing-in-asynchook-callbacks">Printing in <code>AsyncHook</code> callbacks</a></li>
</ul>
</li>
<li><a href="#all_async_hooks_class-asynchook">Class: <code>AsyncHook</code></a>
<ul>
<li><a href="#all_async_hooks_asynchookenable"><code>asyncHook.enable()</code></a></li>
<li><a href="#all_async_hooks_asynchookdisable"><code>asyncHook.disable()</code></a></li>
<li><a href="#all_async_hooks_hook-callbacks">Hook callbacks</a>
<ul>
<li><a href="#all_async_hooks_initasyncid-type-triggerasyncid-resource"><code>init(asyncId, type, triggerAsyncId, resource)</code></a>
<ul>
<li><a href="#all_async_hooks_type"><code>type</code></a></li>
<li><a href="#all_async_hooks_triggerasyncid"><code>triggerAsyncId</code></a></li>
<li><a href="#all_async_hooks_resource"><code>resource</code></a></li>
<li><a href="#all_async_hooks_asynchronous-context-example">Asynchronous context example</a></li>
</ul>
</li>
<li><a href="#all_async_hooks_beforeasyncid"><code>before(asyncId)</code></a></li>
<li><a href="#all_async_hooks_afterasyncid"><code>after(asyncId)</code></a></li>
<li><a href="#all_async_hooks_destroyasyncid"><code>destroy(asyncId)</code></a></li>
<li><a href="#all_async_hooks_promiseresolveasyncid"><code>promiseResolve(asyncId)</code></a></li>
</ul>
</li>
<li><a href="#all_async_hooks_async_hooksexecutionasyncresource"><code>async_hooks.executionAsyncResource()</code></a></li>
<li><a href="#all_async_hooks_async_hooksexecutionasyncid"><code>async_hooks.executionAsyncId()</code></a></li>
<li><a href="#all_async_hooks_async_hookstriggerasyncid"><code>async_hooks.triggerAsyncId()</code></a></li>
<li><a href="#all_async_hooks_async_hooksasyncwrapproviders"><code>async_hooks.asyncWrapProviders</code></a></li>
</ul>
</li>
<li><a href="#all_async_hooks_promise-execution-tracking">Promise execution tracking</a></li>
<li><a href="#all_async_hooks_javascript-embedder-api">JavaScript embedder API</a>
<ul>
<li><a href="#all_async_hooks_class-asyncresource">Class: <code>AsyncResource</code></a></li>
</ul>
</li>
<li><a href="#all_async_hooks_class-asynclocalstorage">Class: <code>AsyncLocalStorage</code></a></li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_buffer_buffer">Buffer</a></span>
<ul>
<li><a href="#all_buffer_buffers-and-character-encodings">Buffers and character encodings</a></li>
<li><a href="#all_buffer_buffers-and-typedarrays">Buffers and TypedArrays</a></li>
<li><a href="#all_buffer_buffers-and-iteration">Buffers and iteration</a></li>
<li><a href="#all_buffer_class-blob">Class: <code>Blob</code></a>
<ul>
<li><a href="#all_buffer_new-bufferblobsources-options"><code>new buffer.Blob([sources[, options]])</code></a></li>
<li><a href="#all_buffer_blobarraybuffer"><code>blob.arrayBuffer()</code></a>
<ul>
<li><a href="#all_buffer_blobbytes"><code>blob.bytes()</code></a></li>
</ul>
</li>
<li><a href="#all_buffer_blobsize"><code>blob.size</code></a></li>
<li><a href="#all_buffer_blobslicestart-end-type"><code>blob.slice([start[, end[, type]]])</code></a></li>
<li><a href="#all_buffer_blobstream"><code>blob.stream()</code></a></li>
<li><a href="#all_buffer_blobtext"><code>blob.text()</code></a></li>
<li><a href="#all_buffer_blobtype"><code>blob.type</code></a></li>
<li><a href="#all_buffer_blob-objects-and-messagechannel"><code>Blob</code> objects and <code>MessageChannel</code></a></li>
</ul>
</li>
<li><a href="#all_buffer_class-buffer">Class: <code>Buffer</code></a>
<ul>
<li><a href="#all_buffer_static-method-bufferallocsize-fill-encoding">Static method: <code>Buffer.alloc(size[, fill[, encoding]])</code></a></li>
<li><a href="#all_buffer_static-method-bufferallocunsafesize">Static method: <code>Buffer.allocUnsafe(size)</code></a></li>
<li><a href="#all_buffer_static-method-bufferallocunsafeslowsize">Static method: <code>Buffer.allocUnsafeSlow(size)</code></a></li>
<li><a href="#all_buffer_static-method-bufferbytelengthstring-encoding">Static method: <code>Buffer.byteLength(string[, encoding])</code></a></li>
<li><a href="#all_buffer_static-method-buffercomparebuf1-buf2">Static method: <code>Buffer.compare(buf1, buf2)</code></a></li>
<li><a href="#all_buffer_static-method-bufferconcatlist-totallength">Static method: <code>Buffer.concat(list[, totalLength])</code></a></li>
<li><a href="#all_buffer_static-method-buffercopybytesfromview-offset-length">Static method: <code>Buffer.copyBytesFrom(view[, offset[, length]])</code></a></li>
<li><a href="#all_buffer_static-method-bufferfromarray">Static method: <code>Buffer.from(array)</code></a></li>
<li><a href="#all_buffer_static-method-bufferfromarraybuffer-byteoffset-length">Static method: <code>Buffer.from(arrayBuffer[, byteOffset[, length]])</code></a></li>
<li><a href="#all_buffer_static-method-bufferfrombuffer">Static method: <code>Buffer.from(buffer)</code></a></li>
<li><a href="#all_buffer_static-method-bufferfromobject-offsetorencoding-length">Static method: <code>Buffer.from(object[, offsetOrEncoding[, length]])</code></a></li>
<li><a href="#all_buffer_static-method-bufferfromstring-encoding">Static method: <code>Buffer.from(string[, encoding])</code></a></li>
<li><a href="#all_buffer_static-method-bufferisbufferobj">Static method: <code>Buffer.isBuffer(obj)</code></a></li>
<li><a href="#all_buffer_static-method-bufferisencodingencoding">Static method: <code>Buffer.isEncoding(encoding)</code></a></li>
<li><a href="#all_buffer_class-property-bufferpoolsize">Class property: <code>Buffer.poolSize</code></a></li>
<li><a href="#all_buffer_bufindex"><code>buf[index]</code></a></li>
<li><a href="#all_buffer_bufbuffer"><code>buf.buffer</code></a></li>
<li><a href="#all_buffer_bufbyteoffset"><code>buf.byteOffset</code></a></li>
<li><a href="#all_buffer_bufcomparetarget-targetstart-targetend-sourcestart-sourceend"><code>buf.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]])</code></a></li>
<li><a href="#all_buffer_bufcopytarget-targetstart-sourcestart-sourceend"><code>buf.copy(target[, targetStart[, sourceStart[, sourceEnd]]])</code></a></li>
<li><a href="#all_buffer_bufentries"><code>buf.entries()</code></a></li>
<li><a href="#all_buffer_bufequalsotherbuffer"><code>buf.equals(otherBuffer)</code></a></li>
<li><a href="#all_buffer_buffillvalue-offset-end-encoding"><code>buf.fill(value[, offset[, end]][, encoding])</code></a></li>
<li><a href="#all_buffer_bufincludesvalue-byteoffset-encoding"><code>buf.includes(value[, byteOffset][, encoding])</code></a></li>
<li><a href="#all_buffer_bufindexofvalue-byteoffset-encoding"><code>buf.indexOf(value[, byteOffset][, encoding])</code></a></li>
<li><a href="#all_buffer_bufkeys"><code>buf.keys()</code></a></li>
<li><a href="#all_buffer_buflastindexofvalue-byteoffset-encoding"><code>buf.lastIndexOf(value[, byteOffset][, encoding])</code></a></li>
<li><a href="#all_buffer_buflength"><code>buf.length</code></a></li>
<li><span class="stability_0"><a href="#all_buffer_bufparent"><code>buf.parent</code></a></span></li>
<li><a href="#all_buffer_bufreadbigint64beoffset"><code>buf.readBigInt64BE([offset])</code></a></li>
<li><a href="#all_buffer_bufreadbigint64leoffset"><code>buf.readBigInt64LE([offset])</code></a></li>
<li><a href="#all_buffer_bufreadbiguint64beoffset"><code>buf.readBigUInt64BE([offset])</code></a></li>
<li><a href="#all_buffer_bufreadbiguint64leoffset"><code>buf.readBigUInt64LE([offset])</code></a></li>
<li><a href="#all_buffer_bufreaddoublebeoffset"><code>buf.readDoubleBE([offset])</code></a></li>
<li><a href="#all_buffer_bufreaddoubleleoffset"><code>buf.readDoubleLE([offset])</code></a></li>
<li><a href="#all_buffer_bufreadfloatbeoffset"><code>buf.readFloatBE([offset])</code></a></li>
<li><a href="#all_buffer_bufreadfloatleoffset"><code>buf.readFloatLE([offset])</code></a></li>
<li><a href="#all_buffer_bufreadint8offset"><code>buf.readInt8([offset])</code></a></li>
<li><a href="#all_buffer_bufreadint16beoffset"><code>buf.readInt16BE([offset])</code></a></li>
<li><a href="#all_buffer_bufreadint16leoffset"><code>buf.readInt16LE([offset])</code></a></li>
<li><a href="#all_buffer_bufreadint32beoffset"><code>buf.readInt32BE([offset])</code></a></li>
<li><a href="#all_buffer_bufreadint32leoffset"><code>buf.readInt32LE([offset])</code></a></li>
<li><a href="#all_buffer_bufreadintbeoffset-bytelength"><code>buf.readIntBE(offset, byteLength)</code></a></li>
<li><a href="#all_buffer_bufreadintleoffset-bytelength"><code>buf.readIntLE(offset, byteLength)</code></a></li>
<li><a href="#all_buffer_bufreaduint8offset"><code>buf.readUInt8([offset])</code></a></li>
<li><a href="#all_buffer_bufreaduint16beoffset"><code>buf.readUInt16BE([offset])</code></a></li>
<li><a href="#all_buffer_bufreaduint16leoffset"><code>buf.readUInt16LE([offset])</code></a></li>
<li><a href="#all_buffer_bufreaduint32beoffset"><code>buf.readUInt32BE([offset])</code></a></li>
<li><a href="#all_buffer_bufreaduint32leoffset"><code>buf.readUInt32LE([offset])</code></a></li>
<li><a href="#all_buffer_bufreaduintbeoffset-bytelength"><code>buf.readUIntBE(offset, byteLength)</code></a></li>
<li><a href="#all_buffer_bufreaduintleoffset-bytelength"><code>buf.readUIntLE(offset, byteLength)</code></a></li>
<li><a href="#all_buffer_bufsubarraystart-end"><code>buf.subarray([start[, end]])</code></a></li>
<li><span class="stability_0"><a href="#all_buffer_bufslicestart-end"><code>buf.slice([start[, end]])</code></a></span></li>
<li><a href="#all_buffer_bufswap16"><code>buf.swap16()</code></a></li>
<li><a href="#all_buffer_bufswap32"><code>buf.swap32()</code></a></li>
<li><a href="#all_buffer_bufswap64"><code>buf.swap64()</code></a></li>
<li><a href="#all_buffer_buftojson"><code>buf.toJSON()</code></a></li>
<li><a href="#all_buffer_buftostringencoding-start-end"><code>buf.toString([encoding[, start[, end]]])</code></a></li>
<li><a href="#all_buffer_bufvalues"><code>buf.values()</code></a></li>
<li><a href="#all_buffer_bufwritestring-offset-length-encoding"><code>buf.write(string[, offset[, length]][, encoding])</code></a></li>
<li><a href="#all_buffer_bufwritebigint64bevalue-offset"><code>buf.writeBigInt64BE(value[, offset])</code></a></li>
<li><a href="#all_buffer_bufwritebigint64levalue-offset"><code>buf.writeBigInt64LE(value[, offset])</code></a></li>
<li><a href="#all_buffer_bufwritebiguint64bevalue-offset"><code>buf.writeBigUInt64BE(value[, offset])</code></a></li>
<li><a href="#all_buffer_bufwritebiguint64levalue-offset"><code>buf.writeBigUInt64LE(value[, offset])</code></a></li>
<li><a href="#all_buffer_bufwritedoublebevalue-offset"><code>buf.writeDoubleBE(value[, offset])</code></a></li>
<li><a href="#all_buffer_bufwritedoublelevalue-offset"><code>buf.writeDoubleLE(value[, offset])</code></a></li>
<li><a href="#all_buffer_bufwritefloatbevalue-offset"><code>buf.writeFloatBE(value[, offset])</code></a></li>
<li><a href="#all_buffer_bufwritefloatlevalue-offset"><code>buf.writeFloatLE(value[, offset])</code></a></li>
<li><a href="#all_buffer_bufwriteint8value-offset"><code>buf.writeInt8(value[, offset])</code></a></li>
<li><a href="#all_buffer_bufwriteint16bevalue-offset"><code>buf.writeInt16BE(value[, offset])</code></a></li>
<li><a href="#all_buffer_bufwriteint16levalue-offset"><code>buf.writeInt16LE(value[, offset])</code></a></li>
<li><a href="#all_buffer_bufwriteint32bevalue-offset"><code>buf.writeInt32BE(value[, offset])</code></a></li>
<li><a href="#all_buffer_bufwriteint32levalue-offset"><code>buf.writeInt32LE(value[, offset])</code></a></li>
<li><a href="#all_buffer_bufwriteintbevalue-offset-bytelength"><code>buf.writeIntBE(value, offset, byteLength)</code></a></li>
<li><a href="#all_buffer_bufwriteintlevalue-offset-bytelength"><code>buf.writeIntLE(value, offset, byteLength)</code></a></li>
<li><a href="#all_buffer_bufwriteuint8value-offset"><code>buf.writeUInt8(value[, offset])</code></a></li>
<li><a href="#all_buffer_bufwriteuint16bevalue-offset"><code>buf.writeUInt16BE(value[, offset])</code></a></li>
<li><a href="#all_buffer_bufwriteuint16levalue-offset"><code>buf.writeUInt16LE(value[, offset])</code></a></li>
<li><a href="#all_buffer_bufwriteuint32bevalue-offset"><code>buf.writeUInt32BE(value[, offset])</code></a></li>
<li><a href="#all_buffer_bufwriteuint32levalue-offset"><code>buf.writeUInt32LE(value[, offset])</code></a></li>
<li><a href="#all_buffer_bufwriteuintbevalue-offset-bytelength"><code>buf.writeUIntBE(value, offset, byteLength)</code></a></li>
<li><a href="#all_buffer_bufwriteuintlevalue-offset-bytelength"><code>buf.writeUIntLE(value, offset, byteLength)</code></a></li>
<li><span class="stability_0"><a href="#all_buffer_new-bufferarray"><code>new Buffer(array)</code></a></span></li>
<li><span class="stability_0"><a href="#all_buffer_new-bufferarraybuffer-byteoffset-length"><code>new Buffer(arrayBuffer[, byteOffset[, length]])</code></a></span></li>
<li><span class="stability_0"><a href="#all_buffer_new-bufferbuffer"><code>new Buffer(buffer)</code></a></span></li>
<li><span class="stability_0"><a href="#all_buffer_new-buffersize"><code>new Buffer(size)</code></a></span></li>
<li><span class="stability_0"><a href="#all_buffer_new-bufferstring-encoding"><code>new Buffer(string[, encoding])</code></a></span></li>
</ul>
</li>
<li><a href="#all_buffer_class-file">Class: <code>File</code></a>
<ul>
<li><a href="#all_buffer_new-bufferfilesources-filename-options"><code>new buffer.File(sources, fileName[, options])</code></a></li>
<li><a href="#all_buffer_filename"><code>file.name</code></a></li>
<li><a href="#all_buffer_filelastmodified"><code>file.lastModified</code></a></li>
</ul>
</li>
<li><a href="#all_buffer_nodebuffer-module-apis"><code>node:buffer</code> module APIs</a>
<ul>
<li><span class="stability_3"><a href="#all_buffer_bufferatobdata"><code>buffer.atob(data)</code></a></span></li>
<li><span class="stability_3"><a href="#all_buffer_bufferbtoadata"><code>buffer.btoa(data)</code></a></span></li>
<li><a href="#all_buffer_bufferisasciiinput"><code>buffer.isAscii(input)</code></a></li>
<li><a href="#all_buffer_bufferisutf8input"><code>buffer.isUtf8(input)</code></a></li>
<li><a href="#all_buffer_bufferinspect_max_bytes"><code>buffer.INSPECT_MAX_BYTES</code></a></li>
<li><a href="#all_buffer_bufferkmaxlength"><code>buffer.kMaxLength</code></a></li>
<li><a href="#all_buffer_bufferkstringmaxlength"><code>buffer.kStringMaxLength</code></a></li>
<li><span class="stability_1"><a href="#all_buffer_bufferresolveobjecturlid"><code>buffer.resolveObjectURL(id)</code></a></span></li>
<li><a href="#all_buffer_buffertranscodesource-fromenc-toenc"><code>buffer.transcode(source, fromEnc, toEnc)</code></a></li>
<li><span class="stability_0"><a href="#all_buffer_class-slowbuffer">Class: <code>SlowBuffer</code></a></span>
<ul>
<li><span class="stability_0"><a href="#all_buffer_new-slowbuffersize"><code>new SlowBuffer(size)</code></a></span></li>
</ul>
</li>
<li><a href="#all_buffer_buffer-constants">Buffer constants</a>
<ul>
<li><a href="#all_buffer_bufferconstantsmax_length"><code>buffer.constants.MAX_LENGTH</code></a></li>
<li><a href="#all_buffer_bufferconstantsmax_string_length"><code>buffer.constants.MAX_STRING_LENGTH</code></a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_buffer_bufferfrom-bufferalloc-and-bufferallocunsafe"><code>Buffer.from()</code>, <code>Buffer.alloc()</code>, and <code>Buffer.allocUnsafe()</code></a>
<ul>
<li><a href="#all_buffer_the---zero-fill-buffers-command-line-option">The <code>--zero-fill-buffers</code> command-line option</a></li>
<li><a href="#all_buffer_what-makes-bufferallocunsafe-and-bufferallocunsafeslow-unsafe">What makes <code>Buffer.allocUnsafe()</code> and <code>Buffer.allocUnsafeSlow()</code> "unsafe"?</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_addons_c-addons">C++ addons</a>
<ul>
<li><a href="#all_addons_hello-world">Hello world</a>
<ul>
<li><a href="#all_addons_context-aware-addons">Context-aware addons</a>
<ul>
<li><a href="#all_addons_worker-support">Worker support</a></li>
</ul>
</li>
<li><a href="#all_addons_building">Building</a></li>
<li><a href="#all_addons_linking-to-libraries-included-with-nodejs">Linking to libraries included with Node.js</a></li>
<li><a href="#all_addons_loading-addons-using-require">Loading addons using <code>require()</code></a></li>
</ul>
</li>
<li><a href="#all_addons_native-abstractions-for-nodejs">Native abstractions for Node.js</a></li>
<li><span class="stability_2"><a href="#all_addons_node-api">Node-API</a></span></li>
<li><a href="#all_addons_addon-examples">Addon examples</a>
<ul>
<li><a href="#all_addons_function-arguments">Function arguments</a></li>
<li><a href="#all_addons_callbacks">Callbacks</a></li>
<li><a href="#all_addons_object-factory">Object factory</a></li>
<li><a href="#all_addons_function-factory">Function factory</a></li>
<li><a href="#all_addons_wrapping-c-objects">Wrapping C++ objects</a></li>
<li><a href="#all_addons_factory-of-wrapped-objects">Factory of wrapped objects</a></li>
<li><a href="#all_addons_passing-wrapped-objects-around">Passing wrapped objects around</a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_n-api_node-api">Node-API</a></span>
<ul>
<li><a href="#all_n-api_implications-of-abi-stability">Implications of ABI stability</a></li>
<li><a href="#all_n-api_building">Building</a>
<ul>
<li><a href="#all_n-api_build-tools">Build tools</a>
<ul>
<li><a href="#all_n-api_node-gyp">node-gyp</a></li>
<li><a href="#all_n-api_cmakejs">CMake.js</a></li>
</ul>
</li>
<li><a href="#all_n-api_uploading-precompiled-binaries">Uploading precompiled binaries</a>
<ul>
<li><a href="#all_n-api_node-pre-gyp">node-pre-gyp</a></li>
<li><a href="#all_n-api_prebuild">prebuild</a></li>
<li><a href="#all_n-api_prebuildify">prebuildify</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_n-api_usage">Usage</a></li>
<li><a href="#all_n-api_node-api-version-matrix">Node-API version matrix</a></li>
<li><a href="#all_n-api_environment-life-cycle-apis">Environment life cycle APIs</a>
<ul>
<li><a href="#all_n-api_napi_set_instance_data"><code>napi_set_instance_data</code></a></li>
<li><a href="#all_n-api_napi_get_instance_data"><code>napi_get_instance_data</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_basic-node-api-data-types">Basic Node-API data types</a>
<ul>
<li><a href="#all_n-api_napi_status"><code>napi_status</code></a></li>
<li><a href="#all_n-api_napi_extended_error_info"><code>napi_extended_error_info</code></a></li>
<li><a href="#all_n-api_napi_env"><code>napi_env</code></a></li>
<li><span class="stability_1"><a href="#all_n-api_node_api_basic_env"><code>node_api_basic_env</code></a></span></li>
<li><a href="#all_n-api_napi_value"><code>napi_value</code></a></li>
<li><a href="#all_n-api_napi_threadsafe_function"><code>napi_threadsafe_function</code></a></li>
<li><a href="#all_n-api_napi_threadsafe_function_release_mode"><code>napi_threadsafe_function_release_mode</code></a></li>
<li><a href="#all_n-api_napi_threadsafe_function_call_mode"><code>napi_threadsafe_function_call_mode</code></a></li>
<li><a href="#all_n-api_node-api-memory-management-types">Node-API memory management types</a>
<ul>
<li><a href="#all_n-api_napi_handle_scope"><code>napi_handle_scope</code></a></li>
<li><a href="#all_n-api_napi_escapable_handle_scope"><code>napi_escapable_handle_scope</code></a></li>
<li><a href="#all_n-api_napi_ref"><code>napi_ref</code></a></li>
<li><a href="#all_n-api_napi_type_tag"><code>napi_type_tag</code></a></li>
<li><a href="#all_n-api_napi_async_cleanup_hook_handle"><code>napi_async_cleanup_hook_handle</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_node-api-callback-types">Node-API callback types</a>
<ul>
<li><a href="#all_n-api_napi_callback_info"><code>napi_callback_info</code></a></li>
<li><a href="#all_n-api_napi_callback"><code>napi_callback</code></a></li>
<li><span class="stability_1"><a href="#all_n-api_node_api_basic_finalize"><code>node_api_basic_finalize</code></a></span></li>
<li><a href="#all_n-api_napi_finalize"><code>napi_finalize</code></a></li>
<li><a href="#all_n-api_napi_async_execute_callback"><code>napi_async_execute_callback</code></a></li>
<li><a href="#all_n-api_napi_async_complete_callback"><code>napi_async_complete_callback</code></a></li>
<li><a href="#all_n-api_napi_threadsafe_function_call_js"><code>napi_threadsafe_function_call_js</code></a></li>
<li><a href="#all_n-api_napi_cleanup_hook"><code>napi_cleanup_hook</code></a></li>
<li><a href="#all_n-api_napi_async_cleanup_hook"><code>napi_async_cleanup_hook</code></a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_n-api_error-handling">Error handling</a>
<ul>
<li><a href="#all_n-api_return-values">Return values</a>
<ul>
<li><a href="#all_n-api_napi_get_last_error_info"><code>napi_get_last_error_info</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_exceptions">Exceptions</a>
<ul>
<li><a href="#all_n-api_napi_throw"><code>napi_throw</code></a></li>
<li><a href="#all_n-api_napi_throw_error"><code>napi_throw_error</code></a></li>
<li><a href="#all_n-api_napi_throw_type_error"><code>napi_throw_type_error</code></a></li>
<li><a href="#all_n-api_napi_throw_range_error"><code>napi_throw_range_error</code></a></li>
<li><a href="#all_n-api_node_api_throw_syntax_error"><code>node_api_throw_syntax_error</code></a></li>
<li><a href="#all_n-api_napi_is_error"><code>napi_is_error</code></a></li>
<li><a href="#all_n-api_napi_create_error"><code>napi_create_error</code></a></li>
<li><a href="#all_n-api_napi_create_type_error"><code>napi_create_type_error</code></a></li>
<li><a href="#all_n-api_napi_create_range_error"><code>napi_create_range_error</code></a></li>
<li><a href="#all_n-api_node_api_create_syntax_error"><code>node_api_create_syntax_error</code></a></li>
<li><a href="#all_n-api_napi_get_and_clear_last_exception"><code>napi_get_and_clear_last_exception</code></a></li>
<li><a href="#all_n-api_napi_is_exception_pending"><code>napi_is_exception_pending</code></a></li>
<li><a href="#all_n-api_napi_fatal_exception"><code>napi_fatal_exception</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_fatal-errors">Fatal errors</a>
<ul>
<li><a href="#all_n-api_napi_fatal_error"><code>napi_fatal_error</code></a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_n-api_object-lifetime-management">Object lifetime management</a>
<ul>
<li><a href="#all_n-api_making-handle-lifespan-shorter-than-that-of-the-native-method">Making handle lifespan shorter than that of the native method</a>
<ul>
<li><a href="#all_n-api_napi_open_handle_scope"><code>napi_open_handle_scope</code></a></li>
<li><a href="#all_n-api_napi_close_handle_scope"><code>napi_close_handle_scope</code></a></li>
<li><a href="#all_n-api_napi_open_escapable_handle_scope"><code>napi_open_escapable_handle_scope</code></a></li>
<li><a href="#all_n-api_napi_close_escapable_handle_scope"><code>napi_close_escapable_handle_scope</code></a></li>
<li><a href="#all_n-api_napi_escape_handle"><code>napi_escape_handle</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_references-to-values-with-a-lifespan-longer-than-that-of-the-native-method">References to values with a lifespan longer than that of the native method</a>
<ul>
<li><a href="#all_n-api_napi_create_reference"><code>napi_create_reference</code></a></li>
<li><a href="#all_n-api_napi_delete_reference"><code>napi_delete_reference</code></a></li>
<li><a href="#all_n-api_napi_reference_ref"><code>napi_reference_ref</code></a></li>
<li><a href="#all_n-api_napi_reference_unref"><code>napi_reference_unref</code></a></li>
<li><a href="#all_n-api_napi_get_reference_value"><code>napi_get_reference_value</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_cleanup-on-exit-of-the-current-nodejs-environment">Cleanup on exit of the current Node.js environment</a>
<ul>
<li><a href="#all_n-api_napi_add_env_cleanup_hook"><code>napi_add_env_cleanup_hook</code></a></li>
<li><a href="#all_n-api_napi_remove_env_cleanup_hook"><code>napi_remove_env_cleanup_hook</code></a></li>
<li><a href="#all_n-api_napi_add_async_cleanup_hook"><code>napi_add_async_cleanup_hook</code></a></li>
<li><a href="#all_n-api_napi_remove_async_cleanup_hook"><code>napi_remove_async_cleanup_hook</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_finalization-on-the-exit-of-the-nodejs-environment">Finalization on the exit of the Node.js environment</a></li>
</ul>
</li>
<li><a href="#all_n-api_module-registration">Module registration</a></li>
<li><a href="#all_n-api_working-with-javascript-values">Working with JavaScript values</a>
<ul>
<li><a href="#all_n-api_enum-types">Enum types</a>
<ul>
<li><a href="#all_n-api_napi_key_collection_mode"><code>napi_key_collection_mode</code></a></li>
<li><a href="#all_n-api_napi_key_filter"><code>napi_key_filter</code></a></li>
<li><a href="#all_n-api_napi_key_conversion"><code>napi_key_conversion</code></a></li>
<li><a href="#all_n-api_napi_valuetype"><code>napi_valuetype</code></a></li>
<li><a href="#all_n-api_napi_typedarray_type"><code>napi_typedarray_type</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_object-creation-functions">Object creation functions</a>
<ul>
<li><a href="#all_n-api_napi_create_array"><code>napi_create_array</code></a></li>
<li><a href="#all_n-api_napi_create_array_with_length"><code>napi_create_array_with_length</code></a></li>
<li><a href="#all_n-api_napi_create_arraybuffer"><code>napi_create_arraybuffer</code></a></li>
<li><a href="#all_n-api_napi_create_buffer"><code>napi_create_buffer</code></a></li>
<li><a href="#all_n-api_napi_create_buffer_copy"><code>napi_create_buffer_copy</code></a></li>
<li><a href="#all_n-api_napi_create_date"><code>napi_create_date</code></a></li>
<li><a href="#all_n-api_napi_create_external"><code>napi_create_external</code></a></li>
<li><a href="#all_n-api_napi_create_external_arraybuffer"><code>napi_create_external_arraybuffer</code></a></li>
<li><a href="#all_n-api_napi_create_external_buffer"><code>napi_create_external_buffer</code></a></li>
<li><a href="#all_n-api_napi_create_object"><code>napi_create_object</code></a></li>
<li><a href="#all_n-api_napi_create_symbol"><code>napi_create_symbol</code></a></li>
<li><a href="#all_n-api_node_api_symbol_for"><code>node_api_symbol_for</code></a></li>
<li><a href="#all_n-api_napi_create_typedarray"><code>napi_create_typedarray</code></a></li>
<li><a href="#all_n-api_napi_create_dataview"><code>napi_create_dataview</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_functions-to-convert-from-c-types-to-node-api">Functions to convert from C types to Node-API</a>
<ul>
<li><a href="#all_n-api_napi_create_int32"><code>napi_create_int32</code></a></li>
<li><a href="#all_n-api_napi_create_uint32"><code>napi_create_uint32</code></a></li>
<li><a href="#all_n-api_napi_create_int64"><code>napi_create_int64</code></a></li>
<li><a href="#all_n-api_napi_create_double"><code>napi_create_double</code></a></li>
<li><a href="#all_n-api_napi_create_bigint_int64"><code>napi_create_bigint_int64</code></a></li>
<li><a href="#all_n-api_napi_create_bigint_uint64"><code>napi_create_bigint_uint64</code></a></li>
<li><a href="#all_n-api_napi_create_bigint_words"><code>napi_create_bigint_words</code></a></li>
<li><a href="#all_n-api_napi_create_string_latin1"><code>napi_create_string_latin1</code></a></li>
<li><span class="stability_1"><a href="#all_n-api_node_api_create_external_string_latin1"><code>node_api_create_external_string_latin1</code></a></span></li>
<li><a href="#all_n-api_napi_create_string_utf16"><code>napi_create_string_utf16</code></a></li>
<li><span class="stability_1"><a href="#all_n-api_node_api_create_external_string_utf16"><code>node_api_create_external_string_utf16</code></a></span></li>
<li><a href="#all_n-api_napi_create_string_utf8"><code>napi_create_string_utf8</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_functions-to-create-optimized-property-keys">Functions to create optimized property keys</a>
<ul>
<li><span class="stability_1"><a href="#all_n-api_node_api_create_property_key_latin1"><code>node_api_create_property_key_latin1</code></a></span></li>
<li><span class="stability_1"><a href="#all_n-api_node_api_create_property_key_utf16"><code>node_api_create_property_key_utf16</code></a></span></li>
<li><span class="stability_1"><a href="#all_n-api_node_api_create_property_key_utf8"><code>node_api_create_property_key_utf8</code></a></span></li>
</ul>
</li>
<li><a href="#all_n-api_functions-to-convert-from-node-api-to-c-types">Functions to convert from Node-API to C types</a>
<ul>
<li><a href="#all_n-api_napi_get_array_length"><code>napi_get_array_length</code></a></li>
<li><a href="#all_n-api_napi_get_arraybuffer_info"><code>napi_get_arraybuffer_info</code></a></li>
<li><a href="#all_n-api_napi_get_buffer_info"><code>napi_get_buffer_info</code></a></li>
<li><a href="#all_n-api_napi_get_prototype"><code>napi_get_prototype</code></a></li>
<li><a href="#all_n-api_napi_get_typedarray_info"><code>napi_get_typedarray_info</code></a></li>
<li><a href="#all_n-api_napi_get_dataview_info"><code>napi_get_dataview_info</code></a></li>
<li><a href="#all_n-api_napi_get_date_value"><code>napi_get_date_value</code></a></li>
<li><a href="#all_n-api_napi_get_value_bool"><code>napi_get_value_bool</code></a></li>
<li><a href="#all_n-api_napi_get_value_double"><code>napi_get_value_double</code></a></li>
<li><a href="#all_n-api_napi_get_value_bigint_int64"><code>napi_get_value_bigint_int64</code></a></li>
<li><a href="#all_n-api_napi_get_value_bigint_uint64"><code>napi_get_value_bigint_uint64</code></a></li>
<li><a href="#all_n-api_napi_get_value_bigint_words"><code>napi_get_value_bigint_words</code></a></li>
<li><a href="#all_n-api_napi_get_value_external"><code>napi_get_value_external</code></a></li>
<li><a href="#all_n-api_napi_get_value_int32"><code>napi_get_value_int32</code></a></li>
<li><a href="#all_n-api_napi_get_value_int64"><code>napi_get_value_int64</code></a></li>
<li><a href="#all_n-api_napi_get_value_string_latin1"><code>napi_get_value_string_latin1</code></a></li>
<li><a href="#all_n-api_napi_get_value_string_utf8"><code>napi_get_value_string_utf8</code></a></li>
<li><a href="#all_n-api_napi_get_value_string_utf16"><code>napi_get_value_string_utf16</code></a></li>
<li><a href="#all_n-api_napi_get_value_uint32"><code>napi_get_value_uint32</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_functions-to-get-global-instances">Functions to get global instances</a>
<ul>
<li><a href="#all_n-api_napi_get_boolean"><code>napi_get_boolean</code></a></li>
<li><a href="#all_n-api_napi_get_global"><code>napi_get_global</code></a></li>
<li><a href="#all_n-api_napi_get_null"><code>napi_get_null</code></a></li>
<li><a href="#all_n-api_napi_get_undefined"><code>napi_get_undefined</code></a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_n-api_working-with-javascript-values-and-abstract-operations">Working with JavaScript values and abstract operations</a>
<ul>
<li><a href="#all_n-api_napi_coerce_to_bool"><code>napi_coerce_to_bool</code></a></li>
<li><a href="#all_n-api_napi_coerce_to_number"><code>napi_coerce_to_number</code></a></li>
<li><a href="#all_n-api_napi_coerce_to_object"><code>napi_coerce_to_object</code></a></li>
<li><a href="#all_n-api_napi_coerce_to_string"><code>napi_coerce_to_string</code></a></li>
<li><a href="#all_n-api_napi_typeof"><code>napi_typeof</code></a></li>
<li><a href="#all_n-api_napi_instanceof"><code>napi_instanceof</code></a></li>
<li><a href="#all_n-api_napi_is_array"><code>napi_is_array</code></a></li>
<li><a href="#all_n-api_napi_is_arraybuffer"><code>napi_is_arraybuffer</code></a></li>
<li><a href="#all_n-api_napi_is_buffer"><code>napi_is_buffer</code></a></li>
<li><a href="#all_n-api_napi_is_date"><code>napi_is_date</code></a></li>
<li><a href="#all_n-api_napi_is_error_1"><code>napi_is_error</code></a></li>
<li><a href="#all_n-api_napi_is_typedarray"><code>napi_is_typedarray</code></a></li>
<li><a href="#all_n-api_napi_is_dataview"><code>napi_is_dataview</code></a></li>
<li><a href="#all_n-api_napi_strict_equals"><code>napi_strict_equals</code></a></li>
<li><a href="#all_n-api_napi_detach_arraybuffer"><code>napi_detach_arraybuffer</code></a></li>
<li><a href="#all_n-api_napi_is_detached_arraybuffer"><code>napi_is_detached_arraybuffer</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_working-with-javascript-properties">Working with JavaScript properties</a>
<ul>
<li><a href="#all_n-api_structures">Structures</a>
<ul>
<li><a href="#all_n-api_napi_property_attributes"><code>napi_property_attributes</code></a></li>
<li><a href="#all_n-api_napi_property_descriptor"><code>napi_property_descriptor</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_functions">Functions</a>
<ul>
<li><a href="#all_n-api_napi_get_property_names"><code>napi_get_property_names</code></a></li>
<li><a href="#all_n-api_napi_get_all_property_names"><code>napi_get_all_property_names</code></a></li>
<li><a href="#all_n-api_napi_set_property"><code>napi_set_property</code></a></li>
<li><a href="#all_n-api_napi_get_property"><code>napi_get_property</code></a></li>
<li><a href="#all_n-api_napi_has_property"><code>napi_has_property</code></a></li>
<li><a href="#all_n-api_napi_delete_property"><code>napi_delete_property</code></a></li>
<li><a href="#all_n-api_napi_has_own_property"><code>napi_has_own_property</code></a></li>
<li><a href="#all_n-api_napi_set_named_property"><code>napi_set_named_property</code></a></li>
<li><a href="#all_n-api_napi_get_named_property"><code>napi_get_named_property</code></a></li>
<li><a href="#all_n-api_napi_has_named_property"><code>napi_has_named_property</code></a></li>
<li><a href="#all_n-api_napi_set_element"><code>napi_set_element</code></a></li>
<li><a href="#all_n-api_napi_get_element"><code>napi_get_element</code></a></li>
<li><a href="#all_n-api_napi_has_element"><code>napi_has_element</code></a></li>
<li><a href="#all_n-api_napi_delete_element"><code>napi_delete_element</code></a></li>
<li><a href="#all_n-api_napi_define_properties"><code>napi_define_properties</code></a></li>
<li><a href="#all_n-api_napi_object_freeze"><code>napi_object_freeze</code></a></li>
<li><a href="#all_n-api_napi_object_seal"><code>napi_object_seal</code></a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_n-api_working-with-javascript-functions">Working with JavaScript functions</a>
<ul>
<li><a href="#all_n-api_napi_call_function"><code>napi_call_function</code></a></li>
<li><a href="#all_n-api_napi_create_function"><code>napi_create_function</code></a></li>
<li><a href="#all_n-api_napi_get_cb_info"><code>napi_get_cb_info</code></a></li>
<li><a href="#all_n-api_napi_get_new_target"><code>napi_get_new_target</code></a></li>
<li><a href="#all_n-api_napi_new_instance"><code>napi_new_instance</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_object-wrap">Object wrap</a>
<ul>
<li><a href="#all_n-api_napi_define_class"><code>napi_define_class</code></a></li>
<li><a href="#all_n-api_napi_wrap"><code>napi_wrap</code></a></li>
<li><a href="#all_n-api_napi_unwrap"><code>napi_unwrap</code></a></li>
<li><a href="#all_n-api_napi_remove_wrap"><code>napi_remove_wrap</code></a></li>
<li><a href="#all_n-api_napi_type_tag_object"><code>napi_type_tag_object</code></a></li>
<li><a href="#all_n-api_napi_check_object_type_tag"><code>napi_check_object_type_tag</code></a></li>
<li><a href="#all_n-api_napi_add_finalizer"><code>napi_add_finalizer</code></a>
<ul>
<li><span class="stability_1"><a href="#all_n-api_node_api_post_finalizer"><code>node_api_post_finalizer</code></a></span></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_n-api_simple-asynchronous-operations">Simple asynchronous operations</a>
<ul>
<li><a href="#all_n-api_napi_create_async_work"><code>napi_create_async_work</code></a></li>
<li><a href="#all_n-api_napi_delete_async_work"><code>napi_delete_async_work</code></a></li>
<li><a href="#all_n-api_napi_queue_async_work"><code>napi_queue_async_work</code></a></li>
<li><a href="#all_n-api_napi_cancel_async_work"><code>napi_cancel_async_work</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_custom-asynchronous-operations">Custom asynchronous operations</a>
<ul>
<li><a href="#all_n-api_napi_async_init"><code>napi_async_init</code></a></li>
<li><a href="#all_n-api_napi_async_destroy"><code>napi_async_destroy</code></a></li>
<li><a href="#all_n-api_napi_make_callback"><code>napi_make_callback</code></a></li>
<li><a href="#all_n-api_napi_open_callback_scope"><code>napi_open_callback_scope</code></a></li>
<li><a href="#all_n-api_napi_close_callback_scope"><code>napi_close_callback_scope</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_version-management">Version management</a>
<ul>
<li><a href="#all_n-api_napi_get_node_version"><code>napi_get_node_version</code></a></li>
<li><a href="#all_n-api_napi_get_version"><code>napi_get_version</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_memory-management">Memory management</a>
<ul>
<li><a href="#all_n-api_napi_adjust_external_memory"><code>napi_adjust_external_memory</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_promises">Promises</a>
<ul>
<li><a href="#all_n-api_napi_create_promise"><code>napi_create_promise</code></a></li>
<li><a href="#all_n-api_napi_resolve_deferred"><code>napi_resolve_deferred</code></a></li>
<li><a href="#all_n-api_napi_reject_deferred"><code>napi_reject_deferred</code></a></li>
<li><a href="#all_n-api_napi_is_promise"><code>napi_is_promise</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_script-execution">Script execution</a>
<ul>
<li><a href="#all_n-api_napi_run_script"><code>napi_run_script</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_libuv-event-loop">libuv event loop</a>
<ul>
<li><a href="#all_n-api_napi_get_uv_event_loop"><code>napi_get_uv_event_loop</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_asynchronous-thread-safe-function-calls">Asynchronous thread-safe function calls</a>
<ul>
<li><a href="#all_n-api_calling-a-thread-safe-function">Calling a thread-safe function</a></li>
<li><a href="#all_n-api_reference-counting-of-thread-safe-functions">Reference counting of thread-safe functions</a></li>
<li><a href="#all_n-api_deciding-whether-to-keep-the-process-running">Deciding whether to keep the process running</a></li>
<li><a href="#all_n-api_napi_create_threadsafe_function"><code>napi_create_threadsafe_function</code></a></li>
<li><a href="#all_n-api_napi_get_threadsafe_function_context"><code>napi_get_threadsafe_function_context</code></a></li>
<li><a href="#all_n-api_napi_call_threadsafe_function"><code>napi_call_threadsafe_function</code></a></li>
<li><a href="#all_n-api_napi_acquire_threadsafe_function"><code>napi_acquire_threadsafe_function</code></a></li>
<li><a href="#all_n-api_napi_release_threadsafe_function"><code>napi_release_threadsafe_function</code></a></li>
<li><a href="#all_n-api_napi_ref_threadsafe_function"><code>napi_ref_threadsafe_function</code></a></li>
<li><a href="#all_n-api_napi_unref_threadsafe_function"><code>napi_unref_threadsafe_function</code></a></li>
</ul>
</li>
<li><a href="#all_n-api_miscellaneous-utilities">Miscellaneous utilities</a>
<ul>
<li><a href="#all_n-api_node_api_get_module_file_name"><code>node_api_get_module_file_name</code></a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_embedding_c-embedder-api">C++ embedder API</a>
<ul>
<li><a href="#all_embedding_example-embedding-application">Example embedding application</a>
<ul>
<li><a href="#all_embedding_setting-up-per-process-state">Setting up per-process state</a></li>
<li><a href="#all_embedding_per-instance-state">Per-instance state</a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_child_process_child-process">Child process</a></span>
<ul>
<li><a href="#all_child_process_asynchronous-process-creation">Asynchronous process creation</a>
<ul>
<li><a href="#all_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="#all_child_process_child_processexeccommand-options-callback"><code>child_process.exec(command[, options][, callback])</code></a></li>
<li><a href="#all_child_process_child_processexecfilefile-args-options-callback"><code>child_process.execFile(file[, args][, options][, callback])</code></a></li>
<li><a href="#all_child_process_child_processforkmodulepath-args-options"><code>child_process.fork(modulePath[, args][, options])</code></a></li>
<li><a href="#all_child_process_child_processspawncommand-args-options"><code>child_process.spawn(command[, args][, options])</code></a>
<ul>
<li><a href="#all_child_process_optionsdetached"><code>options.detached</code></a></li>
<li><a href="#all_child_process_optionsstdio"><code>options.stdio</code></a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_child_process_synchronous-process-creation">Synchronous process creation</a>
<ul>
<li><a href="#all_child_process_child_processexecfilesyncfile-args-options"><code>child_process.execFileSync(file[, args][, options])</code></a></li>
<li><a href="#all_child_process_child_processexecsynccommand-options"><code>child_process.execSync(command[, options])</code></a></li>
<li><a href="#all_child_process_child_processspawnsynccommand-args-options"><code>child_process.spawnSync(command[, args][, options])</code></a></li>
</ul>
</li>
<li><a href="#all_child_process_class-childprocess">Class: <code>ChildProcess</code></a>
<ul>
<li><a href="#all_child_process_event-close">Event: <code>'close'</code></a></li>
<li><a href="#all_child_process_event-disconnect">Event: <code>'disconnect'</code></a></li>
<li><a href="#all_child_process_event-error">Event: <code>'error'</code></a></li>
<li><a href="#all_child_process_event-exit">Event: <code>'exit'</code></a></li>
<li><a href="#all_child_process_event-message">Event: <code>'message'</code></a></li>
<li><a href="#all_child_process_event-spawn">Event: <code>'spawn'</code></a></li>
<li><a href="#all_child_process_subprocesschannel"><code>subprocess.channel</code></a>
<ul>
<li><a href="#all_child_process_subprocesschannelref"><code>subprocess.channel.ref()</code></a></li>
<li><a href="#all_child_process_subprocesschannelunref"><code>subprocess.channel.unref()</code></a></li>
</ul>
</li>
<li><a href="#all_child_process_subprocessconnected"><code>subprocess.connected</code></a></li>
<li><a href="#all_child_process_subprocessdisconnect"><code>subprocess.disconnect()</code></a></li>
<li><a href="#all_child_process_subprocessexitcode"><code>subprocess.exitCode</code></a></li>
<li><a href="#all_child_process_subprocesskillsignal"><code>subprocess.kill([signal])</code></a></li>
<li><span class="stability_1"><a href="#all_child_process_subprocesssymboldispose"><code>subprocess[Symbol.dispose]()</code></a></span></li>
<li><a href="#all_child_process_subprocesskilled"><code>subprocess.killed</code></a></li>
<li><a href="#all_child_process_subprocesspid"><code>subprocess.pid</code></a></li>
<li><a href="#all_child_process_subprocessref"><code>subprocess.ref()</code></a></li>
<li><a href="#all_child_process_subprocesssendmessage-sendhandle-options-callback"><code>subprocess.send(message[, sendHandle[, options]][, callback])</code></a>
<ul>
<li><a href="#all_child_process_example-sending-a-server-object">Example: sending a server object</a></li>
<li><a href="#all_child_process_example-sending-a-socket-object">Example: sending a socket object</a></li>
</ul>
</li>
<li><a href="#all_child_process_subprocesssignalcode"><code>subprocess.signalCode</code></a></li>
<li><a href="#all_child_process_subprocessspawnargs"><code>subprocess.spawnargs</code></a></li>
<li><a href="#all_child_process_subprocessspawnfile"><code>subprocess.spawnfile</code></a></li>
<li><a href="#all_child_process_subprocessstderr"><code>subprocess.stderr</code></a></li>
<li><a href="#all_child_process_subprocessstdin"><code>subprocess.stdin</code></a></li>
<li><a href="#all_child_process_subprocessstdio"><code>subprocess.stdio</code></a></li>
<li><a href="#all_child_process_subprocessstdout"><code>subprocess.stdout</code></a></li>
<li><a href="#all_child_process_subprocessunref"><code>subprocess.unref()</code></a></li>
</ul>
</li>
<li><a href="#all_child_process_maxbuffer-and-unicode"><code>maxBuffer</code> and Unicode</a></li>
<li><a href="#all_child_process_shell-requirements">Shell requirements</a></li>
<li><a href="#all_child_process_default-windows-shell">Default Windows shell</a></li>
<li><a href="#all_child_process_advanced-serialization">Advanced serialization</a></li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_cluster_cluster">Cluster</a></span>
<ul>
<li><a href="#all_cluster_how-it-works">How it works</a></li>
<li><a href="#all_cluster_class-worker">Class: <code>Worker</code></a>
<ul>
<li><a href="#all_cluster_event-disconnect">Event: <code>'disconnect'</code></a></li>
<li><a href="#all_cluster_event-error">Event: <code>'error'</code></a></li>
<li><a href="#all_cluster_event-exit">Event: <code>'exit'</code></a></li>
<li><a href="#all_cluster_event-listening">Event: <code>'listening'</code></a></li>
<li><a href="#all_cluster_event-message">Event: <code>'message'</code></a></li>
<li><a href="#all_cluster_event-online">Event: <code>'online'</code></a></li>
<li><a href="#all_cluster_workerdisconnect"><code>worker.disconnect()</code></a></li>
<li><a href="#all_cluster_workerexitedafterdisconnect"><code>worker.exitedAfterDisconnect</code></a></li>
<li><a href="#all_cluster_workerid"><code>worker.id</code></a></li>
<li><a href="#all_cluster_workerisconnected"><code>worker.isConnected()</code></a></li>
<li><a href="#all_cluster_workerisdead"><code>worker.isDead()</code></a></li>
<li><a href="#all_cluster_workerkillsignal"><code>worker.kill([signal])</code></a></li>
<li><a href="#all_cluster_workerprocess"><code>worker.process</code></a></li>
<li><a href="#all_cluster_workersendmessage-sendhandle-options-callback"><code>worker.send(message[, sendHandle[, options]][, callback])</code></a></li>
</ul>
</li>
<li><a href="#all_cluster_event-disconnect_1">Event: <code>'disconnect'</code></a></li>
<li><a href="#all_cluster_event-exit_1">Event: <code>'exit'</code></a></li>
<li><a href="#all_cluster_event-fork">Event: <code>'fork'</code></a></li>
<li><a href="#all_cluster_event-listening_1">Event: <code>'listening'</code></a></li>
<li><a href="#all_cluster_event-message_1">Event: <code>'message'</code></a></li>
<li><a href="#all_cluster_event-online_1">Event: <code>'online'</code></a></li>
<li><a href="#all_cluster_event-setup">Event: <code>'setup'</code></a></li>
<li><a href="#all_cluster_clusterdisconnectcallback"><code>cluster.disconnect([callback])</code></a></li>
<li><a href="#all_cluster_clusterforkenv"><code>cluster.fork([env])</code></a></li>
<li><span class="stability_0"><a href="#all_cluster_clusterismaster"><code>cluster.isMaster</code></a></span></li>
<li><a href="#all_cluster_clusterisprimary"><code>cluster.isPrimary</code></a></li>
<li><a href="#all_cluster_clusterisworker"><code>cluster.isWorker</code></a></li>
<li><a href="#all_cluster_clusterschedulingpolicy"><code>cluster.schedulingPolicy</code></a></li>
<li><a href="#all_cluster_clustersettings"><code>cluster.settings</code></a></li>
<li><span class="stability_0"><a href="#all_cluster_clustersetupmastersettings"><code>cluster.setupMaster([settings])</code></a></span></li>
<li><a href="#all_cluster_clustersetupprimarysettings"><code>cluster.setupPrimary([settings])</code></a></li>
<li><a href="#all_cluster_clusterworker"><code>cluster.worker</code></a></li>
<li><a href="#all_cluster_clusterworkers"><code>cluster.workers</code></a></li>
</ul>
</li>
<li><a href="#all_cli_command-line-api">Command-line API</a>
<ul>
<li><a href="#all_cli_synopsis">Synopsis</a></li>
<li><a href="#all_cli_program-entry-point">Program entry point</a>
<ul>
<li><a href="#all_cli_ecmascript-modules-loader-entry-point-caveat">ECMAScript modules loader entry point caveat</a></li>
</ul>
</li>
<li><a href="#all_cli_options">Options</a>
<ul>
<li><a href="#all_cli_-"><code>-</code></a></li>
<li><a href="#all_cli_--"><code>--</code></a></li>
<li><a href="#all_cli_--abort-on-uncaught-exception"><code>--abort-on-uncaught-exception</code></a></li>
<li><span class="stability_1"><a href="#all_cli_--allow-addons"><code>--allow-addons</code></a></span></li>
<li><span class="stability_1"><a href="#all_cli_--allow-child-process"><code>--allow-child-process</code></a></span></li>
<li><span class="stability_1"><a href="#all_cli_--allow-fs-read"><code>--allow-fs-read</code></a></span></li>
<li><span class="stability_1"><a href="#all_cli_--allow-fs-write"><code>--allow-fs-write</code></a></span></li>
<li><span class="stability_1"><a href="#all_cli_--allow-wasi"><code>--allow-wasi</code></a></span></li>
<li><span class="stability_1"><a href="#all_cli_--allow-worker"><code>--allow-worker</code></a></span></li>
<li><span class="stability_1"><a href="#all_cli_--build-snapshot"><code>--build-snapshot</code></a></span></li>
<li><span class="stability_1"><a href="#all_cli_--build-snapshot-config"><code>--build-snapshot-config</code></a></span></li>
<li><a href="#all_cli_-c---check"><code>-c</code>, <code>--check</code></a></li>
<li><a href="#all_cli_--completion-bash"><code>--completion-bash</code></a></li>
<li><span class="stability_2"><a href="#all_cli_-c-condition---conditionscondition"><code>-C condition</code>, <code>--conditions=condition</code></a></span></li>
<li><span class="stability_2"><a href="#all_cli_--cpu-prof"><code>--cpu-prof</code></a></span></li>
<li><span class="stability_2"><a href="#all_cli_--cpu-prof-dir"><code>--cpu-prof-dir</code></a></span></li>
<li><span class="stability_2"><a href="#all_cli_--cpu-prof-interval"><code>--cpu-prof-interval</code></a></span></li>
<li><span class="stability_2"><a href="#all_cli_--cpu-prof-name"><code>--cpu-prof-name</code></a></span></li>
<li><a href="#all_cli_--diagnostic-dirdirectory"><code>--diagnostic-dir=directory</code></a></li>
<li><span class="stability_1"><a href="#all_cli_--disable-warningcode-or-type"><code>--disable-warning=code-or-type</code></a></span></li>
<li><a href="#all_cli_--disable-wasm-trap-handler"><code>--disable-wasm-trap-handler</code></a></li>
<li><a href="#all_cli_--disable-protomode"><code>--disable-proto=mode</code></a></li>
<li><a href="#all_cli_--disallow-code-generation-from-strings"><code>--disallow-code-generation-from-strings</code></a></li>
<li><span class="stability_1"><a href="#all_cli_--expose-gc"><code>--expose-gc</code></a></span></li>
<li><a href="#all_cli_--dns-result-orderorder"><code>--dns-result-order=order</code></a></li>
<li><a href="#all_cli_--enable-fips"><code>--enable-fips</code></a></li>
<li><a href="#all_cli_--enable-source-maps"><code>--enable-source-maps</code></a></li>
<li><span class="stability_1"><a href="#all_cli_--env-fileconfig"><code>--env-file=config</code></a></span></li>
<li><a href="#all_cli_-e---eval-script"><code>-e</code>, <code>--eval "script"</code></a></li>
<li><span class="stability_1"><a href="#all_cli_--experimental-default-typetype"><code>--experimental-default-type=type</code></a></span></li>
<li><span class="stability_1"><a href="#all_cli_--experimental-detect-module"><code>--experimental-detect-module</code></a></span></li>
<li><a href="#all_cli_--experimental-eventsource"><code>--experimental-eventsource</code></a></li>
<li><a href="#all_cli_--experimental-import-meta-resolve"><code>--experimental-import-meta-resolve</code></a></li>
<li><a href="#all_cli_--experimental-loadermodule"><code>--experimental-loader=module</code></a></li>
<li><span class="stability_1"><a href="#all_cli_--experimental-network-imports"><code>--experimental-network-imports</code></a></span></li>
<li><span class="stability_1"><a href="#all_cli_--experimental-network-inspection"><code>--experimental-network-inspection</code></a></span></li>
<li><span class="stability_1"><a href="#all_cli_--experimental-permission"><code>--experimental-permission</code></a></span></li>
<li><span class="stability_0"><a href="#all_cli_--experimental-policy"><code>--experimental-policy</code></a></span></li>
<li><span class="stability_1"><a href="#all_cli_--experimental-require-module"><code>--experimental-require-module</code></a></span></li>
<li><span class="stability_1"><a href="#all_cli_--experimental-sea-config"><code>--experimental-sea-config</code></a></span></li>
<li><a href="#all_cli_--experimental-shadow-realm"><code>--experimental-shadow-realm</code></a></li>
<li><a href="#all_cli_--experimental-test-coverage"><code>--experimental-test-coverage</code></a></li>
<li><span class="stability_1"><a href="#all_cli_--experimental-test-module-mocks"><code>--experimental-test-module-mocks</code></a></span></li>
<li><a href="#all_cli_--experimental-vm-modules"><code>--experimental-vm-modules</code></a></li>
<li><a href="#all_cli_--experimental-wasi-unstable-preview1"><code>--experimental-wasi-unstable-preview1</code></a></li>
<li><a href="#all_cli_--experimental-wasm-modules"><code>--experimental-wasm-modules</code></a></li>
<li><a href="#all_cli_--experimental-websocket"><code>--experimental-websocket</code></a></li>
<li><a href="#all_cli_--force-context-aware"><code>--force-context-aware</code></a></li>
<li><a href="#all_cli_--force-fips"><code>--force-fips</code></a></li>
<li><a href="#all_cli_--force-node-api-uncaught-exceptions-policy"><code>--force-node-api-uncaught-exceptions-policy</code></a></li>
<li><span class="stability_1"><a href="#all_cli_--frozen-intrinsics"><code>--frozen-intrinsics</code></a></span></li>
<li><span class="stability_2"><a href="#all_cli_--heap-prof"><code>--heap-prof</code></a></span></li>
<li><span class="stability_2"><a href="#all_cli_--heap-prof-dir"><code>--heap-prof-dir</code></a></span></li>
<li><span class="stability_2"><a href="#all_cli_--heap-prof-interval"><code>--heap-prof-interval</code></a></span></li>
<li><span class="stability_2"><a href="#all_cli_--heap-prof-name"><code>--heap-prof-name</code></a></span></li>
<li><span class="stability_1"><a href="#all_cli_--heapsnapshot-near-heap-limitmax_count"><code>--heapsnapshot-near-heap-limit=max_count</code></a></span></li>
<li><a href="#all_cli_--heapsnapshot-signalsignal"><code>--heapsnapshot-signal=signal</code></a></li>
<li><a href="#all_cli_-h---help"><code>-h</code>, <code>--help</code></a></li>
<li><a href="#all_cli_--icu-data-dirfile"><code>--icu-data-dir=file</code></a></li>
<li><span class="stability_1"><a href="#all_cli_--importmodule"><code>--import=module</code></a></span></li>
<li><a href="#all_cli_--input-typetype"><code>--input-type=type</code></a></li>
<li><a href="#all_cli_--insecure-http-parser"><code>--insecure-http-parser</code></a></li>
<li><a href="#all_cli_--inspecthostport"><code>--inspect[=[host:]port]</code></a>
<ul>
<li><a href="#all_cli_warning-binding-inspector-to-a-public-ipport-combination-is-insecure">Warning: binding inspector to a public IP:port combination is insecure</a></li>
</ul>
</li>
<li><a href="#all_cli_--inspect-brkhostport"><code>--inspect-brk[=[host:]port]</code></a></li>
<li><a href="#all_cli_--inspect-porthostport"><code>--inspect-port=[host:]port</code></a></li>
<li><a href="#all_cli_--inspect-publish-uidstderrhttp"><code>--inspect-publish-uid=stderr,http</code></a></li>
<li><a href="#all_cli_--inspect-waithostport"><code>--inspect-wait[=[host:]port]</code></a></li>
<li><a href="#all_cli_-i---interactive"><code>-i</code>, <code>--interactive</code></a></li>
<li><span class="stability_1"><a href="#all_cli_--jitless"><code>--jitless</code></a></span></li>
<li><a href="#all_cli_--max-http-header-sizesize"><code>--max-http-header-size=size</code></a></li>
<li><a href="#all_cli_--napi-modules"><code>--napi-modules</code></a></li>
<li><a href="#all_cli_--network-family-autoselection-attempt-timeout"><code>--network-family-autoselection-attempt-timeout</code></a></li>
<li><a href="#all_cli_--no-addons"><code>--no-addons</code></a></li>
<li><a href="#all_cli_--no-deprecation"><code>--no-deprecation</code></a></li>
<li><a href="#all_cli_--no-experimental-fetch"><code>--no-experimental-fetch</code></a></li>
<li><a href="#all_cli_--no-experimental-global-customevent"><code>--no-experimental-global-customevent</code></a></li>
<li><a href="#all_cli_--no-experimental-global-webcrypto"><code>--no-experimental-global-webcrypto</code></a></li>
<li><a href="#all_cli_--no-experimental-repl-await"><code>--no-experimental-repl-await</code></a></li>
<li><a href="#all_cli_--no-extra-info-on-fatal-exception"><code>--no-extra-info-on-fatal-exception</code></a></li>
<li><a href="#all_cli_--no-force-async-hooks-checks"><code>--no-force-async-hooks-checks</code></a></li>
<li><a href="#all_cli_--no-global-search-paths"><code>--no-global-search-paths</code></a></li>
<li><a href="#all_cli_--no-network-family-autoselection"><code>--no-network-family-autoselection</code></a></li>
<li><a href="#all_cli_--no-warnings"><code>--no-warnings</code></a></li>
<li><a href="#all_cli_--node-memory-debug"><code>--node-memory-debug</code></a></li>
<li><a href="#all_cli_--openssl-configfile"><code>--openssl-config=file</code></a></li>
<li><a href="#all_cli_--openssl-legacy-provider"><code>--openssl-legacy-provider</code></a></li>
<li><a href="#all_cli_--openssl-shared-config"><code>--openssl-shared-config</code></a></li>
<li><a href="#all_cli_--pending-deprecation"><code>--pending-deprecation</code></a></li>
<li><span class="stability_0"><a href="#all_cli_--policy-integritysri"><code>--policy-integrity=sri</code></a></span></li>
<li><a href="#all_cli_--preserve-symlinks"><code>--preserve-symlinks</code></a></li>
<li><a href="#all_cli_--preserve-symlinks-main"><code>--preserve-symlinks-main</code></a></li>
<li><a href="#all_cli_-p---print-script"><code>-p</code>, <code>--print "script"</code></a></li>
<li><a href="#all_cli_--experimental-print-required-tla"><code>--experimental-print-required-tla</code></a></li>
<li><a href="#all_cli_--prof"><code>--prof</code></a></li>
<li><a href="#all_cli_--prof-process"><code>--prof-process</code></a></li>
<li><a href="#all_cli_--redirect-warningsfile"><code>--redirect-warnings=file</code></a></li>
<li><a href="#all_cli_--report-compact"><code>--report-compact</code></a></li>
<li><a href="#all_cli_--report-dirdirectory-report-directorydirectory"><code>--report-dir=directory</code>, <code>report-directory=directory</code></a></li>
<li><a href="#all_cli_--report-filenamefilename"><code>--report-filename=filename</code></a></li>
<li><a href="#all_cli_--report-on-fatalerror"><code>--report-on-fatalerror</code></a></li>
<li><a href="#all_cli_--report-on-signal"><code>--report-on-signal</code></a></li>
<li><a href="#all_cli_--report-signalsignal"><code>--report-signal=signal</code></a></li>
<li><a href="#all_cli_--report-uncaught-exception"><code>--report-uncaught-exception</code></a></li>
<li><a href="#all_cli_--report-exclude-network"><code>--report-exclude-network</code></a></li>
<li><a href="#all_cli_-r---require-module"><code>-r</code>, <code>--require module</code></a></li>
<li><a href="#all_cli_--secure-heapn"><code>--secure-heap=n</code></a></li>
<li><a href="#all_cli_--secure-heap-minn"><code>--secure-heap-min=n</code></a></li>
<li><span class="stability_1"><a href="#all_cli_--snapshot-blobpath"><code>--snapshot-blob=path</code></a></span></li>
<li><a href="#all_cli_--test"><code>--test</code></a></li>
<li><a href="#all_cli_--test-concurrency"><code>--test-concurrency</code></a></li>
<li><span class="stability_1"><a href="#all_cli_--test-coverage-exclude"><code>--test-coverage-exclude</code></a></span></li>
<li><span class="stability_1"><a href="#all_cli_--test-coverage-include"><code>--test-coverage-include</code></a></span></li>
<li><a href="#all_cli_--test-force-exit"><code>--test-force-exit</code></a></li>
<li><a href="#all_cli_--test-name-pattern"><code>--test-name-pattern</code></a></li>
<li><a href="#all_cli_--test-only"><code>--test-only</code></a></li>
<li><a href="#all_cli_--test-reporter"><code>--test-reporter</code></a></li>
<li><a href="#all_cli_--test-reporter-destination"><code>--test-reporter-destination</code></a></li>
<li><a href="#all_cli_--test-shard"><code>--test-shard</code></a></li>
<li><a href="#all_cli_--test-timeout"><code>--test-timeout</code></a></li>
<li><a href="#all_cli_--throw-deprecation"><code>--throw-deprecation</code></a></li>
<li><a href="#all_cli_--titletitle"><code>--title=title</code></a></li>
<li><a href="#all_cli_--tls-cipher-listlist"><code>--tls-cipher-list=list</code></a></li>
<li><a href="#all_cli_--tls-keylogfile"><code>--tls-keylog=file</code></a></li>
<li><a href="#all_cli_--tls-max-v12"><code>--tls-max-v1.2</code></a></li>
<li><a href="#all_cli_--tls-max-v13"><code>--tls-max-v1.3</code></a></li>
<li><a href="#all_cli_--tls-min-v10"><code>--tls-min-v1.0</code></a></li>
<li><a href="#all_cli_--tls-min-v11"><code>--tls-min-v1.1</code></a></li>
<li><a href="#all_cli_--tls-min-v12"><code>--tls-min-v1.2</code></a></li>
<li><a href="#all_cli_--tls-min-v13"><code>--tls-min-v1.3</code></a></li>
<li><span class="stability_0"><a href="#all_cli_--trace-atomics-wait"><code>--trace-atomics-wait</code></a></span></li>
<li><a href="#all_cli_--trace-deprecation"><code>--trace-deprecation</code></a></li>
<li><a href="#all_cli_--trace-event-categories"><code>--trace-event-categories</code></a></li>
<li><a href="#all_cli_--trace-event-file-pattern"><code>--trace-event-file-pattern</code></a></li>
<li><a href="#all_cli_--trace-events-enabled"><code>--trace-events-enabled</code></a></li>
<li><a href="#all_cli_--trace-exit"><code>--trace-exit</code></a></li>
<li><a href="#all_cli_--trace-sigint"><code>--trace-sigint</code></a></li>
<li><a href="#all_cli_--trace-sync-io"><code>--trace-sync-io</code></a></li>
<li><a href="#all_cli_--trace-tls"><code>--trace-tls</code></a></li>
<li><a href="#all_cli_--trace-uncaught"><code>--trace-uncaught</code></a></li>
<li><a href="#all_cli_--trace-warnings"><code>--trace-warnings</code></a></li>
<li><a href="#all_cli_--track-heap-objects"><code>--track-heap-objects</code></a></li>
<li><a href="#all_cli_--unhandled-rejectionsmode"><code>--unhandled-rejections=mode</code></a></li>
<li><a href="#all_cli_--use-bundled-ca---use-openssl-ca"><code>--use-bundled-ca</code>, <code>--use-openssl-ca</code></a></li>
<li><a href="#all_cli_--use-largepagesmode"><code>--use-largepages=mode</code></a></li>
<li><a href="#all_cli_--v8-options"><code>--v8-options</code></a></li>
<li><a href="#all_cli_--v8-pool-sizenum"><code>--v8-pool-size=num</code></a></li>
<li><a href="#all_cli_-v---version"><code>-v</code>, <code>--version</code></a></li>
<li><span class="stability_2"><a href="#all_cli_--watch"><code>--watch</code></a></span></li>
<li><span class="stability_2"><a href="#all_cli_--watch-path"><code>--watch-path</code></a></span></li>
<li><a href="#all_cli_--watch-preserve-output"><code>--watch-preserve-output</code></a></li>
<li><a href="#all_cli_--zero-fill-buffers"><code>--zero-fill-buffers</code></a></li>
</ul>
</li>
<li><a href="#all_cli_environment-variables">Environment variables</a>
<ul>
<li><a href="#all_cli_force_color1-2-3"><code>FORCE_COLOR=[1, 2, 3]</code></a></li>
<li><a href="#all_cli_no_colorany"><code>NO_COLOR=&#x3C;any></code></a></li>
<li><a href="#all_cli_node_debugmodule"><code>NODE_DEBUG=module[,…]</code></a></li>
<li><a href="#all_cli_node_debug_nativemodule"><code>NODE_DEBUG_NATIVE=module[,…]</code></a></li>
<li><a href="#all_cli_node_disable_colors1"><code>NODE_DISABLE_COLORS=1</code></a></li>
<li><a href="#all_cli_node_extra_ca_certsfile"><code>NODE_EXTRA_CA_CERTS=file</code></a></li>
<li><a href="#all_cli_node_icu_datafile"><code>NODE_ICU_DATA=file</code></a></li>
<li><a href="#all_cli_node_no_warnings1"><code>NODE_NO_WARNINGS=1</code></a></li>
<li><a href="#all_cli_node_optionsoptions"><code>NODE_OPTIONS=options...</code></a></li>
<li><a href="#all_cli_node_pathpath"><code>NODE_PATH=path[:…]</code></a></li>
<li><a href="#all_cli_node_pending_deprecation1"><code>NODE_PENDING_DEPRECATION=1</code></a></li>
<li><a href="#all_cli_node_pending_pipe_instancesinstances"><code>NODE_PENDING_PIPE_INSTANCES=instances</code></a></li>
<li><a href="#all_cli_node_preserve_symlinks1"><code>NODE_PRESERVE_SYMLINKS=1</code></a></li>
<li><a href="#all_cli_node_redirect_warningsfile"><code>NODE_REDIRECT_WARNINGS=file</code></a></li>
<li><a href="#all_cli_node_repl_external_modulefile"><code>NODE_REPL_EXTERNAL_MODULE=file</code></a></li>
<li><a href="#all_cli_node_repl_historyfile"><code>NODE_REPL_HISTORY=file</code></a></li>
<li><a href="#all_cli_node_skip_platform_checkvalue"><code>NODE_SKIP_PLATFORM_CHECK=value</code></a></li>
<li><a href="#all_cli_node_test_contextvalue"><code>NODE_TEST_CONTEXT=value</code></a></li>
<li><a href="#all_cli_node_tls_reject_unauthorizedvalue"><code>NODE_TLS_REJECT_UNAUTHORIZED=value</code></a></li>
<li><a href="#all_cli_node_v8_coveragedir"><code>NODE_V8_COVERAGE=dir</code></a>
<ul>
<li><a href="#all_cli_coverage-output">Coverage output</a></li>
<li><span class="stability_1"><a href="#all_cli_source-map-cache">Source map cache</a></span></li>
</ul>
</li>
<li><a href="#all_cli_openssl_conffile"><code>OPENSSL_CONF=file</code></a></li>
<li><a href="#all_cli_ssl_cert_dirdir"><code>SSL_CERT_DIR=dir</code></a></li>
<li><a href="#all_cli_ssl_cert_filefile"><code>SSL_CERT_FILE=file</code></a></li>
<li><a href="#all_cli_tz"><code>TZ</code></a></li>
<li><a href="#all_cli_uv_threadpool_sizesize"><code>UV_THREADPOOL_SIZE=size</code></a></li>
<li><a href="#all_cli_uv_use_io_uringvalue"><code>UV_USE_IO_URING=value</code></a></li>
</ul>
</li>
<li><a href="#all_cli_useful-v8-options">Useful V8 options</a>
<ul>
<li><a href="#all_cli_--abort-on-uncaught-exception_1"><code>--abort-on-uncaught-exception</code></a></li>
<li><a href="#all_cli_--disallow-code-generation-from-strings_1"><code>--disallow-code-generation-from-strings</code></a></li>
<li><a href="#all_cli_--enable-etw-stack-walking"><code>--enable-etw-stack-walking</code></a></li>
<li><a href="#all_cli_--expose-gc_1"><code>--expose-gc</code></a></li>
<li><a href="#all_cli_--harmony-shadow-realm"><code>--harmony-shadow-realm</code></a></li>
<li><a href="#all_cli_--huge-max-old-generation-size"><code>--huge-max-old-generation-size</code></a></li>
<li><a href="#all_cli_--jitless_1"><code>--jitless</code></a></li>
<li><a href="#all_cli_--interpreted-frames-native-stack"><code>--interpreted-frames-native-stack</code></a></li>
<li><a href="#all_cli_--prof_1"><code>--prof</code></a></li>
<li><a href="#all_cli_--perf-basic-prof"><code>--perf-basic-prof</code></a></li>
<li><a href="#all_cli_--perf-basic-prof-only-functions"><code>--perf-basic-prof-only-functions</code></a></li>
<li><a href="#all_cli_--perf-prof"><code>--perf-prof</code></a></li>
<li><a href="#all_cli_--perf-prof-unwinding-info"><code>--perf-prof-unwinding-info</code></a></li>
<li><a href="#all_cli_--max-old-space-sizesize-in-mib"><code>--max-old-space-size=SIZE</code> (in MiB)</a></li>
<li><a href="#all_cli_--max-semi-space-sizesize-in-mib"><code>--max-semi-space-size=SIZE</code> (in MiB)</a></li>
<li><a href="#all_cli_--security-revert"><code>--security-revert</code></a></li>
<li><a href="#all_cli_--stack-trace-limitlimit"><code>--stack-trace-limit=limit</code></a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_console_console">Console</a></span>
<ul>
<li><a href="#all_console_class-console">Class: <code>Console</code></a>
<ul>
<li><a href="#all_console_new-consolestdout-stderr-ignoreerrors"><code>new Console(stdout[, stderr][, ignoreErrors])</code></a></li>
<li><a href="#all_console_new-consoleoptions"><code>new Console(options)</code></a></li>
<li><a href="#all_console_consoleassertvalue-message"><code>console.assert(value[, ...message])</code></a></li>
<li><a href="#all_console_consoleclear"><code>console.clear()</code></a></li>
<li><a href="#all_console_consolecountlabel"><code>console.count([label])</code></a></li>
<li><a href="#all_console_consolecountresetlabel"><code>console.countReset([label])</code></a></li>
<li><a href="#all_console_consoledebugdata-args"><code>console.debug(data[, ...args])</code></a></li>
<li><a href="#all_console_consoledirobj-options"><code>console.dir(obj[, options])</code></a></li>
<li><a href="#all_console_consoledirxmldata"><code>console.dirxml(...data)</code></a></li>
<li><a href="#all_console_consoleerrordata-args"><code>console.error([data][, ...args])</code></a></li>
<li><a href="#all_console_consolegrouplabel"><code>console.group([...label])</code></a></li>
<li><a href="#all_console_consolegroupcollapsed"><code>console.groupCollapsed()</code></a></li>
<li><a href="#all_console_consolegroupend"><code>console.groupEnd()</code></a></li>
<li><a href="#all_console_consoleinfodata-args"><code>console.info([data][, ...args])</code></a></li>
<li><a href="#all_console_consolelogdata-args"><code>console.log([data][, ...args])</code></a></li>
<li><a href="#all_console_consoletabletabulardata-properties"><code>console.table(tabularData[, properties])</code></a></li>
<li><a href="#all_console_consoletimelabel"><code>console.time([label])</code></a></li>
<li><a href="#all_console_consoletimeendlabel"><code>console.timeEnd([label])</code></a></li>
<li><a href="#all_console_consoletimeloglabel-data"><code>console.timeLog([label][, ...data])</code></a></li>
<li><a href="#all_console_consoletracemessage-args"><code>console.trace([message][, ...args])</code></a></li>
<li><a href="#all_console_consolewarndata-args"><code>console.warn([data][, ...args])</code></a></li>
</ul>
</li>
<li><a href="#all_console_inspector-only-methods">Inspector only methods</a>
<ul>
<li><a href="#all_console_consoleprofilelabel"><code>console.profile([label])</code></a></li>
<li><a href="#all_console_consoleprofileendlabel"><code>console.profileEnd([label])</code></a></li>
<li><a href="#all_console_consoletimestamplabel"><code>console.timeStamp([label])</code></a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_corepack_corepack">Corepack</a>
<ul>
<li><a href="#all_corepack_workflows">Workflows</a>
<ul>
<li><a href="#all_corepack_enabling-the-feature">Enabling the feature</a></li>
<li><a href="#all_corepack_configuring-a-package">Configuring a package</a></li>
<li><a href="#all_corepack_upgrading-the-global-versions">Upgrading the global versions</a></li>
<li><a href="#all_corepack_offline-workflow">Offline workflow</a></li>
</ul>
</li>
<li><a href="#all_corepack_supported-package-managers">Supported package managers</a></li>
<li><a href="#all_corepack_common-questions">Common questions</a>
<ul>
<li><a href="#all_corepack_how-does-corepack-interact-with-npm">How does Corepack interact with npm?</a></li>
<li><a href="#all_corepack_running-npm-install--g-yarn-doesnt-work">Running <code>npm install -g yarn</code> doesn't work</a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_crypto_crypto">Crypto</a></span>
<ul>
<li><a href="#all_crypto_determining-if-crypto-support-is-unavailable">Determining if crypto support is unavailable</a></li>
<li><a href="#all_crypto_class-certificate">Class: <code>Certificate</code></a>
<ul>
<li><a href="#all_crypto_static-method-certificateexportchallengespkac-encoding">Static method: <code>Certificate.exportChallenge(spkac[, encoding])</code></a></li>
<li><a href="#all_crypto_static-method-certificateexportpublickeyspkac-encoding">Static method: <code>Certificate.exportPublicKey(spkac[, encoding])</code></a></li>
<li><a href="#all_crypto_static-method-certificateverifyspkacspkac-encoding">Static method: <code>Certificate.verifySpkac(spkac[, encoding])</code></a></li>
<li><span class="stability_0"><a href="#all_crypto_legacy-api">Legacy API</a></span>
<ul>
<li><a href="#all_crypto_new-cryptocertificate"><code>new crypto.Certificate()</code></a></li>
<li><a href="#all_crypto_certificateexportchallengespkac-encoding"><code>certificate.exportChallenge(spkac[, encoding])</code></a></li>
<li><a href="#all_crypto_certificateexportpublickeyspkac-encoding"><code>certificate.exportPublicKey(spkac[, encoding])</code></a></li>
<li><a href="#all_crypto_certificateverifyspkacspkac-encoding"><code>certificate.verifySpkac(spkac[, encoding])</code></a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_crypto_class-cipher">Class: <code>Cipher</code></a>
<ul>
<li><a href="#all_crypto_cipherfinaloutputencoding"><code>cipher.final([outputEncoding])</code></a></li>
<li><a href="#all_crypto_ciphergetauthtag"><code>cipher.getAuthTag()</code></a></li>
<li><a href="#all_crypto_ciphersetaadbuffer-options"><code>cipher.setAAD(buffer[, options])</code></a></li>
<li><a href="#all_crypto_ciphersetautopaddingautopadding"><code>cipher.setAutoPadding([autoPadding])</code></a></li>
<li><a href="#all_crypto_cipherupdatedata-inputencoding-outputencoding"><code>cipher.update(data[, inputEncoding][, outputEncoding])</code></a></li>
</ul>
</li>
<li><a href="#all_crypto_class-decipher">Class: <code>Decipher</code></a>
<ul>
<li><a href="#all_crypto_decipherfinaloutputencoding"><code>decipher.final([outputEncoding])</code></a></li>
<li><a href="#all_crypto_deciphersetaadbuffer-options"><code>decipher.setAAD(buffer[, options])</code></a></li>
<li><a href="#all_crypto_deciphersetauthtagbuffer-encoding"><code>decipher.setAuthTag(buffer[, encoding])</code></a></li>
<li><a href="#all_crypto_deciphersetautopaddingautopadding"><code>decipher.setAutoPadding([autoPadding])</code></a></li>
<li><a href="#all_crypto_decipherupdatedata-inputencoding-outputencoding"><code>decipher.update(data[, inputEncoding][, outputEncoding])</code></a></li>
</ul>
</li>
<li><a href="#all_crypto_class-diffiehellman">Class: <code>DiffieHellman</code></a>
<ul>
<li><a href="#all_crypto_diffiehellmancomputesecretotherpublickey-inputencoding-outputencoding"><code>diffieHellman.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])</code></a></li>
<li><a href="#all_crypto_diffiehellmangeneratekeysencoding"><code>diffieHellman.generateKeys([encoding])</code></a></li>
<li><a href="#all_crypto_diffiehellmangetgeneratorencoding"><code>diffieHellman.getGenerator([encoding])</code></a></li>
<li><a href="#all_crypto_diffiehellmangetprimeencoding"><code>diffieHellman.getPrime([encoding])</code></a></li>
<li><a href="#all_crypto_diffiehellmangetprivatekeyencoding"><code>diffieHellman.getPrivateKey([encoding])</code></a></li>
<li><a href="#all_crypto_diffiehellmangetpublickeyencoding"><code>diffieHellman.getPublicKey([encoding])</code></a></li>
<li><a href="#all_crypto_diffiehellmansetprivatekeyprivatekey-encoding"><code>diffieHellman.setPrivateKey(privateKey[, encoding])</code></a></li>
<li><a href="#all_crypto_diffiehellmansetpublickeypublickey-encoding"><code>diffieHellman.setPublicKey(publicKey[, encoding])</code></a></li>
<li><a href="#all_crypto_diffiehellmanverifyerror"><code>diffieHellman.verifyError</code></a></li>
</ul>
</li>
<li><a href="#all_crypto_class-diffiehellmangroup">Class: <code>DiffieHellmanGroup</code></a></li>
<li><a href="#all_crypto_class-ecdh">Class: <code>ECDH</code></a>
<ul>
<li><a href="#all_crypto_static-method-ecdhconvertkeykey-curve-inputencoding-outputencoding-format">Static method: <code>ECDH.convertKey(key, curve[, inputEncoding[, outputEncoding[, format]]])</code></a></li>
<li><a href="#all_crypto_ecdhcomputesecretotherpublickey-inputencoding-outputencoding"><code>ecdh.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])</code></a></li>
<li><a href="#all_crypto_ecdhgeneratekeysencoding-format"><code>ecdh.generateKeys([encoding[, format]])</code></a></li>
<li><a href="#all_crypto_ecdhgetprivatekeyencoding"><code>ecdh.getPrivateKey([encoding])</code></a></li>
<li><a href="#all_crypto_ecdhgetpublickeyencoding-format"><code>ecdh.getPublicKey([encoding][, format])</code></a></li>
<li><a href="#all_crypto_ecdhsetprivatekeyprivatekey-encoding"><code>ecdh.setPrivateKey(privateKey[, encoding])</code></a></li>
<li><span class="stability_0"><a href="#all_crypto_ecdhsetpublickeypublickey-encoding"><code>ecdh.setPublicKey(publicKey[, encoding])</code></a></span></li>
</ul>
</li>
<li><a href="#all_crypto_class-hash">Class: <code>Hash</code></a>
<ul>
<li><a href="#all_crypto_hashcopyoptions"><code>hash.copy([options])</code></a></li>
<li><a href="#all_crypto_hashdigestencoding"><code>hash.digest([encoding])</code></a></li>
<li><a href="#all_crypto_hashupdatedata-inputencoding"><code>hash.update(data[, inputEncoding])</code></a></li>
</ul>
</li>
<li><a href="#all_crypto_class-hmac">Class: <code>Hmac</code></a>
<ul>
<li><a href="#all_crypto_hmacdigestencoding"><code>hmac.digest([encoding])</code></a></li>
<li><a href="#all_crypto_hmacupdatedata-inputencoding"><code>hmac.update(data[, inputEncoding])</code></a></li>
</ul>
</li>
<li><a href="#all_crypto_class-keyobject">Class: <code>KeyObject</code></a>
<ul>
<li><a href="#all_crypto_static-method-keyobjectfromkey">Static method: <code>KeyObject.from(key)</code></a></li>
<li><a href="#all_crypto_keyobjectasymmetrickeydetails"><code>keyObject.asymmetricKeyDetails</code></a></li>
<li><a href="#all_crypto_keyobjectasymmetrickeytype"><code>keyObject.asymmetricKeyType</code></a></li>
<li><a href="#all_crypto_keyobjectexportoptions"><code>keyObject.export([options])</code></a></li>
<li><a href="#all_crypto_keyobjectequalsotherkeyobject"><code>keyObject.equals(otherKeyObject)</code></a></li>
<li><a href="#all_crypto_keyobjectsymmetrickeysize"><code>keyObject.symmetricKeySize</code></a></li>
<li><a href="#all_crypto_keyobjecttype"><code>keyObject.type</code></a></li>
</ul>
</li>
<li><a href="#all_crypto_class-sign">Class: <code>Sign</code></a>
<ul>
<li><a href="#all_crypto_signsignprivatekey-outputencoding"><code>sign.sign(privateKey[, outputEncoding])</code></a></li>
<li><a href="#all_crypto_signupdatedata-inputencoding"><code>sign.update(data[, inputEncoding])</code></a></li>
</ul>
</li>
<li><a href="#all_crypto_class-verify">Class: <code>Verify</code></a>
<ul>
<li><a href="#all_crypto_verifyupdatedata-inputencoding"><code>verify.update(data[, inputEncoding])</code></a></li>
<li><a href="#all_crypto_verifyverifyobject-signature-signatureencoding"><code>verify.verify(object, signature[, signatureEncoding])</code></a></li>
</ul>
</li>
<li><a href="#all_crypto_class-x509certificate">Class: <code>X509Certificate</code></a>
<ul>
<li><a href="#all_crypto_new-x509certificatebuffer"><code>new X509Certificate(buffer)</code></a></li>
<li><a href="#all_crypto_x509ca"><code>x509.ca</code></a></li>
<li><a href="#all_crypto_x509checkemailemail-options"><code>x509.checkEmail(email[, options])</code></a></li>
<li><a href="#all_crypto_x509checkhostname-options"><code>x509.checkHost(name[, options])</code></a></li>
<li><a href="#all_crypto_x509checkipip"><code>x509.checkIP(ip)</code></a></li>
<li><a href="#all_crypto_x509checkissuedothercert"><code>x509.checkIssued(otherCert)</code></a></li>
<li><a href="#all_crypto_x509checkprivatekeyprivatekey"><code>x509.checkPrivateKey(privateKey)</code></a></li>
<li><a href="#all_crypto_x509fingerprint"><code>x509.fingerprint</code></a></li>
<li><a href="#all_crypto_x509fingerprint256"><code>x509.fingerprint256</code></a></li>
<li><a href="#all_crypto_x509fingerprint512"><code>x509.fingerprint512</code></a></li>
<li><a href="#all_crypto_x509infoaccess"><code>x509.infoAccess</code></a></li>
<li><a href="#all_crypto_x509issuer"><code>x509.issuer</code></a></li>
<li><a href="#all_crypto_x509issuercertificate"><code>x509.issuerCertificate</code></a></li>
<li><a href="#all_crypto_x509extkeyusage"><code>x509.extKeyUsage</code></a></li>
<li><a href="#all_crypto_x509publickey"><code>x509.publicKey</code></a></li>
<li><a href="#all_crypto_x509raw"><code>x509.raw</code></a></li>
<li><a href="#all_crypto_x509serialnumber"><code>x509.serialNumber</code></a></li>
<li><a href="#all_crypto_x509subject"><code>x509.subject</code></a></li>
<li><a href="#all_crypto_x509subjectaltname"><code>x509.subjectAltName</code></a></li>
<li><a href="#all_crypto_x509tojson"><code>x509.toJSON()</code></a></li>
<li><a href="#all_crypto_x509tolegacyobject"><code>x509.toLegacyObject()</code></a></li>
<li><a href="#all_crypto_x509tostring"><code>x509.toString()</code></a></li>
<li><a href="#all_crypto_x509validfrom"><code>x509.validFrom</code></a></li>
<li><a href="#all_crypto_x509validto"><code>x509.validTo</code></a></li>
<li><a href="#all_crypto_x509verifypublickey"><code>x509.verify(publicKey)</code></a></li>
</ul>
</li>
<li><a href="#all_crypto_nodecrypto-module-methods-and-properties"><code>node:crypto</code> module methods and properties</a>
<ul>
<li><a href="#all_crypto_cryptoconstants"><code>crypto.constants</code></a></li>
<li><span class="stability_0"><a href="#all_crypto_cryptofips"><code>crypto.fips</code></a></span></li>
<li><a href="#all_crypto_cryptocheckprimecandidate-options-callback"><code>crypto.checkPrime(candidate[, options], callback)</code></a></li>
<li><a href="#all_crypto_cryptocheckprimesynccandidate-options"><code>crypto.checkPrimeSync(candidate[, options])</code></a></li>
<li><span class="stability_0"><a href="#all_crypto_cryptocreatecipheralgorithm-password-options"><code>crypto.createCipher(algorithm, password[, options])</code></a></span></li>
<li><a href="#all_crypto_cryptocreatecipherivalgorithm-key-iv-options"><code>crypto.createCipheriv(algorithm, key, iv[, options])</code></a></li>
<li><span class="stability_0"><a href="#all_crypto_cryptocreatedecipheralgorithm-password-options"><code>crypto.createDecipher(algorithm, password[, options])</code></a></span></li>
<li><a href="#all_crypto_cryptocreatedecipherivalgorithm-key-iv-options"><code>crypto.createDecipheriv(algorithm, key, iv[, options])</code></a></li>
<li><a href="#all_crypto_cryptocreatediffiehellmanprime-primeencoding-generator-generatorencoding"><code>crypto.createDiffieHellman(prime[, primeEncoding][, generator][, generatorEncoding])</code></a></li>
<li><a href="#all_crypto_cryptocreatediffiehellmanprimelength-generator"><code>crypto.createDiffieHellman(primeLength[, generator])</code></a></li>
<li><a href="#all_crypto_cryptocreatediffiehellmangroupname"><code>crypto.createDiffieHellmanGroup(name)</code></a></li>
<li><a href="#all_crypto_cryptocreateecdhcurvename"><code>crypto.createECDH(curveName)</code></a></li>
<li><a href="#all_crypto_cryptocreatehashalgorithm-options"><code>crypto.createHash(algorithm[, options])</code></a></li>
<li><a href="#all_crypto_cryptocreatehmacalgorithm-key-options"><code>crypto.createHmac(algorithm, key[, options])</code></a></li>
<li><a href="#all_crypto_cryptocreateprivatekeykey"><code>crypto.createPrivateKey(key)</code></a></li>
<li><a href="#all_crypto_cryptocreatepublickeykey"><code>crypto.createPublicKey(key)</code></a></li>
<li><a href="#all_crypto_cryptocreatesecretkeykey-encoding"><code>crypto.createSecretKey(key[, encoding])</code></a></li>
<li><a href="#all_crypto_cryptocreatesignalgorithm-options"><code>crypto.createSign(algorithm[, options])</code></a></li>
<li><a href="#all_crypto_cryptocreateverifyalgorithm-options"><code>crypto.createVerify(algorithm[, options])</code></a></li>
<li><a href="#all_crypto_cryptodiffiehellmanoptions"><code>crypto.diffieHellman(options)</code></a></li>
<li><span class="stability_1"><a href="#all_crypto_cryptohashalgorithm-data-outputencoding"><code>crypto.hash(algorithm, data[, outputEncoding])</code></a></span></li>
<li><a href="#all_crypto_cryptogeneratekeytype-options-callback"><code>crypto.generateKey(type, options, callback)</code></a></li>
<li><a href="#all_crypto_cryptogeneratekeypairtype-options-callback"><code>crypto.generateKeyPair(type, options, callback)</code></a></li>
<li><a href="#all_crypto_cryptogeneratekeypairsynctype-options"><code>crypto.generateKeyPairSync(type, options)</code></a></li>
<li><a href="#all_crypto_cryptogeneratekeysynctype-options"><code>crypto.generateKeySync(type, options)</code></a></li>
<li><a href="#all_crypto_cryptogenerateprimesize-options-callback"><code>crypto.generatePrime(size[, options[, callback]])</code></a></li>
<li><a href="#all_crypto_cryptogenerateprimesyncsize-options"><code>crypto.generatePrimeSync(size[, options])</code></a></li>
<li><a href="#all_crypto_cryptogetcipherinfonameornid-options"><code>crypto.getCipherInfo(nameOrNid[, options])</code></a></li>
<li><a href="#all_crypto_cryptogetciphers"><code>crypto.getCiphers()</code></a></li>
<li><a href="#all_crypto_cryptogetcurves"><code>crypto.getCurves()</code></a></li>
<li><a href="#all_crypto_cryptogetdiffiehellmangroupname"><code>crypto.getDiffieHellman(groupName)</code></a></li>
<li><a href="#all_crypto_cryptogetfips"><code>crypto.getFips()</code></a></li>
<li><a href="#all_crypto_cryptogethashes"><code>crypto.getHashes()</code></a></li>
<li><a href="#all_crypto_cryptogetrandomvaluestypedarray"><code>crypto.getRandomValues(typedArray)</code></a></li>
<li><a href="#all_crypto_cryptohkdfdigest-ikm-salt-info-keylen-callback"><code>crypto.hkdf(digest, ikm, salt, info, keylen, callback)</code></a></li>
<li><a href="#all_crypto_cryptohkdfsyncdigest-ikm-salt-info-keylen"><code>crypto.hkdfSync(digest, ikm, salt, info, keylen)</code></a></li>
<li><a href="#all_crypto_cryptopbkdf2password-salt-iterations-keylen-digest-callback"><code>crypto.pbkdf2(password, salt, iterations, keylen, digest, callback)</code></a></li>
<li><a href="#all_crypto_cryptopbkdf2syncpassword-salt-iterations-keylen-digest"><code>crypto.pbkdf2Sync(password, salt, iterations, keylen, digest)</code></a></li>
<li><a href="#all_crypto_cryptoprivatedecryptprivatekey-buffer"><code>crypto.privateDecrypt(privateKey, buffer)</code></a></li>
<li><a href="#all_crypto_cryptoprivateencryptprivatekey-buffer"><code>crypto.privateEncrypt(privateKey, buffer)</code></a></li>
<li><a href="#all_crypto_cryptopublicdecryptkey-buffer"><code>crypto.publicDecrypt(key, buffer)</code></a></li>
<li><a href="#all_crypto_cryptopublicencryptkey-buffer"><code>crypto.publicEncrypt(key, buffer)</code></a></li>
<li><a href="#all_crypto_cryptorandombytessize-callback"><code>crypto.randomBytes(size[, callback])</code></a></li>
<li><a href="#all_crypto_cryptorandomfillsyncbuffer-offset-size"><code>crypto.randomFillSync(buffer[, offset][, size])</code></a></li>
<li><a href="#all_crypto_cryptorandomfillbuffer-offset-size-callback"><code>crypto.randomFill(buffer[, offset][, size], callback)</code></a></li>
<li><a href="#all_crypto_cryptorandomintmin-max-callback"><code>crypto.randomInt([min, ]max[, callback])</code></a></li>
<li><a href="#all_crypto_cryptorandomuuidoptions"><code>crypto.randomUUID([options])</code></a></li>
<li><a href="#all_crypto_cryptoscryptpassword-salt-keylen-options-callback"><code>crypto.scrypt(password, salt, keylen[, options], callback)</code></a></li>
<li><a href="#all_crypto_cryptoscryptsyncpassword-salt-keylen-options"><code>crypto.scryptSync(password, salt, keylen[, options])</code></a></li>
<li><a href="#all_crypto_cryptosecureheapused"><code>crypto.secureHeapUsed()</code></a></li>
<li><a href="#all_crypto_cryptosetengineengine-flags"><code>crypto.setEngine(engine[, flags])</code></a></li>
<li><a href="#all_crypto_cryptosetfipsbool"><code>crypto.setFips(bool)</code></a></li>
<li><a href="#all_crypto_cryptosignalgorithm-data-key-callback"><code>crypto.sign(algorithm, data, key[, callback])</code></a></li>
<li><a href="#all_crypto_cryptosubtle"><code>crypto.subtle</code></a></li>
<li><a href="#all_crypto_cryptotimingsafeequala-b"><code>crypto.timingSafeEqual(a, b)</code></a></li>
<li><a href="#all_crypto_cryptoverifyalgorithm-data-key-signature-callback"><code>crypto.verify(algorithm, data, key, signature[, callback])</code></a></li>
<li><a href="#all_crypto_cryptowebcrypto"><code>crypto.webcrypto</code></a></li>
</ul>
</li>
<li><a href="#all_crypto_notes">Notes</a>
<ul>
<li><a href="#all_crypto_using-strings-as-inputs-to-cryptographic-apis">Using strings as inputs to cryptographic APIs</a></li>
<li><a href="#all_crypto_legacy-streams-api-prior-to-nodejs-010">Legacy streams API (prior to Node.js 0.10)</a></li>
<li><a href="#all_crypto_support-for-weak-or-compromised-algorithms">Support for weak or compromised algorithms</a></li>
<li><a href="#all_crypto_ccm-mode">CCM mode</a></li>
<li><a href="#all_crypto_fips-mode">FIPS mode</a></li>
</ul>
</li>
<li><a href="#all_crypto_crypto-constants">Crypto constants</a>
<ul>
<li><a href="#all_crypto_openssl-options">OpenSSL options</a></li>
<li><a href="#all_crypto_openssl-engine-constants">OpenSSL engine constants</a></li>
<li><a href="#all_crypto_other-openssl-constants">Other OpenSSL constants</a></li>
<li><a href="#all_crypto_nodejs-crypto-constants">Node.js crypto constants</a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_debugger_debugger">Debugger</a></span>
<ul>
<li><a href="#all_debugger_watchers">Watchers</a></li>
<li><a href="#all_debugger_command-reference">Command reference</a>
<ul>
<li><a href="#all_debugger_stepping">Stepping</a></li>
<li><a href="#all_debugger_breakpoints">Breakpoints</a></li>
<li><a href="#all_debugger_information">Information</a></li>
<li><a href="#all_debugger_execution-control">Execution control</a></li>
<li><a href="#all_debugger_various">Various</a></li>
</ul>
</li>
<li><a href="#all_debugger_advanced-usage">Advanced usage</a>
<ul>
<li><a href="#all_debugger_v8-inspector-integration-for-nodejs">V8 inspector integration for Node.js</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_deprecations_deprecated-apis">Deprecated APIs</a>
<ul>
<li><a href="#all_deprecations_revoking-deprecations">Revoking deprecations</a></li>
<li><a href="#all_deprecations_list-of-deprecated-apis">List of deprecated APIs</a>
<ul>
<li><a href="#DEP0001">DEP0001: <code>http.OutgoingMessage.prototype.flush</code></a></li>
<li><a href="#DEP0002">DEP0002: <code>require('_linklist')</code></a></li>
<li><a href="#DEP0003">DEP0003: <code>_writableState.buffer</code></a></li>
<li><a href="#DEP0004">DEP0004: <code>CryptoStream.prototype.readyState</code></a></li>
<li><a href="#DEP0005">DEP0005: <code>Buffer()</code> constructor</a></li>
<li><a href="#DEP0006">DEP0006: <code>child_process</code> <code>options.customFds</code></a></li>
<li><a href="#DEP0007">DEP0007: Replace <code>cluster</code> <code>worker.suicide</code> with <code>worker.exitedAfterDisconnect</code></a></li>
<li><a href="#DEP0008">DEP0008: <code>require('node:constants')</code></a></li>
<li><a href="#DEP0009">DEP0009: <code>crypto.pbkdf2</code> without digest</a></li>
<li><a href="#DEP0010">DEP0010: <code>crypto.createCredentials</code></a></li>
<li><a href="#DEP0011">DEP0011: <code>crypto.Credentials</code></a></li>
<li><a href="#DEP0012">DEP0012: <code>Domain.dispose</code></a></li>
<li><a href="#DEP0013">DEP0013: <code>fs</code> asynchronous function without callback</a></li>
<li><a href="#DEP0014">DEP0014: <code>fs.read</code> legacy String interface</a></li>
<li><a href="#DEP0015">DEP0015: <code>fs.readSync</code> legacy String interface</a></li>
<li><a href="#DEP0016">DEP0016: <code>GLOBAL</code>/<code>root</code></a></li>
<li><a href="#DEP0017">DEP0017: <code>Intl.v8BreakIterator</code></a></li>
<li><a href="#DEP0018">DEP0018: Unhandled promise rejections</a></li>
<li><a href="#DEP0019">DEP0019: <code>require('.')</code> resolved outside directory</a></li>
<li><a href="#DEP0020">DEP0020: <code>Server.connections</code></a></li>
<li><a href="#DEP0021">DEP0021: <code>Server.listenFD</code></a></li>
<li><a href="#DEP0022">DEP0022: <code>os.tmpDir()</code></a></li>
<li><a href="#DEP0023">DEP0023: <code>os.getNetworkInterfaces()</code></a></li>
<li><a href="#DEP0024">DEP0024: <code>REPLServer.prototype.convertToContext()</code></a></li>
<li><a href="#DEP0025">DEP0025: <code>require('node:sys')</code></a></li>
<li><a href="#DEP0026">DEP0026: <code>util.print()</code></a></li>
<li><a href="#DEP0027">DEP0027: <code>util.puts()</code></a></li>
<li><a href="#DEP0028">DEP0028: <code>util.debug()</code></a></li>
<li><a href="#DEP0029">DEP0029: <code>util.error()</code></a></li>
<li><a href="#DEP0030">DEP0030: <code>SlowBuffer</code></a></li>
<li><a href="#DEP0031">DEP0031: <code>ecdh.setPublicKey()</code></a></li>
<li><a href="#DEP0032">DEP0032: <code>node:domain</code> module</a></li>
<li><a href="#DEP0033">DEP0033: <code>EventEmitter.listenerCount()</code></a></li>
<li><a href="#DEP0034">DEP0034: <code>fs.exists(path, callback)</code></a></li>
<li><a href="#DEP0035">DEP0035: <code>fs.lchmod(path, mode, callback)</code></a></li>
<li><a href="#DEP0036">DEP0036: <code>fs.lchmodSync(path, mode)</code></a></li>
<li><a href="#DEP0037">DEP0037: <code>fs.lchown(path, uid, gid, callback)</code></a></li>
<li><a href="#DEP0038">DEP0038: <code>fs.lchownSync(path, uid, gid)</code></a></li>
<li><a href="#DEP0039">DEP0039: <code>require.extensions</code></a></li>
<li><a href="#DEP0040">DEP0040: <code>node:punycode</code> module</a></li>
<li><a href="#DEP0041">DEP0041: <code>NODE_REPL_HISTORY_FILE</code> environment variable</a></li>
<li><a href="#DEP0042">DEP0042: <code>tls.CryptoStream</code></a></li>
<li><a href="#DEP0043">DEP0043: <code>tls.SecurePair</code></a></li>
<li><a href="#DEP0044">DEP0044: <code>util.isArray()</code></a></li>
<li><a href="#DEP0045">DEP0045: <code>util.isBoolean()</code></a></li>
<li><a href="#DEP0046">DEP0046: <code>util.isBuffer()</code></a></li>
<li><a href="#DEP0047">DEP0047: <code>util.isDate()</code></a></li>
<li><a href="#DEP0048">DEP0048: <code>util.isError()</code></a></li>
<li><a href="#DEP0049">DEP0049: <code>util.isFunction()</code></a></li>
<li><a href="#DEP0050">DEP0050: <code>util.isNull()</code></a></li>
<li><a href="#DEP0051">DEP0051: <code>util.isNullOrUndefined()</code></a></li>
<li><a href="#DEP0052">DEP0052: <code>util.isNumber()</code></a></li>
<li><a href="#DEP0053">DEP0053: <code>util.isObject()</code></a></li>
<li><a href="#DEP0054">DEP0054: <code>util.isPrimitive()</code></a></li>
<li><a href="#DEP0055">DEP0055: <code>util.isRegExp()</code></a></li>
<li><a href="#DEP0056">DEP0056: <code>util.isString()</code></a></li>
<li><a href="#DEP0057">DEP0057: <code>util.isSymbol()</code></a></li>
<li><a href="#DEP0058">DEP0058: <code>util.isUndefined()</code></a></li>
<li><a href="#DEP0059">DEP0059: <code>util.log()</code></a></li>
<li><a href="#DEP0060">DEP0060: <code>util._extend()</code></a></li>
<li><a href="#DEP0061">DEP0061: <code>fs.SyncWriteStream</code></a></li>
<li><a href="#DEP0062">DEP0062: <code>node --debug</code></a></li>
<li><a href="#DEP0063">DEP0063: <code>ServerResponse.prototype.writeHeader()</code></a></li>
<li><a href="#DEP0064">DEP0064: <code>tls.createSecurePair()</code></a></li>
<li><a href="#DEP0065">DEP0065: <code>repl.REPL_MODE_MAGIC</code> and <code>NODE_REPL_MODE=magic</code></a></li>
<li><a href="#DEP0066">DEP0066: <code>OutgoingMessage.prototype._headers, OutgoingMessage.prototype._headerNames</code></a></li>
<li><a href="#DEP0067">DEP0067: <code>OutgoingMessage.prototype._renderHeaders</code></a></li>
<li><a href="#DEP0068">DEP0068: <code>node debug</code></a></li>
<li><a href="#DEP0069">DEP0069: <code>vm.runInDebugContext(string)</code></a></li>
<li><a href="#DEP0070">DEP0070: <code>async_hooks.currentId()</code></a></li>
<li><a href="#DEP0071">DEP0071: <code>async_hooks.triggerId()</code></a></li>
<li><a href="#DEP0072">DEP0072: <code>async_hooks.AsyncResource.triggerId()</code></a></li>
<li><a href="#DEP0073">DEP0073: Several internal properties of <code>net.Server</code></a></li>
<li><a href="#DEP0074">DEP0074: <code>REPLServer.bufferedCommand</code></a></li>
<li><a href="#DEP0075">DEP0075: <code>REPLServer.parseREPLKeyword()</code></a></li>
<li><a href="#DEP0076">DEP0076: <code>tls.parseCertString()</code></a></li>
<li><a href="#DEP0077">DEP0077: <code>Module._debug()</code></a></li>
<li><a href="#DEP0078">DEP0078: <code>REPLServer.turnOffEditorMode()</code></a></li>
<li><a href="#DEP0079">DEP0079: Custom inspection function on objects via <code>.inspect()</code></a></li>
<li><a href="#DEP0080">DEP0080: <code>path._makeLong()</code></a></li>
<li><a href="#DEP0081">DEP0081: <code>fs.truncate()</code> using a file descriptor</a></li>
<li><a href="#DEP0082">DEP0082: <code>REPLServer.prototype.memory()</code></a></li>
<li><a href="#DEP0083">DEP0083: Disabling ECDH by setting <code>ecdhCurve</code> to <code>false</code></a></li>
<li><a href="#DEP0084">DEP0084: requiring bundled internal dependencies</a></li>
<li><a href="#DEP0085">DEP0085: AsyncHooks sensitive API</a></li>
<li><a href="#DEP0086">DEP0086: Remove <code>runInAsyncIdScope</code></a></li>
<li><a href="#DEP0089">DEP0089: <code>require('node:assert')</code></a></li>
<li><a href="#DEP0090">DEP0090: Invalid GCM authentication tag lengths</a></li>
<li><a href="#DEP0091">DEP0091: <code>crypto.DEFAULT_ENCODING</code></a></li>
<li><a href="#DEP0092">DEP0092: Top-level <code>this</code> bound to <code>module.exports</code></a></li>
<li><a href="#DEP0093">DEP0093: <code>crypto.fips</code> is deprecated and replaced</a></li>
<li><a href="#DEP0094">DEP0094: Using <code>assert.fail()</code> with more than one argument</a></li>
<li><a href="#DEP0095">DEP0095: <code>timers.enroll()</code></a></li>
<li><a href="#DEP0096">DEP0096: <code>timers.unenroll()</code></a></li>
<li><a href="#DEP0097">DEP0097: <code>MakeCallback</code> with <code>domain</code> property</a></li>
<li><a href="#DEP0098">DEP0098: AsyncHooks embedder <code>AsyncResource.emitBefore</code> and <code>AsyncResource.emitAfter</code> APIs</a></li>
<li><a href="#DEP0099">DEP0099: Async context-unaware <code>node::MakeCallback</code> C++ APIs</a></li>
<li><a href="#DEP0100">DEP0100: <code>process.assert()</code></a></li>
<li><a href="#DEP0101">DEP0101: <code>--with-lttng</code></a></li>
<li><a href="#DEP0102">DEP0102: Using <code>noAssert</code> in <code>Buffer#(read|write)</code> operations</a></li>
<li><a href="#DEP0103">DEP0103: <code>process.binding('util').is[...]</code> typechecks</a></li>
<li><a href="#DEP0104">DEP0104: <code>process.env</code> string coercion</a></li>
<li><a href="#DEP0105">DEP0105: <code>decipher.finaltol</code></a></li>
<li><a href="#DEP0106">DEP0106: <code>crypto.createCipher</code> and <code>crypto.createDecipher</code></a></li>
<li><a href="#DEP0107">DEP0107: <code>tls.convertNPNProtocols()</code></a></li>
<li><a href="#DEP0108">DEP0108: <code>zlib.bytesRead</code></a></li>
<li><a href="#DEP0109">DEP0109: <code>http</code>, <code>https</code>, and <code>tls</code> support for invalid URLs</a></li>
<li><a href="#DEP0110">DEP0110: <code>vm.Script</code> cached data</a></li>
<li><a href="#DEP0111">DEP0111: <code>process.binding()</code></a></li>
<li><a href="#DEP0112">DEP0112: <code>dgram</code> private APIs</a></li>
<li><a href="#DEP0113">DEP0113: <code>Cipher.setAuthTag()</code>, <code>Decipher.getAuthTag()</code></a></li>
<li><a href="#DEP0114">DEP0114: <code>crypto._toBuf()</code></a></li>
<li><a href="#DEP0115">DEP0115: <code>crypto.prng()</code>, <code>crypto.pseudoRandomBytes()</code>, <code>crypto.rng()</code></a></li>
<li><a href="#DEP0116">DEP0116: Legacy URL API</a></li>
<li><a href="#DEP0117">DEP0117: Native crypto handles</a></li>
<li><a href="#DEP0118">DEP0118: <code>dns.lookup()</code> support for a falsy host name</a></li>
<li><a href="#DEP0119">DEP0119: <code>process.binding('uv').errname()</code> private API</a></li>
<li><a href="#DEP0120">DEP0120: Windows Performance Counter support</a></li>
<li><a href="#DEP0121">DEP0121: <code>net._setSimultaneousAccepts()</code></a></li>
<li><a href="#DEP0122">DEP0122: <code>tls</code> <code>Server.prototype.setOptions()</code></a></li>
<li><a href="#DEP0123">DEP0123: setting the TLS ServerName to an IP address</a></li>
<li><a href="#DEP0124">DEP0124: using <code>REPLServer.rli</code></a></li>
<li><a href="#DEP0125">DEP0125: <code>require('node:_stream_wrap')</code></a></li>
<li><a href="#DEP0126">DEP0126: <code>timers.active()</code></a></li>
<li><a href="#DEP0127">DEP0127: <code>timers._unrefActive()</code></a></li>
<li><a href="#DEP0128">DEP0128: modules with an invalid <code>main</code> entry and an <code>index.js</code> file</a></li>
<li><a href="#DEP0129">DEP0129: <code>ChildProcess._channel</code></a></li>
<li><a href="#DEP0130">DEP0130: <code>Module.createRequireFromPath()</code></a></li>
<li><a href="#DEP0131">DEP0131: Legacy HTTP parser</a></li>
<li><a href="#DEP0132">DEP0132: <code>worker.terminate()</code> with callback</a></li>
<li><a href="#DEP0133">DEP0133: <code>http</code> <code>connection</code></a></li>
<li><a href="#DEP0134">DEP0134: <code>process._tickCallback</code></a></li>
<li><a href="#DEP0135">DEP0135: <code>WriteStream.open()</code> and <code>ReadStream.open()</code> are internal</a></li>
<li><a href="#DEP0136">DEP0136: <code>http</code> <code>finished</code></a></li>
<li><a href="#DEP0137">DEP0137: Closing fs.FileHandle on garbage collection</a></li>
<li><a href="#DEP0138">DEP0138: <code>process.mainModule</code></a></li>
<li><a href="#DEP0139">DEP0139: <code>process.umask()</code> with no arguments</a></li>
<li><a href="#DEP0140">DEP0140: Use <code>request.destroy()</code> instead of <code>request.abort()</code></a></li>
<li><a href="#DEP0141">DEP0141: <code>repl.inputStream</code> and <code>repl.outputStream</code></a></li>
<li><a href="#DEP0142">DEP0142: <code>repl._builtinLibs</code></a></li>
<li><a href="#DEP0143">DEP0143: <code>Transform._transformState</code></a></li>
<li><a href="#DEP0144">DEP0144: <code>module.parent</code></a></li>
<li><a href="#DEP0145">DEP0145: <code>socket.bufferSize</code></a></li>
<li><a href="#DEP0146">DEP0146: <code>new crypto.Certificate()</code></a></li>
<li><a href="#DEP0147">DEP0147: <code>fs.rmdir(path, { recursive: true })</code></a></li>
<li><a href="#DEP0148">DEP0148: Folder mappings in <code>"exports"</code> (trailing <code>"/"</code>)</a></li>
<li><a href="#DEP0149">DEP0149: <code>http.IncomingMessage#connection</code></a></li>
<li><a href="#DEP0150">DEP0150: Changing the value of <code>process.config</code></a></li>
<li><a href="#DEP0151">DEP0151: Main index lookup and extension searching</a></li>
<li><a href="#DEP0152">DEP0152: Extension PerformanceEntry properties</a></li>
<li><a href="#DEP0153">DEP0153: <code>dns.lookup</code> and <code>dnsPromises.lookup</code> options type coercion</a></li>
<li><a href="#DEP0154">DEP0154: RSA-PSS generate key pair options</a></li>
<li><a href="#DEP0155">DEP0155: Trailing slashes in pattern specifier resolutions</a></li>
<li><a href="#DEP0156">DEP0156: <code>.aborted</code> property and <code>'abort'</code>, <code>'aborted'</code> event in <code>http</code></a></li>
<li><a href="#DEP0157">DEP0157: Thenable support in streams</a></li>
<li><a href="#DEP0158">DEP0158: <code>buffer.slice(start, end)</code></a></li>
<li><a href="#DEP0159">DEP0159: <code>ERR_INVALID_CALLBACK</code></a></li>
<li><a href="#DEP0160">DEP0160: <code>process.on('multipleResolves', handler)</code></a></li>
<li><a href="#DEP0161">DEP0161: <code>process._getActiveRequests()</code> and <code>process._getActiveHandles()</code></a></li>
<li><a href="#DEP0162">DEP0162: <code>fs.write()</code>, <code>fs.writeFileSync()</code> coercion to string</a></li>
<li><a href="#DEP0163">DEP0163: <code>channel.subscribe(onMessage)</code>, <code>channel.unsubscribe(onMessage)</code></a></li>
<li><a href="#DEP0164">DEP0164: <code>process.exit(code)</code>, <code>process.exitCode</code> coercion to integer</a></li>
<li><a href="#DEP0165">DEP0165: <code>--trace-atomics-wait</code></a></li>
<li><a href="#DEP0166">DEP0166: Double slashes in imports and exports targets</a></li>
<li><a href="#DEP0167">DEP0167: Weak <code>DiffieHellmanGroup</code> instances (<code>modp1</code>, <code>modp2</code>, <code>modp5</code>)</a></li>
<li><a href="#DEP0168">DEP0168: Unhandled exception in Node-API callbacks</a></li>
<li><a href="#DEP0169">DEP0169: Insecure url.parse()</a></li>
<li><a href="#DEP0170">DEP0170: Invalid port when using <code>url.parse()</code></a></li>
<li><a href="#DEP0171">DEP0171: Setters for <code>http.IncomingMessage</code> headers and trailers</a></li>
<li><a href="#DEP0172">DEP0172: The <code>asyncResource</code> property of <code>AsyncResource</code> bound functions</a></li>
<li><a href="#DEP0173">DEP0173: the <code>assert.CallTracker</code> class</a></li>
<li><a href="#DEP0174">DEP0174: calling <code>promisify</code> on a function that returns a <code>Promise</code></a></li>
<li><a href="#DEP0175">DEP0175: <code>util.toUSVString</code></a></li>
<li><a href="#DEP0176">DEP0176: <code>fs.F_OK</code>, <code>fs.R_OK</code>, <code>fs.W_OK</code>, <code>fs.X_OK</code></a></li>
<li><a href="#DEP0177">DEP0177: <code>util.types.isWebAssemblyCompiledModule</code></a></li>
<li><a href="#DEP0178">DEP0178: <code>dirent.path</code></a></li>
<li><a href="#DEP0179">DEP0179: <code>Hash</code> constructor</a></li>
<li><a href="#DEP0180">DEP0180: <code>fs.Stats</code> constructor</a></li>
<li><a href="#DEP0181">DEP0181: <code>Hmac</code> constructor</a></li>
<li><a href="#DEP0182">DEP0182: Short GCM authentication tags without explicit <code>authTagLength</code></a></li>
<li><a href="#DEP0183">DEP0183: OpenSSL engine-based APIs</a></li>
<li><a href="#DEP0184">DEP0184: Instantiating <code>node:zlib</code> classes without <code>new</code></a></li>
<li><a href="#DEP0185">DEP0185: Instantiating <code>node:repl</code> classes without <code>new</code></a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_diagnostics_channel_diagnostics-channel">Diagnostics Channel</a></span>
<ul>
<li><a href="#all_diagnostics_channel_public-api">Public API</a>
<ul>
<li><a href="#all_diagnostics_channel_overview">Overview</a>
<ul>
<li><a href="#all_diagnostics_channel_diagnostics_channelhassubscribersname"><code>diagnostics_channel.hasSubscribers(name)</code></a></li>
<li><a href="#all_diagnostics_channel_diagnostics_channelchannelname"><code>diagnostics_channel.channel(name)</code></a></li>
<li><a href="#all_diagnostics_channel_diagnostics_channelsubscribename-onmessage"><code>diagnostics_channel.subscribe(name, onMessage)</code></a></li>
<li><a href="#all_diagnostics_channel_diagnostics_channelunsubscribename-onmessage"><code>diagnostics_channel.unsubscribe(name, onMessage)</code></a></li>
<li><span class="stability_1"><a href="#all_diagnostics_channel_diagnostics_channeltracingchannelnameorchannels"><code>diagnostics_channel.tracingChannel(nameOrChannels)</code></a></span></li>
</ul>
</li>
<li><a href="#all_diagnostics_channel_class-channel">Class: <code>Channel</code></a>
<ul>
<li><a href="#all_diagnostics_channel_channelhassubscribers"><code>channel.hasSubscribers</code></a></li>
<li><a href="#all_diagnostics_channel_channelpublishmessage"><code>channel.publish(message)</code></a></li>
<li><span class="stability_0"><a href="#all_diagnostics_channel_channelsubscribeonmessage"><code>channel.subscribe(onMessage)</code></a></span></li>
<li><span class="stability_0"><a href="#all_diagnostics_channel_channelunsubscribeonmessage"><code>channel.unsubscribe(onMessage)</code></a></span></li>
<li><span class="stability_1"><a href="#all_diagnostics_channel_channelbindstorestore-transform"><code>channel.bindStore(store[, transform])</code></a></span></li>
<li><span class="stability_1"><a href="#all_diagnostics_channel_channelunbindstorestore"><code>channel.unbindStore(store)</code></a></span></li>
<li><span class="stability_1"><a href="#all_diagnostics_channel_channelrunstorescontext-fn-thisarg-args"><code>channel.runStores(context, fn[, thisArg[, ...args]])</code></a></span></li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_diagnostics_channel_class-tracingchannel">Class: <code>TracingChannel</code></a></span>
<ul>
<li><span class="stability_1"><a href="#all_diagnostics_channel_tracingchannelsubscribesubscribers"><code>tracingChannel.subscribe(subscribers)</code></a></span></li>
<li><span class="stability_1"><a href="#all_diagnostics_channel_tracingchannelunsubscribesubscribers"><code>tracingChannel.unsubscribe(subscribers)</code></a></span></li>
<li><span class="stability_1"><a href="#all_diagnostics_channel_tracingchanneltracesyncfn-context-thisarg-args"><code>tracingChannel.traceSync(fn[, context[, thisArg[, ...args]]])</code></a></span></li>
<li><span class="stability_1"><a href="#all_diagnostics_channel_tracingchanneltracepromisefn-context-thisarg-args"><code>tracingChannel.tracePromise(fn[, context[, thisArg[, ...args]]])</code></a></span></li>
<li><span class="stability_1"><a href="#all_diagnostics_channel_tracingchanneltracecallbackfn-position-context-thisarg-args"><code>tracingChannel.traceCallback(fn[, position[, context[, thisArg[, ...args]]]])</code></a></span></li>
<li><span class="stability_1"><a href="#all_diagnostics_channel_tracingchannelhassubscribers"><code>tracingChannel.hasSubscribers</code></a></span></li>
</ul>
</li>
<li><a href="#all_diagnostics_channel_tracingchannel-channels">TracingChannel Channels</a>
<ul>
<li><a href="#all_diagnostics_channel_startevent"><code>start(event)</code></a></li>
<li><a href="#all_diagnostics_channel_endevent"><code>end(event)</code></a></li>
<li><a href="#all_diagnostics_channel_asyncstartevent"><code>asyncStart(event)</code></a></li>
<li><a href="#all_diagnostics_channel_asyncendevent"><code>asyncEnd(event)</code></a></li>
<li><a href="#all_diagnostics_channel_errorevent"><code>error(event)</code></a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_diagnostics_channel_built-in-channels">Built-in Channels</a></span>
<ul>
<li><a href="#all_diagnostics_channel_http">HTTP</a></li>
<li><a href="#all_diagnostics_channel_net">NET</a></li>
<li><a href="#all_diagnostics_channel_udp">UDP</a></li>
<li><a href="#all_diagnostics_channel_process">Process</a></li>
<li><a href="#all_diagnostics_channel_worker-thread">Worker Thread</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_dns_dns">DNS</a></span>
<ul>
<li><a href="#all_dns_class-dnsresolver">Class: <code>dns.Resolver</code></a>
<ul>
<li><a href="#all_dns_resolveroptions"><code>Resolver([options])</code></a></li>
<li><a href="#all_dns_resolvercancel"><code>resolver.cancel()</code></a></li>
<li><a href="#all_dns_resolversetlocaladdressipv4-ipv6"><code>resolver.setLocalAddress([ipv4][, ipv6])</code></a></li>
</ul>
</li>
<li><a href="#all_dns_dnsgetservers"><code>dns.getServers()</code></a></li>
<li><a href="#all_dns_dnslookuphostname-options-callback"><code>dns.lookup(hostname[, options], callback)</code></a>
<ul>
<li><a href="#all_dns_supported-getaddrinfo-flags">Supported getaddrinfo flags</a></li>
</ul>
</li>
<li><a href="#all_dns_dnslookupserviceaddress-port-callback"><code>dns.lookupService(address, port, callback)</code></a></li>
<li><a href="#all_dns_dnsresolvehostname-rrtype-callback"><code>dns.resolve(hostname[, rrtype], callback)</code></a></li>
<li><a href="#all_dns_dnsresolve4hostname-options-callback"><code>dns.resolve4(hostname[, options], callback)</code></a></li>
<li><a href="#all_dns_dnsresolve6hostname-options-callback"><code>dns.resolve6(hostname[, options], callback)</code></a></li>
<li><a href="#all_dns_dnsresolveanyhostname-callback"><code>dns.resolveAny(hostname, callback)</code></a></li>
<li><a href="#all_dns_dnsresolvecnamehostname-callback"><code>dns.resolveCname(hostname, callback)</code></a></li>
<li><a href="#all_dns_dnsresolvecaahostname-callback"><code>dns.resolveCaa(hostname, callback)</code></a></li>
<li><a href="#all_dns_dnsresolvemxhostname-callback"><code>dns.resolveMx(hostname, callback)</code></a></li>
<li><a href="#all_dns_dnsresolvenaptrhostname-callback"><code>dns.resolveNaptr(hostname, callback)</code></a></li>
<li><a href="#all_dns_dnsresolvenshostname-callback"><code>dns.resolveNs(hostname, callback)</code></a></li>
<li><a href="#all_dns_dnsresolveptrhostname-callback"><code>dns.resolvePtr(hostname, callback)</code></a></li>
<li><a href="#all_dns_dnsresolvesoahostname-callback"><code>dns.resolveSoa(hostname, callback)</code></a></li>
<li><a href="#all_dns_dnsresolvesrvhostname-callback"><code>dns.resolveSrv(hostname, callback)</code></a></li>
<li><a href="#all_dns_dnsresolvetxthostname-callback"><code>dns.resolveTxt(hostname, callback)</code></a></li>
<li><a href="#all_dns_dnsreverseip-callback"><code>dns.reverse(ip, callback)</code></a></li>
<li><a href="#all_dns_dnssetdefaultresultorderorder"><code>dns.setDefaultResultOrder(order)</code></a></li>
<li><a href="#all_dns_dnsgetdefaultresultorder"><code>dns.getDefaultResultOrder()</code></a></li>
<li><a href="#all_dns_dnssetserversservers"><code>dns.setServers(servers)</code></a></li>
<li><a href="#all_dns_dns-promises-api">DNS promises API</a>
<ul>
<li><a href="#all_dns_class-dnspromisesresolver">Class: <code>dnsPromises.Resolver</code></a></li>
<li><a href="#all_dns_resolvercancel_1"><code>resolver.cancel()</code></a></li>
<li><a href="#all_dns_dnspromisesgetservers"><code>dnsPromises.getServers()</code></a></li>
<li><a href="#all_dns_dnspromiseslookuphostname-options"><code>dnsPromises.lookup(hostname[, options])</code></a></li>
<li><a href="#all_dns_dnspromiseslookupserviceaddress-port"><code>dnsPromises.lookupService(address, port)</code></a></li>
<li><a href="#all_dns_dnspromisesresolvehostname-rrtype"><code>dnsPromises.resolve(hostname[, rrtype])</code></a></li>
<li><a href="#all_dns_dnspromisesresolve4hostname-options"><code>dnsPromises.resolve4(hostname[, options])</code></a></li>
<li><a href="#all_dns_dnspromisesresolve6hostname-options"><code>dnsPromises.resolve6(hostname[, options])</code></a></li>
<li><a href="#all_dns_dnspromisesresolveanyhostname"><code>dnsPromises.resolveAny(hostname)</code></a></li>
<li><a href="#all_dns_dnspromisesresolvecaahostname"><code>dnsPromises.resolveCaa(hostname)</code></a></li>
<li><a href="#all_dns_dnspromisesresolvecnamehostname"><code>dnsPromises.resolveCname(hostname)</code></a></li>
<li><a href="#all_dns_dnspromisesresolvemxhostname"><code>dnsPromises.resolveMx(hostname)</code></a></li>
<li><a href="#all_dns_dnspromisesresolvenaptrhostname"><code>dnsPromises.resolveNaptr(hostname)</code></a></li>
<li><a href="#all_dns_dnspromisesresolvenshostname"><code>dnsPromises.resolveNs(hostname)</code></a></li>
<li><a href="#all_dns_dnspromisesresolveptrhostname"><code>dnsPromises.resolvePtr(hostname)</code></a></li>
<li><a href="#all_dns_dnspromisesresolvesoahostname"><code>dnsPromises.resolveSoa(hostname)</code></a></li>
<li><a href="#all_dns_dnspromisesresolvesrvhostname"><code>dnsPromises.resolveSrv(hostname)</code></a></li>
<li><a href="#all_dns_dnspromisesresolvetxthostname"><code>dnsPromises.resolveTxt(hostname)</code></a></li>
<li><a href="#all_dns_dnspromisesreverseip"><code>dnsPromises.reverse(ip)</code></a></li>
<li><a href="#all_dns_dnspromisessetdefaultresultorderorder"><code>dnsPromises.setDefaultResultOrder(order)</code></a></li>
<li><a href="#all_dns_dnspromisesgetdefaultresultorder"><code>dnsPromises.getDefaultResultOrder()</code></a></li>
<li><a href="#all_dns_dnspromisessetserversservers"><code>dnsPromises.setServers(servers)</code></a></li>
</ul>
</li>
<li><a href="#all_dns_error-codes">Error codes</a></li>
<li><a href="#all_dns_implementation-considerations">Implementation considerations</a>
<ul>
<li><a href="#all_dns_dnslookup"><code>dns.lookup()</code></a></li>
<li><a href="#all_dns_dnsresolve-dnsresolve-and-dnsreverse"><code>dns.resolve()</code>, <code>dns.resolve*()</code>, and <code>dns.reverse()</code></a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_0"><a href="#all_domain_domain">Domain</a></span>
<ul>
<li><a href="#all_domain_warning-dont-ignore-errors">Warning: Don't ignore errors!</a></li>
<li><a href="#all_domain_additions-to-error-objects">Additions to <code>Error</code> objects</a></li>
<li><a href="#all_domain_implicit-binding">Implicit binding</a></li>
<li><a href="#all_domain_explicit-binding">Explicit binding</a></li>
<li><a href="#all_domain_domaincreate"><code>domain.create()</code></a></li>
<li><a href="#all_domain_class-domain">Class: <code>Domain</code></a>
<ul>
<li><a href="#all_domain_domainmembers"><code>domain.members</code></a></li>
<li><a href="#all_domain_domainaddemitter"><code>domain.add(emitter)</code></a></li>
<li><a href="#all_domain_domainbindcallback"><code>domain.bind(callback)</code></a></li>
<li><a href="#all_domain_domainenter"><code>domain.enter()</code></a></li>
<li><a href="#all_domain_domainexit"><code>domain.exit()</code></a></li>
<li><a href="#all_domain_domaininterceptcallback"><code>domain.intercept(callback)</code></a></li>
<li><a href="#all_domain_domainremoveemitter"><code>domain.remove(emitter)</code></a></li>
<li><a href="#all_domain_domainrunfn-args"><code>domain.run(fn[, ...args])</code></a></li>
</ul>
</li>
<li><a href="#all_domain_domains-and-promises">Domains and promises</a></li>
</ul>
</li>
<li><a href="#all_errors_errors">Errors</a>
<ul>
<li><a href="#all_errors_error-propagation-and-interception">Error propagation and interception</a></li>
<li><a href="#all_errors_class-error">Class: <code>Error</code></a>
<ul>
<li><a href="#all_errors_new-errormessage-options"><code>new Error(message[, options])</code></a></li>
<li><a href="#all_errors_errorcapturestacktracetargetobject-constructoropt"><code>Error.captureStackTrace(targetObject[, constructorOpt])</code></a></li>
<li><a href="#all_errors_errorstacktracelimit"><code>Error.stackTraceLimit</code></a></li>
<li><a href="#all_errors_errorcause"><code>error.cause</code></a></li>
<li><a href="#all_errors_errorcode"><code>error.code</code></a></li>
<li><a href="#all_errors_errormessage"><code>error.message</code></a></li>
<li><a href="#all_errors_errorstack"><code>error.stack</code></a></li>
</ul>
</li>
<li><a href="#all_errors_class-assertionerror">Class: <code>AssertionError</code></a></li>
<li><a href="#all_errors_class-rangeerror">Class: <code>RangeError</code></a></li>
<li><a href="#all_errors_class-referenceerror">Class: <code>ReferenceError</code></a></li>
<li><a href="#all_errors_class-syntaxerror">Class: <code>SyntaxError</code></a></li>
<li><a href="#all_errors_class-systemerror">Class: <code>SystemError</code></a>
<ul>
<li><a href="#all_errors_erroraddress"><code>error.address</code></a></li>
<li><a href="#all_errors_errorcode_1"><code>error.code</code></a></li>
<li><a href="#all_errors_errordest"><code>error.dest</code></a></li>
<li><a href="#all_errors_errorerrno"><code>error.errno</code></a></li>
<li><a href="#all_errors_errorinfo"><code>error.info</code></a></li>
<li><a href="#all_errors_errormessage_1"><code>error.message</code></a></li>
<li><a href="#all_errors_errorpath"><code>error.path</code></a></li>
<li><a href="#all_errors_errorport"><code>error.port</code></a></li>
<li><a href="#all_errors_errorsyscall"><code>error.syscall</code></a></li>
<li><a href="#all_errors_common-system-errors">Common system errors</a></li>
</ul>
</li>
<li><a href="#all_errors_class-typeerror">Class: <code>TypeError</code></a></li>
<li><a href="#all_errors_exceptions-vs-errors">Exceptions vs. errors</a></li>
<li><a href="#all_errors_openssl-errors">OpenSSL errors</a>
<ul>
<li><a href="#all_errors_erroropensslerrorstack"><code>error.opensslErrorStack</code></a></li>
<li><a href="#all_errors_errorfunction"><code>error.function</code></a></li>
<li><a href="#all_errors_errorlibrary"><code>error.library</code></a></li>
<li><a href="#all_errors_errorreason"><code>error.reason</code></a></li>
</ul>
</li>
<li><a href="#all_errors_nodejs-error-codes">Node.js error codes</a>
<ul>
<li><a href="#all_errors_abort_err"><code>ABORT_ERR</code></a></li>
<li><a href="#all_errors_err_access_denied"><code>ERR_ACCESS_DENIED</code></a></li>
<li><a href="#all_errors_err_ambiguous_argument"><code>ERR_AMBIGUOUS_ARGUMENT</code></a></li>
<li><a href="#all_errors_err_arg_not_iterable"><code>ERR_ARG_NOT_ITERABLE</code></a></li>
<li><a href="#all_errors_err_assertion"><code>ERR_ASSERTION</code></a></li>
<li><a href="#all_errors_err_async_callback"><code>ERR_ASYNC_CALLBACK</code></a></li>
<li><a href="#all_errors_err_async_type"><code>ERR_ASYNC_TYPE</code></a></li>
<li><a href="#all_errors_err_brotli_compression_failed"><code>ERR_BROTLI_COMPRESSION_FAILED</code></a></li>
<li><a href="#all_errors_err_brotli_invalid_param"><code>ERR_BROTLI_INVALID_PARAM</code></a></li>
<li><a href="#all_errors_err_buffer_context_not_available"><code>ERR_BUFFER_CONTEXT_NOT_AVAILABLE</code></a></li>
<li><a href="#all_errors_err_buffer_out_of_bounds"><code>ERR_BUFFER_OUT_OF_BOUNDS</code></a></li>
<li><a href="#all_errors_err_buffer_too_large"><code>ERR_BUFFER_TOO_LARGE</code></a></li>
<li><a href="#all_errors_err_cannot_watch_sigint"><code>ERR_CANNOT_WATCH_SIGINT</code></a></li>
<li><a href="#all_errors_err_child_closed_before_reply"><code>ERR_CHILD_CLOSED_BEFORE_REPLY</code></a></li>
<li><a href="#all_errors_err_child_process_ipc_required"><code>ERR_CHILD_PROCESS_IPC_REQUIRED</code></a></li>
<li><a href="#all_errors_err_child_process_stdio_maxbuffer"><code>ERR_CHILD_PROCESS_STDIO_MAXBUFFER</code></a></li>
<li><a href="#all_errors_err_closed_message_port"><code>ERR_CLOSED_MESSAGE_PORT</code></a></li>
<li><a href="#all_errors_err_console_writable_stream"><code>ERR_CONSOLE_WRITABLE_STREAM</code></a></li>
<li><a href="#all_errors_err_construct_call_invalid"><code>ERR_CONSTRUCT_CALL_INVALID</code></a></li>
<li><a href="#all_errors_err_construct_call_required"><code>ERR_CONSTRUCT_CALL_REQUIRED</code></a></li>
<li><a href="#all_errors_err_context_not_initialized"><code>ERR_CONTEXT_NOT_INITIALIZED</code></a></li>
<li><a href="#all_errors_err_crypto_custom_engine_not_supported"><code>ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED</code></a></li>
<li><a href="#all_errors_err_crypto_ecdh_invalid_format"><code>ERR_CRYPTO_ECDH_INVALID_FORMAT</code></a></li>
<li><a href="#all_errors_err_crypto_ecdh_invalid_public_key"><code>ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY</code></a></li>
<li><a href="#all_errors_err_crypto_engine_unknown"><code>ERR_CRYPTO_ENGINE_UNKNOWN</code></a></li>
<li><a href="#all_errors_err_crypto_fips_forced"><code>ERR_CRYPTO_FIPS_FORCED</code></a></li>
<li><a href="#all_errors_err_crypto_fips_unavailable"><code>ERR_CRYPTO_FIPS_UNAVAILABLE</code></a></li>
<li><a href="#all_errors_err_crypto_hash_finalized"><code>ERR_CRYPTO_HASH_FINALIZED</code></a></li>
<li><a href="#all_errors_err_crypto_hash_update_failed"><code>ERR_CRYPTO_HASH_UPDATE_FAILED</code></a></li>
<li><a href="#all_errors_err_crypto_incompatible_key"><code>ERR_CRYPTO_INCOMPATIBLE_KEY</code></a></li>
<li><a href="#all_errors_err_crypto_incompatible_key_options"><code>ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS</code></a></li>
<li><a href="#all_errors_err_crypto_initialization_failed"><code>ERR_CRYPTO_INITIALIZATION_FAILED</code></a></li>
<li><a href="#all_errors_err_crypto_invalid_auth_tag"><code>ERR_CRYPTO_INVALID_AUTH_TAG</code></a></li>
<li><a href="#all_errors_err_crypto_invalid_counter"><code>ERR_CRYPTO_INVALID_COUNTER</code></a></li>
<li><a href="#all_errors_err_crypto_invalid_curve"><code>ERR_CRYPTO_INVALID_CURVE</code></a></li>
<li><a href="#all_errors_err_crypto_invalid_digest"><code>ERR_CRYPTO_INVALID_DIGEST</code></a></li>
<li><a href="#all_errors_err_crypto_invalid_iv"><code>ERR_CRYPTO_INVALID_IV</code></a></li>
<li><a href="#all_errors_err_crypto_invalid_jwk"><code>ERR_CRYPTO_INVALID_JWK</code></a></li>
<li><a href="#all_errors_err_crypto_invalid_key_object_type"><code>ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE</code></a></li>
<li><a href="#all_errors_err_crypto_invalid_keylen"><code>ERR_CRYPTO_INVALID_KEYLEN</code></a></li>
<li><a href="#all_errors_err_crypto_invalid_keypair"><code>ERR_CRYPTO_INVALID_KEYPAIR</code></a></li>
<li><a href="#all_errors_err_crypto_invalid_keytype"><code>ERR_CRYPTO_INVALID_KEYTYPE</code></a></li>
<li><a href="#all_errors_err_crypto_invalid_messagelen"><code>ERR_CRYPTO_INVALID_MESSAGELEN</code></a></li>
<li><a href="#all_errors_err_crypto_invalid_scrypt_params"><code>ERR_CRYPTO_INVALID_SCRYPT_PARAMS</code></a></li>
<li><a href="#all_errors_err_crypto_invalid_state"><code>ERR_CRYPTO_INVALID_STATE</code></a></li>
<li><a href="#all_errors_err_crypto_invalid_tag_length"><code>ERR_CRYPTO_INVALID_TAG_LENGTH</code></a></li>
<li><a href="#all_errors_err_crypto_job_init_failed"><code>ERR_CRYPTO_JOB_INIT_FAILED</code></a></li>
<li><a href="#all_errors_err_crypto_jwk_unsupported_curve"><code>ERR_CRYPTO_JWK_UNSUPPORTED_CURVE</code></a></li>
<li><a href="#all_errors_err_crypto_jwk_unsupported_key_type"><code>ERR_CRYPTO_JWK_UNSUPPORTED_KEY_TYPE</code></a></li>
<li><a href="#all_errors_err_crypto_operation_failed"><code>ERR_CRYPTO_OPERATION_FAILED</code></a></li>
<li><a href="#all_errors_err_crypto_pbkdf2_error"><code>ERR_CRYPTO_PBKDF2_ERROR</code></a></li>
<li><a href="#all_errors_err_crypto_scrypt_invalid_parameter"><code>ERR_CRYPTO_SCRYPT_INVALID_PARAMETER</code></a></li>
<li><a href="#all_errors_err_crypto_scrypt_not_supported"><code>ERR_CRYPTO_SCRYPT_NOT_SUPPORTED</code></a></li>
<li><a href="#all_errors_err_crypto_sign_key_required"><code>ERR_CRYPTO_SIGN_KEY_REQUIRED</code></a></li>
<li><a href="#all_errors_err_crypto_timing_safe_equal_length"><code>ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH</code></a></li>
<li><a href="#all_errors_err_crypto_unknown_cipher"><code>ERR_CRYPTO_UNKNOWN_CIPHER</code></a></li>
<li><a href="#all_errors_err_crypto_unknown_dh_group"><code>ERR_CRYPTO_UNKNOWN_DH_GROUP</code></a></li>
<li><a href="#all_errors_err_crypto_unsupported_operation"><code>ERR_CRYPTO_UNSUPPORTED_OPERATION</code></a></li>
<li><a href="#all_errors_err_debugger_error"><code>ERR_DEBUGGER_ERROR</code></a></li>
<li><a href="#all_errors_err_debugger_startup_error"><code>ERR_DEBUGGER_STARTUP_ERROR</code></a></li>
<li><a href="#all_errors_err_dlopen_disabled"><code>ERR_DLOPEN_DISABLED</code></a></li>
<li><a href="#all_errors_err_dlopen_failed"><code>ERR_DLOPEN_FAILED</code></a></li>
<li><a href="#all_errors_err_dir_closed"><code>ERR_DIR_CLOSED</code></a></li>
<li><a href="#all_errors_err_dir_concurrent_operation"><code>ERR_DIR_CONCURRENT_OPERATION</code></a></li>
<li><a href="#all_errors_err_dns_set_servers_failed"><code>ERR_DNS_SET_SERVERS_FAILED</code></a></li>
<li><a href="#all_errors_err_domain_callback_not_available"><code>ERR_DOMAIN_CALLBACK_NOT_AVAILABLE</code></a></li>
<li><a href="#all_errors_err_domain_cannot_set_uncaught_exception_capture"><code>ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE</code></a></li>
<li><a href="#all_errors_err_duplicate_startup_snapshot_main_function"><code>ERR_DUPLICATE_STARTUP_SNAPSHOT_MAIN_FUNCTION</code></a></li>
<li><a href="#all_errors_err_encoding_invalid_encoded_data"><code>ERR_ENCODING_INVALID_ENCODED_DATA</code></a></li>
<li><a href="#all_errors_err_encoding_not_supported"><code>ERR_ENCODING_NOT_SUPPORTED</code></a></li>
<li><a href="#all_errors_err_eval_esm_cannot_print"><code>ERR_EVAL_ESM_CANNOT_PRINT</code></a></li>
<li><a href="#all_errors_err_event_recursion"><code>ERR_EVENT_RECURSION</code></a></li>
<li><a href="#all_errors_err_execution_environment_not_available"><code>ERR_EXECUTION_ENVIRONMENT_NOT_AVAILABLE</code></a></li>
<li><a href="#all_errors_err_falsy_value_rejection"><code>ERR_FALSY_VALUE_REJECTION</code></a></li>
<li><a href="#all_errors_err_feature_unavailable_on_platform"><code>ERR_FEATURE_UNAVAILABLE_ON_PLATFORM</code></a></li>
<li><a href="#all_errors_err_fs_cp_dir_to_non_dir"><code>ERR_FS_CP_DIR_TO_NON_DIR</code></a></li>
<li><a href="#all_errors_err_fs_cp_eexist"><code>ERR_FS_CP_EEXIST</code></a></li>
<li><a href="#all_errors_err_fs_cp_einval"><code>ERR_FS_CP_EINVAL</code></a></li>
<li><a href="#all_errors_err_http_body_not_allowed"><code>ERR_HTTP_BODY_NOT_ALLOWED</code></a></li>
<li><a href="#all_errors_err_http_content_length_mismatch"><code>ERR_HTTP_CONTENT_LENGTH_MISMATCH</code></a></li>
<li><a href="#all_errors_err_fs_cp_fifo_pipe"><code>ERR_FS_CP_FIFO_PIPE</code></a></li>
<li><a href="#all_errors_err_fs_cp_non_dir_to_dir"><code>ERR_FS_CP_NON_DIR_TO_DIR</code></a></li>
<li><a href="#all_errors_err_fs_cp_socket"><code>ERR_FS_CP_SOCKET</code></a></li>
<li><a href="#all_errors_err_fs_cp_symlink_to_subdirectory"><code>ERR_FS_CP_SYMLINK_TO_SUBDIRECTORY</code></a></li>
<li><a href="#all_errors_err_fs_cp_unknown"><code>ERR_FS_CP_UNKNOWN</code></a></li>
<li><a href="#all_errors_err_fs_eisdir"><code>ERR_FS_EISDIR</code></a></li>
<li><a href="#all_errors_err_fs_file_too_large"><code>ERR_FS_FILE_TOO_LARGE</code></a></li>
<li><a href="#all_errors_err_fs_invalid_symlink_type"><code>ERR_FS_INVALID_SYMLINK_TYPE</code></a></li>
<li><a href="#all_errors_err_http_headers_sent"><code>ERR_HTTP_HEADERS_SENT</code></a></li>
<li><a href="#all_errors_err_http_invalid_header_value"><code>ERR_HTTP_INVALID_HEADER_VALUE</code></a></li>
<li><a href="#all_errors_err_http_invalid_status_code"><code>ERR_HTTP_INVALID_STATUS_CODE</code></a></li>
<li><a href="#all_errors_err_http_request_timeout"><code>ERR_HTTP_REQUEST_TIMEOUT</code></a></li>
<li><a href="#all_errors_err_http_socket_assigned"><code>ERR_HTTP_SOCKET_ASSIGNED</code></a></li>
<li><a href="#all_errors_err_http_socket_encoding"><code>ERR_HTTP_SOCKET_ENCODING</code></a></li>
<li><a href="#all_errors_err_http_trailer_invalid"><code>ERR_HTTP_TRAILER_INVALID</code></a></li>
<li><a href="#all_errors_err_http2_altsvc_invalid_origin"><code>ERR_HTTP2_ALTSVC_INVALID_ORIGIN</code></a></li>
<li><a href="#all_errors_err_http2_altsvc_length"><code>ERR_HTTP2_ALTSVC_LENGTH</code></a></li>
<li><a href="#all_errors_err_http2_connect_authority"><code>ERR_HTTP2_CONNECT_AUTHORITY</code></a></li>
<li><a href="#all_errors_err_http2_connect_path"><code>ERR_HTTP2_CONNECT_PATH</code></a></li>
<li><a href="#all_errors_err_http2_connect_scheme"><code>ERR_HTTP2_CONNECT_SCHEME</code></a></li>
<li><a href="#all_errors_err_http2_error"><code>ERR_HTTP2_ERROR</code></a></li>
<li><a href="#all_errors_err_http2_goaway_session"><code>ERR_HTTP2_GOAWAY_SESSION</code></a></li>
<li><a href="#all_errors_err_http2_header_single_value"><code>ERR_HTTP2_HEADER_SINGLE_VALUE</code></a></li>
<li><a href="#all_errors_err_http2_headers_after_respond"><code>ERR_HTTP2_HEADERS_AFTER_RESPOND</code></a></li>
<li><a href="#all_errors_err_http2_headers_sent"><code>ERR_HTTP2_HEADERS_SENT</code></a></li>
<li><a href="#all_errors_err_http2_info_status_not_allowed"><code>ERR_HTTP2_INFO_STATUS_NOT_ALLOWED</code></a></li>
<li><a href="#all_errors_err_http2_invalid_connection_headers"><code>ERR_HTTP2_INVALID_CONNECTION_HEADERS</code></a></li>
<li><a href="#all_errors_err_http2_invalid_header_value"><code>ERR_HTTP2_INVALID_HEADER_VALUE</code></a></li>
<li><a href="#all_errors_err_http2_invalid_info_status"><code>ERR_HTTP2_INVALID_INFO_STATUS</code></a></li>
<li><a href="#all_errors_err_http2_invalid_origin"><code>ERR_HTTP2_INVALID_ORIGIN</code></a></li>
<li><a href="#all_errors_err_http2_invalid_packed_settings_length"><code>ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH</code></a></li>
<li><a href="#all_errors_err_http2_invalid_pseudoheader"><code>ERR_HTTP2_INVALID_PSEUDOHEADER</code></a></li>
<li><a href="#all_errors_err_http2_invalid_session"><code>ERR_HTTP2_INVALID_SESSION</code></a></li>
<li><a href="#all_errors_err_http2_invalid_setting_value"><code>ERR_HTTP2_INVALID_SETTING_VALUE</code></a></li>
<li><a href="#all_errors_err_http2_invalid_stream"><code>ERR_HTTP2_INVALID_STREAM</code></a></li>
<li><a href="#all_errors_err_http2_max_pending_settings_ack"><code>ERR_HTTP2_MAX_PENDING_SETTINGS_ACK</code></a></li>
<li><a href="#all_errors_err_http2_nested_push"><code>ERR_HTTP2_NESTED_PUSH</code></a></li>
<li><a href="#all_errors_err_http2_no_mem"><code>ERR_HTTP2_NO_MEM</code></a></li>
<li><a href="#all_errors_err_http2_no_socket_manipulation"><code>ERR_HTTP2_NO_SOCKET_MANIPULATION</code></a></li>
<li><a href="#all_errors_err_http2_origin_length"><code>ERR_HTTP2_ORIGIN_LENGTH</code></a></li>
<li><a href="#all_errors_err_http2_out_of_streams"><code>ERR_HTTP2_OUT_OF_STREAMS</code></a></li>
<li><a href="#all_errors_err_http2_payload_forbidden"><code>ERR_HTTP2_PAYLOAD_FORBIDDEN</code></a></li>
<li><a href="#all_errors_err_http2_ping_cancel"><code>ERR_HTTP2_PING_CANCEL</code></a></li>
<li><a href="#all_errors_err_http2_ping_length"><code>ERR_HTTP2_PING_LENGTH</code></a></li>
<li><a href="#all_errors_err_http2_pseudoheader_not_allowed"><code>ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED</code></a></li>
<li><a href="#all_errors_err_http2_push_disabled"><code>ERR_HTTP2_PUSH_DISABLED</code></a></li>
<li><a href="#all_errors_err_http2_send_file"><code>ERR_HTTP2_SEND_FILE</code></a></li>
<li><a href="#all_errors_err_http2_send_file_noseek"><code>ERR_HTTP2_SEND_FILE_NOSEEK</code></a></li>
<li><a href="#all_errors_err_http2_session_error"><code>ERR_HTTP2_SESSION_ERROR</code></a></li>
<li><a href="#all_errors_err_http2_settings_cancel"><code>ERR_HTTP2_SETTINGS_CANCEL</code></a></li>
<li><a href="#all_errors_err_http2_socket_bound"><code>ERR_HTTP2_SOCKET_BOUND</code></a></li>
<li><a href="#all_errors_err_http2_socket_unbound"><code>ERR_HTTP2_SOCKET_UNBOUND</code></a></li>
<li><a href="#all_errors_err_http2_status_101"><code>ERR_HTTP2_STATUS_101</code></a></li>
<li><a href="#all_errors_err_http2_status_invalid"><code>ERR_HTTP2_STATUS_INVALID</code></a></li>
<li><a href="#all_errors_err_http2_stream_cancel"><code>ERR_HTTP2_STREAM_CANCEL</code></a></li>
<li><a href="#all_errors_err_http2_stream_error"><code>ERR_HTTP2_STREAM_ERROR</code></a></li>
<li><a href="#all_errors_err_http2_stream_self_dependency"><code>ERR_HTTP2_STREAM_SELF_DEPENDENCY</code></a></li>
<li><a href="#all_errors_err_http2_too_many_custom_settings"><code>ERR_HTTP2_TOO_MANY_CUSTOM_SETTINGS</code></a></li>
<li><a href="#all_errors_err_http2_too_many_invalid_frames"><code>ERR_HTTP2_TOO_MANY_INVALID_FRAMES</code></a></li>
<li><a href="#all_errors_err_http2_trailers_already_sent"><code>ERR_HTTP2_TRAILERS_ALREADY_SENT</code></a></li>
<li><a href="#all_errors_err_http2_trailers_not_ready"><code>ERR_HTTP2_TRAILERS_NOT_READY</code></a></li>
<li><a href="#all_errors_err_http2_unsupported_protocol"><code>ERR_HTTP2_UNSUPPORTED_PROTOCOL</code></a></li>
<li><a href="#all_errors_err_illegal_constructor"><code>ERR_ILLEGAL_CONSTRUCTOR</code></a></li>
<li><a href="#all_errors_err_import_assertion_type_failed"><code>ERR_IMPORT_ASSERTION_TYPE_FAILED</code></a></li>
<li><a href="#all_errors_err_import_assertion_type_missing"><code>ERR_IMPORT_ASSERTION_TYPE_MISSING</code></a></li>
<li><a href="#all_errors_err_import_assertion_type_unsupported"><code>ERR_IMPORT_ASSERTION_TYPE_UNSUPPORTED</code></a></li>
<li><a href="#all_errors_err_import_attribute_unsupported"><code>ERR_IMPORT_ATTRIBUTE_UNSUPPORTED</code></a></li>
<li><a href="#all_errors_err_incompatible_option_pair"><code>ERR_INCOMPATIBLE_OPTION_PAIR</code></a></li>
<li><span class="stability_1"><a href="#all_errors_err_input_type_not_allowed"><code>ERR_INPUT_TYPE_NOT_ALLOWED</code></a></span></li>
<li><a href="#all_errors_err_inspector_already_activated"><code>ERR_INSPECTOR_ALREADY_ACTIVATED</code></a></li>
<li><a href="#all_errors_err_inspector_already_connected"><code>ERR_INSPECTOR_ALREADY_CONNECTED</code></a></li>
<li><a href="#all_errors_err_inspector_closed"><code>ERR_INSPECTOR_CLOSED</code></a></li>
<li><a href="#all_errors_err_inspector_command"><code>ERR_INSPECTOR_COMMAND</code></a></li>
<li><a href="#all_errors_err_inspector_not_active"><code>ERR_INSPECTOR_NOT_ACTIVE</code></a></li>
<li><a href="#all_errors_err_inspector_not_available"><code>ERR_INSPECTOR_NOT_AVAILABLE</code></a></li>
<li><a href="#all_errors_err_inspector_not_connected"><code>ERR_INSPECTOR_NOT_CONNECTED</code></a></li>
<li><a href="#all_errors_err_inspector_not_worker"><code>ERR_INSPECTOR_NOT_WORKER</code></a></li>
<li><a href="#all_errors_err_internal_assertion"><code>ERR_INTERNAL_ASSERTION</code></a></li>
<li><a href="#all_errors_err_invalid_address"><code>ERR_INVALID_ADDRESS</code></a></li>
<li><a href="#all_errors_err_invalid_address_family"><code>ERR_INVALID_ADDRESS_FAMILY</code></a></li>
<li><a href="#all_errors_err_invalid_arg_type"><code>ERR_INVALID_ARG_TYPE</code></a></li>
<li><a href="#all_errors_err_invalid_arg_value"><code>ERR_INVALID_ARG_VALUE</code></a></li>
<li><a href="#all_errors_err_invalid_async_id"><code>ERR_INVALID_ASYNC_ID</code></a></li>
<li><a href="#all_errors_err_invalid_buffer_size"><code>ERR_INVALID_BUFFER_SIZE</code></a></li>
<li><a href="#all_errors_err_invalid_char"><code>ERR_INVALID_CHAR</code></a></li>
<li><a href="#all_errors_err_invalid_cursor_pos"><code>ERR_INVALID_CURSOR_POS</code></a></li>
<li><a href="#all_errors_err_invalid_fd"><code>ERR_INVALID_FD</code></a></li>
<li><a href="#all_errors_err_invalid_fd_type"><code>ERR_INVALID_FD_TYPE</code></a></li>
<li><a href="#all_errors_err_invalid_file_url_host"><code>ERR_INVALID_FILE_URL_HOST</code></a></li>
<li><a href="#all_errors_err_invalid_file_url_path"><code>ERR_INVALID_FILE_URL_PATH</code></a></li>
<li><a href="#all_errors_err_invalid_handle_type"><code>ERR_INVALID_HANDLE_TYPE</code></a></li>
<li><a href="#all_errors_err_invalid_http_token"><code>ERR_INVALID_HTTP_TOKEN</code></a></li>
<li><a href="#all_errors_err_invalid_ip_address"><code>ERR_INVALID_IP_ADDRESS</code></a></li>
<li><a href="#all_errors_err_invalid_mime_syntax"><code>ERR_INVALID_MIME_SYNTAX</code></a></li>
<li><a href="#all_errors_err_invalid_module"><code>ERR_INVALID_MODULE</code></a></li>
<li><a href="#all_errors_err_invalid_module_specifier"><code>ERR_INVALID_MODULE_SPECIFIER</code></a></li>
<li><a href="#all_errors_err_invalid_object_define_property"><code>ERR_INVALID_OBJECT_DEFINE_PROPERTY</code></a></li>
<li><a href="#all_errors_err_invalid_package_config"><code>ERR_INVALID_PACKAGE_CONFIG</code></a></li>
<li><a href="#all_errors_err_invalid_package_target"><code>ERR_INVALID_PACKAGE_TARGET</code></a></li>
<li><a href="#all_errors_err_invalid_performance_mark"><code>ERR_INVALID_PERFORMANCE_MARK</code></a></li>
<li><a href="#all_errors_err_invalid_protocol"><code>ERR_INVALID_PROTOCOL</code></a></li>
<li><a href="#all_errors_err_invalid_repl_eval_config"><code>ERR_INVALID_REPL_EVAL_CONFIG</code></a></li>
<li><a href="#all_errors_err_invalid_repl_input"><code>ERR_INVALID_REPL_INPUT</code></a></li>
<li><a href="#all_errors_err_invalid_return_property"><code>ERR_INVALID_RETURN_PROPERTY</code></a></li>
<li><a href="#all_errors_err_invalid_return_property_value"><code>ERR_INVALID_RETURN_PROPERTY_VALUE</code></a></li>
<li><a href="#all_errors_err_invalid_return_value"><code>ERR_INVALID_RETURN_VALUE</code></a></li>
<li><a href="#all_errors_err_invalid_state"><code>ERR_INVALID_STATE</code></a></li>
<li><a href="#all_errors_err_invalid_sync_fork_input"><code>ERR_INVALID_SYNC_FORK_INPUT</code></a></li>
<li><a href="#all_errors_err_invalid_this"><code>ERR_INVALID_THIS</code></a></li>
<li><a href="#all_errors_err_invalid_transfer_object"><code>ERR_INVALID_TRANSFER_OBJECT</code></a></li>
<li><a href="#all_errors_err_invalid_tuple"><code>ERR_INVALID_TUPLE</code></a></li>
<li><a href="#all_errors_err_invalid_uri"><code>ERR_INVALID_URI</code></a></li>
<li><a href="#all_errors_err_invalid_url"><code>ERR_INVALID_URL</code></a></li>
<li><a href="#all_errors_err_invalid_url_scheme"><code>ERR_INVALID_URL_SCHEME</code></a></li>
<li><a href="#all_errors_err_ipc_channel_closed"><code>ERR_IPC_CHANNEL_CLOSED</code></a></li>
<li><a href="#all_errors_err_ipc_disconnected"><code>ERR_IPC_DISCONNECTED</code></a></li>
<li><a href="#all_errors_err_ipc_one_pipe"><code>ERR_IPC_ONE_PIPE</code></a></li>
<li><a href="#all_errors_err_ipc_sync_fork"><code>ERR_IPC_SYNC_FORK</code></a></li>
<li><a href="#all_errors_err_loader_chain_incomplete"><code>ERR_LOADER_CHAIN_INCOMPLETE</code></a></li>
<li><a href="#all_errors_err_manifest_assert_integrity"><code>ERR_MANIFEST_ASSERT_INTEGRITY</code></a></li>
<li><a href="#all_errors_err_manifest_dependency_missing"><code>ERR_MANIFEST_DEPENDENCY_MISSING</code></a></li>
<li><a href="#all_errors_err_manifest_integrity_mismatch"><code>ERR_MANIFEST_INTEGRITY_MISMATCH</code></a></li>
<li><a href="#all_errors_err_manifest_invalid_resource_field"><code>ERR_MANIFEST_INVALID_RESOURCE_FIELD</code></a></li>
<li><a href="#all_errors_err_manifest_invalid_specifier"><code>ERR_MANIFEST_INVALID_SPECIFIER</code></a></li>
<li><a href="#all_errors_err_manifest_parse_policy"><code>ERR_MANIFEST_PARSE_POLICY</code></a></li>
<li><a href="#all_errors_err_manifest_tdz"><code>ERR_MANIFEST_TDZ</code></a></li>
<li><a href="#all_errors_err_manifest_unknown_onerror"><code>ERR_MANIFEST_UNKNOWN_ONERROR</code></a></li>
<li><a href="#all_errors_err_memory_allocation_failed"><code>ERR_MEMORY_ALLOCATION_FAILED</code></a></li>
<li><a href="#all_errors_err_message_target_context_unavailable"><code>ERR_MESSAGE_TARGET_CONTEXT_UNAVAILABLE</code></a></li>
<li><a href="#all_errors_err_method_not_implemented"><code>ERR_METHOD_NOT_IMPLEMENTED</code></a></li>
<li><a href="#all_errors_err_missing_args"><code>ERR_MISSING_ARGS</code></a></li>
<li><a href="#all_errors_err_missing_option"><code>ERR_MISSING_OPTION</code></a></li>
<li><a href="#all_errors_err_missing_passphrase"><code>ERR_MISSING_PASSPHRASE</code></a></li>
<li><a href="#all_errors_err_missing_platform_for_worker"><code>ERR_MISSING_PLATFORM_FOR_WORKER</code></a></li>
<li><a href="#all_errors_err_missing_transferable_in_transfer_list"><code>ERR_MISSING_TRANSFERABLE_IN_TRANSFER_LIST</code></a></li>
<li><a href="#all_errors_err_module_not_found"><code>ERR_MODULE_NOT_FOUND</code></a></li>
<li><a href="#all_errors_err_multiple_callback"><code>ERR_MULTIPLE_CALLBACK</code></a></li>
<li><a href="#all_errors_err_napi_cons_function"><code>ERR_NAPI_CONS_FUNCTION</code></a></li>
<li><a href="#all_errors_err_napi_invalid_dataview_args"><code>ERR_NAPI_INVALID_DATAVIEW_ARGS</code></a></li>
<li><a href="#all_errors_err_napi_invalid_typedarray_alignment"><code>ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT</code></a></li>
<li><a href="#all_errors_err_napi_invalid_typedarray_length"><code>ERR_NAPI_INVALID_TYPEDARRAY_LENGTH</code></a></li>
<li><a href="#all_errors_err_napi_tsfn_call_js"><code>ERR_NAPI_TSFN_CALL_JS</code></a></li>
<li><a href="#all_errors_err_napi_tsfn_get_undefined"><code>ERR_NAPI_TSFN_GET_UNDEFINED</code></a></li>
<li><a href="#all_errors_err_napi_tsfn_start_idle_loop"><code>ERR_NAPI_TSFN_START_IDLE_LOOP</code></a></li>
<li><a href="#all_errors_err_napi_tsfn_stop_idle_loop"><code>ERR_NAPI_TSFN_STOP_IDLE_LOOP</code></a></li>
<li><a href="#all_errors_err_not_building_snapshot"><code>ERR_NOT_BUILDING_SNAPSHOT</code></a></li>
<li><a href="#all_errors_err_not_in_single_executable_application"><code>ERR_NOT_IN_SINGLE_EXECUTABLE_APPLICATION</code></a></li>
<li><a href="#all_errors_err_not_supported_in_snapshot"><code>ERR_NOT_SUPPORTED_IN_SNAPSHOT</code></a></li>
<li><a href="#all_errors_err_no_crypto"><code>ERR_NO_CRYPTO</code></a></li>
<li><a href="#all_errors_err_no_icu"><code>ERR_NO_ICU</code></a></li>
<li><a href="#all_errors_err_non_context_aware_disabled"><code>ERR_NON_CONTEXT_AWARE_DISABLED</code></a></li>
<li><a href="#all_errors_err_out_of_range"><code>ERR_OUT_OF_RANGE</code></a></li>
<li><a href="#all_errors_err_package_import_not_defined"><code>ERR_PACKAGE_IMPORT_NOT_DEFINED</code></a></li>
<li><a href="#all_errors_err_package_path_not_exported"><code>ERR_PACKAGE_PATH_NOT_EXPORTED</code></a></li>
<li><a href="#all_errors_err_parse_args_invalid_option_value"><code>ERR_PARSE_ARGS_INVALID_OPTION_VALUE</code></a></li>
<li><a href="#all_errors_err_parse_args_unexpected_positional"><code>ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL</code></a></li>
<li><a href="#all_errors_err_parse_args_unknown_option"><code>ERR_PARSE_ARGS_UNKNOWN_OPTION</code></a></li>
<li><a href="#all_errors_err_performance_invalid_timestamp"><code>ERR_PERFORMANCE_INVALID_TIMESTAMP</code></a></li>
<li><a href="#all_errors_err_performance_measure_invalid_options"><code>ERR_PERFORMANCE_MEASURE_INVALID_OPTIONS</code></a></li>
<li><a href="#all_errors_err_proto_access"><code>ERR_PROTO_ACCESS</code></a></li>
<li><span class="stability_1"><a href="#all_errors_err_require_cycle_module"><code>ERR_REQUIRE_CYCLE_MODULE</code></a></span></li>
<li><span class="stability_1"><a href="#all_errors_err_require_async_module"><code>ERR_REQUIRE_ASYNC_MODULE</code></a></span></li>
<li><span class="stability_1"><a href="#all_errors_err_require_esm"><code>ERR_REQUIRE_ESM</code></a></span></li>
<li><a href="#all_errors_err_script_execution_interrupted"><code>ERR_SCRIPT_EXECUTION_INTERRUPTED</code></a></li>
<li><a href="#all_errors_err_script_execution_timeout"><code>ERR_SCRIPT_EXECUTION_TIMEOUT</code></a></li>
<li><a href="#all_errors_err_server_already_listen"><code>ERR_SERVER_ALREADY_LISTEN</code></a></li>
<li><a href="#all_errors_err_server_not_running"><code>ERR_SERVER_NOT_RUNNING</code></a></li>
<li><a href="#all_errors_err_single_executable_application_asset_not_found"><code>ERR_SINGLE_EXECUTABLE_APPLICATION_ASSET_NOT_FOUND</code></a></li>
<li><a href="#all_errors_err_socket_already_bound"><code>ERR_SOCKET_ALREADY_BOUND</code></a></li>
<li><a href="#all_errors_err_socket_bad_buffer_size"><code>ERR_SOCKET_BAD_BUFFER_SIZE</code></a></li>
<li><a href="#all_errors_err_socket_bad_port"><code>ERR_SOCKET_BAD_PORT</code></a></li>
<li><a href="#all_errors_err_socket_bad_type"><code>ERR_SOCKET_BAD_TYPE</code></a></li>
<li><a href="#all_errors_err_socket_buffer_size"><code>ERR_SOCKET_BUFFER_SIZE</code></a></li>
<li><a href="#all_errors_err_socket_closed"><code>ERR_SOCKET_CLOSED</code></a></li>
<li><a href="#all_errors_err_socket_closed_before_connection"><code>ERR_SOCKET_CLOSED_BEFORE_CONNECTION</code></a></li>
<li><a href="#all_errors_err_socket_connection_timeout"><code>ERR_SOCKET_CONNECTION_TIMEOUT</code></a></li>
<li><a href="#all_errors_err_socket_dgram_is_connected"><code>ERR_SOCKET_DGRAM_IS_CONNECTED</code></a></li>
<li><a href="#all_errors_err_socket_dgram_not_connected"><code>ERR_SOCKET_DGRAM_NOT_CONNECTED</code></a></li>
<li><a href="#all_errors_err_socket_dgram_not_running"><code>ERR_SOCKET_DGRAM_NOT_RUNNING</code></a></li>
<li><a href="#all_errors_err_sri_parse"><code>ERR_SRI_PARSE</code></a></li>
<li><a href="#all_errors_err_stream_already_finished"><code>ERR_STREAM_ALREADY_FINISHED</code></a></li>
<li><a href="#all_errors_err_stream_cannot_pipe"><code>ERR_STREAM_CANNOT_PIPE</code></a></li>
<li><a href="#all_errors_err_stream_destroyed"><code>ERR_STREAM_DESTROYED</code></a></li>
<li><a href="#all_errors_err_stream_null_values"><code>ERR_STREAM_NULL_VALUES</code></a></li>
<li><a href="#all_errors_err_stream_premature_close"><code>ERR_STREAM_PREMATURE_CLOSE</code></a></li>
<li><a href="#all_errors_err_stream_push_after_eof"><code>ERR_STREAM_PUSH_AFTER_EOF</code></a></li>
<li><a href="#all_errors_err_stream_unshift_after_end_event"><code>ERR_STREAM_UNSHIFT_AFTER_END_EVENT</code></a></li>
<li><a href="#all_errors_err_stream_wrap"><code>ERR_STREAM_WRAP</code></a></li>
<li><a href="#all_errors_err_stream_write_after_end"><code>ERR_STREAM_WRITE_AFTER_END</code></a></li>
<li><a href="#all_errors_err_string_too_long"><code>ERR_STRING_TOO_LONG</code></a></li>
<li><a href="#all_errors_err_synthetic"><code>ERR_SYNTHETIC</code></a></li>
<li><a href="#all_errors_err_system_error"><code>ERR_SYSTEM_ERROR</code></a></li>
<li><a href="#all_errors_err_tap_lexer_error"><code>ERR_TAP_LEXER_ERROR</code></a></li>
<li><a href="#all_errors_err_tap_parser_error"><code>ERR_TAP_PARSER_ERROR</code></a></li>
<li><a href="#all_errors_err_tap_validation_error"><code>ERR_TAP_VALIDATION_ERROR</code></a></li>
<li><a href="#all_errors_err_test_failure"><code>ERR_TEST_FAILURE</code></a></li>
<li><a href="#all_errors_err_tls_alpn_callback_invalid_result"><code>ERR_TLS_ALPN_CALLBACK_INVALID_RESULT</code></a></li>
<li><a href="#all_errors_err_tls_alpn_callback_with_protocols"><code>ERR_TLS_ALPN_CALLBACK_WITH_PROTOCOLS</code></a></li>
<li><a href="#all_errors_err_tls_cert_altname_format"><code>ERR_TLS_CERT_ALTNAME_FORMAT</code></a></li>
<li><a href="#all_errors_err_tls_cert_altname_invalid"><code>ERR_TLS_CERT_ALTNAME_INVALID</code></a></li>
<li><a href="#all_errors_err_tls_dh_param_size"><code>ERR_TLS_DH_PARAM_SIZE</code></a></li>
<li><a href="#all_errors_err_tls_handshake_timeout"><code>ERR_TLS_HANDSHAKE_TIMEOUT</code></a></li>
<li><a href="#all_errors_err_tls_invalid_context"><code>ERR_TLS_INVALID_CONTEXT</code></a></li>
<li><a href="#all_errors_err_tls_invalid_protocol_method"><code>ERR_TLS_INVALID_PROTOCOL_METHOD</code></a></li>
<li><a href="#all_errors_err_tls_invalid_protocol_version"><code>ERR_TLS_INVALID_PROTOCOL_VERSION</code></a></li>
<li><a href="#all_errors_err_tls_invalid_state"><code>ERR_TLS_INVALID_STATE</code></a></li>
<li><a href="#all_errors_err_tls_protocol_version_conflict"><code>ERR_TLS_PROTOCOL_VERSION_CONFLICT</code></a></li>
<li><a href="#all_errors_err_tls_psk_set_identiy_hint_failed"><code>ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED</code></a></li>
<li><a href="#all_errors_err_tls_renegotiation_disabled"><code>ERR_TLS_RENEGOTIATION_DISABLED</code></a></li>
<li><a href="#all_errors_err_tls_required_server_name"><code>ERR_TLS_REQUIRED_SERVER_NAME</code></a></li>
<li><a href="#all_errors_err_tls_session_attack"><code>ERR_TLS_SESSION_ATTACK</code></a></li>
<li><a href="#all_errors_err_tls_sni_from_server"><code>ERR_TLS_SNI_FROM_SERVER</code></a></li>
<li><a href="#all_errors_err_trace_events_category_required"><code>ERR_TRACE_EVENTS_CATEGORY_REQUIRED</code></a></li>
<li><a href="#all_errors_err_trace_events_unavailable"><code>ERR_TRACE_EVENTS_UNAVAILABLE</code></a></li>
<li><a href="#all_errors_err_transform_already_transforming"><code>ERR_TRANSFORM_ALREADY_TRANSFORMING</code></a></li>
<li><a href="#all_errors_err_transform_with_length_0"><code>ERR_TRANSFORM_WITH_LENGTH_0</code></a></li>
<li><a href="#all_errors_err_tty_init_failed"><code>ERR_TTY_INIT_FAILED</code></a></li>
<li><a href="#all_errors_err_unavailable_during_exit"><code>ERR_UNAVAILABLE_DURING_EXIT</code></a></li>
<li><a href="#all_errors_err_uncaught_exception_capture_already_set"><code>ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET</code></a></li>
<li><a href="#all_errors_err_unescaped_characters"><code>ERR_UNESCAPED_CHARACTERS</code></a></li>
<li><a href="#all_errors_err_unhandled_error"><code>ERR_UNHANDLED_ERROR</code></a></li>
<li><a href="#all_errors_err_unknown_builtin_module"><code>ERR_UNKNOWN_BUILTIN_MODULE</code></a></li>
<li><a href="#all_errors_err_unknown_credential"><code>ERR_UNKNOWN_CREDENTIAL</code></a></li>
<li><a href="#all_errors_err_unknown_encoding"><code>ERR_UNKNOWN_ENCODING</code></a></li>
<li><span class="stability_1"><a href="#all_errors_err_unknown_file_extension"><code>ERR_UNKNOWN_FILE_EXTENSION</code></a></span></li>
<li><span class="stability_1"><a href="#all_errors_err_unknown_module_format"><code>ERR_UNKNOWN_MODULE_FORMAT</code></a></span></li>
<li><a href="#all_errors_err_unknown_signal"><code>ERR_UNKNOWN_SIGNAL</code></a></li>
<li><a href="#all_errors_err_unsupported_dir_import"><code>ERR_UNSUPPORTED_DIR_IMPORT</code></a></li>
<li><a href="#all_errors_err_unsupported_esm_url_scheme"><code>ERR_UNSUPPORTED_ESM_URL_SCHEME</code></a></li>
<li><a href="#all_errors_err_unsupported_resolve_request"><code>ERR_UNSUPPORTED_RESOLVE_REQUEST</code></a></li>
<li><span class="stability_1"><a href="#all_errors_err_use_after_close"><code>ERR_USE_AFTER_CLOSE</code></a></span></li>
<li><a href="#all_errors_err_valid_performance_entry_type"><code>ERR_VALID_PERFORMANCE_ENTRY_TYPE</code></a></li>
<li><a href="#all_errors_err_vm_dynamic_import_callback_missing_flag"><code>ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG</code></a></li>
<li><a href="#all_errors_err_vm_dynamic_import_callback_missing"><code>ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING</code></a></li>
<li><a href="#all_errors_err_vm_module_already_linked"><code>ERR_VM_MODULE_ALREADY_LINKED</code></a></li>
<li><a href="#all_errors_err_vm_module_cached_data_rejected"><code>ERR_VM_MODULE_CACHED_DATA_REJECTED</code></a></li>
<li><a href="#all_errors_err_vm_module_cannot_create_cached_data"><code>ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA</code></a></li>
<li><a href="#all_errors_err_vm_module_different_context"><code>ERR_VM_MODULE_DIFFERENT_CONTEXT</code></a></li>
<li><a href="#all_errors_err_vm_module_link_failure"><code>ERR_VM_MODULE_LINK_FAILURE</code></a></li>
<li><a href="#all_errors_err_vm_module_not_module"><code>ERR_VM_MODULE_NOT_MODULE</code></a></li>
<li><a href="#all_errors_err_vm_module_status"><code>ERR_VM_MODULE_STATUS</code></a></li>
<li><a href="#all_errors_err_wasi_already_started"><code>ERR_WASI_ALREADY_STARTED</code></a></li>
<li><a href="#all_errors_err_wasi_not_started"><code>ERR_WASI_NOT_STARTED</code></a></li>
<li><a href="#all_errors_err_webassembly_response"><code>ERR_WEBASSEMBLY_RESPONSE</code></a></li>
<li><a href="#all_errors_err_worker_init_failed"><code>ERR_WORKER_INIT_FAILED</code></a></li>
<li><a href="#all_errors_err_worker_invalid_exec_argv"><code>ERR_WORKER_INVALID_EXEC_ARGV</code></a></li>
<li><a href="#all_errors_err_worker_not_running"><code>ERR_WORKER_NOT_RUNNING</code></a></li>
<li><a href="#all_errors_err_worker_out_of_memory"><code>ERR_WORKER_OUT_OF_MEMORY</code></a></li>
<li><a href="#all_errors_err_worker_path"><code>ERR_WORKER_PATH</code></a></li>
<li><a href="#all_errors_err_worker_unserializable_error"><code>ERR_WORKER_UNSERIALIZABLE_ERROR</code></a></li>
<li><a href="#all_errors_err_worker_unsupported_operation"><code>ERR_WORKER_UNSUPPORTED_OPERATION</code></a></li>
<li><a href="#all_errors_err_zlib_initialization_failed"><code>ERR_ZLIB_INITIALIZATION_FAILED</code></a></li>
<li><a href="#all_errors_hpe_header_overflow"><code>HPE_HEADER_OVERFLOW</code></a></li>
<li><a href="#all_errors_hpe_chunk_extensions_overflow"><code>HPE_CHUNK_EXTENSIONS_OVERFLOW</code></a></li>
<li><a href="#all_errors_hpe_unexpected_content_length"><code>HPE_UNEXPECTED_CONTENT_LENGTH</code></a></li>
<li><a href="#all_errors_module_not_found"><code>MODULE_NOT_FOUND</code></a></li>
</ul>
</li>
<li><span class="stability_0"><a href="#all_errors_legacy-nodejs-error-codes">Legacy Node.js error codes</a></span>
<ul>
<li><a href="#all_errors_err_cannot_transfer_object"><code>ERR_CANNOT_TRANSFER_OBJECT</code></a></li>
<li><a href="#all_errors_err_crypto_hash_digest_no_utf16"><code>ERR_CRYPTO_HASH_DIGEST_NO_UTF16</code></a></li>
<li><a href="#all_errors_err_http2_frame_error"><code>ERR_HTTP2_FRAME_ERROR</code></a></li>
<li><a href="#all_errors_err_http2_headers_object"><code>ERR_HTTP2_HEADERS_OBJECT</code></a></li>
<li><a href="#all_errors_err_http2_header_required"><code>ERR_HTTP2_HEADER_REQUIRED</code></a></li>
<li><a href="#all_errors_err_http2_info_headers_after_respond"><code>ERR_HTTP2_INFO_HEADERS_AFTER_RESPOND</code></a></li>
<li><a href="#all_errors_err_http2_stream_closed"><code>ERR_HTTP2_STREAM_CLOSED</code></a></li>
<li><a href="#all_errors_err_http_invalid_char"><code>ERR_HTTP_INVALID_CHAR</code></a></li>
<li><a href="#all_errors_err_index_out_of_range"><code>ERR_INDEX_OUT_OF_RANGE</code></a></li>
<li><a href="#all_errors_err_invalid_opt_value"><code>ERR_INVALID_OPT_VALUE</code></a></li>
<li><a href="#all_errors_err_invalid_opt_value_encoding"><code>ERR_INVALID_OPT_VALUE_ENCODING</code></a></li>
<li><a href="#all_errors_err_missing_message_port_in_transfer_list"><code>ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST</code></a></li>
<li><a href="#all_errors_err_napi_cons_prototype_object"><code>ERR_NAPI_CONS_PROTOTYPE_OBJECT</code></a></li>
<li><span class="stability_1"><a href="#all_errors_err_network_import_bad_response"><code>ERR_NETWORK_IMPORT_BAD_RESPONSE</code></a></span></li>
<li><span class="stability_1"><a href="#all_errors_err_network_import_disallowed"><code>ERR_NETWORK_IMPORT_DISALLOWED</code></a></span></li>
<li><a href="#all_errors_err_no_longer_supported"><code>ERR_NO_LONGER_SUPPORTED</code></a></li>
<li><a href="#all_errors_err_operation_failed"><code>ERR_OPERATION_FAILED</code></a></li>
<li><a href="#all_errors_err_outofmemory"><code>ERR_OUTOFMEMORY</code></a></li>
<li><a href="#all_errors_err_parse_history_data"><code>ERR_PARSE_HISTORY_DATA</code></a></li>
<li><a href="#all_errors_err_socket_cannot_send"><code>ERR_SOCKET_CANNOT_SEND</code></a></li>
<li><a href="#all_errors_err_stderr_close"><code>ERR_STDERR_CLOSE</code></a></li>
<li><a href="#all_errors_err_stdout_close"><code>ERR_STDOUT_CLOSE</code></a></li>
<li><a href="#all_errors_err_stream_read_not_implemented"><code>ERR_STREAM_READ_NOT_IMPLEMENTED</code></a></li>
<li><a href="#all_errors_err_tls_renegotiation_failed"><code>ERR_TLS_RENEGOTIATION_FAILED</code></a></li>
<li><a href="#all_errors_err_transferring_externalized_sharedarraybuffer"><code>ERR_TRANSFERRING_EXTERNALIZED_SHAREDARRAYBUFFER</code></a></li>
<li><a href="#all_errors_err_unknown_stdin_type"><code>ERR_UNKNOWN_STDIN_TYPE</code></a></li>
<li><a href="#all_errors_err_unknown_stream_type"><code>ERR_UNKNOWN_STREAM_TYPE</code></a></li>
<li><a href="#all_errors_err_v8breakiterator"><code>ERR_V8BREAKITERATOR</code></a></li>
<li><a href="#all_errors_err_value_out_of_range"><code>ERR_VALUE_OUT_OF_RANGE</code></a></li>
<li><a href="#all_errors_err_vm_module_not_linked"><code>ERR_VM_MODULE_NOT_LINKED</code></a></li>
<li><a href="#all_errors_err_vm_module_linking_errored"><code>ERR_VM_MODULE_LINKING_ERRORED</code></a></li>
<li><a href="#all_errors_err_worker_unsupported_extension"><code>ERR_WORKER_UNSUPPORTED_EXTENSION</code></a></li>
<li><a href="#all_errors_err_zlib_binding_closed"><code>ERR_ZLIB_BINDING_CLOSED</code></a></li>
<li><a href="#all_errors_err_cpu_usage"><code>ERR_CPU_USAGE</code></a></li>
</ul>
</li>
<li><a href="#all_errors_openssl-error-codes">OpenSSL Error Codes</a>
<ul>
<li><a href="#all_errors_time-validity-errors">Time Validity Errors</a>
<ul>
<li><a href="#all_errors_cert_not_yet_valid"><code>CERT_NOT_YET_VALID</code></a></li>
<li><a href="#all_errors_cert_has_expired"><code>CERT_HAS_EXPIRED</code></a></li>
<li><a href="#all_errors_crl_not_yet_valid"><code>CRL_NOT_YET_VALID</code></a></li>
<li><a href="#all_errors_crl_has_expired"><code>CRL_HAS_EXPIRED</code></a></li>
<li><a href="#all_errors_cert_revoked"><code>CERT_REVOKED</code></a></li>
</ul>
</li>
<li><a href="#all_errors_trust-or-chain-related-errors">Trust or Chain Related Errors</a>
<ul>
<li><a href="#all_errors_unable_to_get_issuer_cert"><code>UNABLE_TO_GET_ISSUER_CERT</code></a></li>
<li><a href="#all_errors_unable_to_get_issuer_cert_locally"><code>UNABLE_TO_GET_ISSUER_CERT_LOCALLY</code></a></li>
<li><a href="#all_errors_depth_zero_self_signed_cert"><code>DEPTH_ZERO_SELF_SIGNED_CERT</code></a></li>
<li><a href="#all_errors_self_signed_cert_in_chain"><code>SELF_SIGNED_CERT_IN_CHAIN</code></a></li>
<li><a href="#all_errors_cert_chain_too_long"><code>CERT_CHAIN_TOO_LONG</code></a></li>
<li><a href="#all_errors_unable_to_get_crl"><code>UNABLE_TO_GET_CRL</code></a></li>
<li><a href="#all_errors_unable_to_verify_leaf_signature"><code>UNABLE_TO_VERIFY_LEAF_SIGNATURE</code></a></li>
<li><a href="#all_errors_cert_untrusted"><code>CERT_UNTRUSTED</code></a></li>
</ul>
</li>
<li><a href="#all_errors_basic-extension-errors">Basic Extension Errors</a>
<ul>
<li><a href="#all_errors_invalid_ca"><code>INVALID_CA</code></a></li>
<li><a href="#all_errors_path_length_exceeded"><code>PATH_LENGTH_EXCEEDED</code></a></li>
</ul>
</li>
<li><a href="#all_errors_name-related-errors">Name Related Errors</a>
<ul>
<li><a href="#all_errors_hostname_mismatch"><code>HOSTNAME_MISMATCH</code></a></li>
</ul>
</li>
<li><a href="#all_errors_usage-and-policy-errors">Usage and Policy Errors</a>
<ul>
<li><a href="#all_errors_invalid_purpose"><code>INVALID_PURPOSE</code></a></li>
<li><a href="#all_errors_cert_rejected"><code>CERT_REJECTED</code></a></li>
</ul>
</li>
<li><a href="#all_errors_formatting-errors">Formatting Errors</a>
<ul>
<li><a href="#all_errors_cert_signature_failure"><code>CERT_SIGNATURE_FAILURE</code></a></li>
<li><a href="#all_errors_crl_signature_failure"><code>CRL_SIGNATURE_FAILURE</code></a></li>
<li><a href="#all_errors_error_in_cert_not_before_field"><code>ERROR_IN_CERT_NOT_BEFORE_FIELD</code></a></li>
<li><a href="#all_errors_error_in_cert_not_after_field"><code>ERROR_IN_CERT_NOT_AFTER_FIELD</code></a></li>
<li><a href="#all_errors_error_in_crl_last_update_field"><code>ERROR_IN_CRL_LAST_UPDATE_FIELD</code></a></li>
<li><a href="#all_errors_error_in_crl_next_update_field"><code>ERROR_IN_CRL_NEXT_UPDATE_FIELD</code></a></li>
<li><a href="#all_errors_unable_to_decrypt_cert_signature"><code>UNABLE_TO_DECRYPT_CERT_SIGNATURE</code></a></li>
<li><a href="#all_errors_unable_to_decrypt_crl_signature"><code>UNABLE_TO_DECRYPT_CRL_SIGNATURE</code></a></li>
<li><a href="#all_errors_unable_to_decode_issuer_public_key"><code>UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY</code></a></li>
</ul>
</li>
<li><a href="#all_errors_other-openssl-errors">Other OpenSSL Errors</a>
<ul>
<li><a href="#all_errors_out_of_mem"><code>OUT_OF_MEM</code></a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_events_events">Events</a></span>
<ul>
<li><a href="#all_events_passing-arguments-and-this-to-listeners">Passing arguments and <code>this</code> to listeners</a></li>
<li><a href="#all_events_asynchronous-vs-synchronous">Asynchronous vs. synchronous</a></li>
<li><a href="#all_events_handling-events-only-once">Handling events only once</a></li>
<li><a href="#all_events_error-events">Error events</a></li>
<li><a href="#all_events_capture-rejections-of-promises">Capture rejections of promises</a></li>
<li><a href="#all_events_class-eventemitter">Class: <code>EventEmitter</code></a>
<ul>
<li><a href="#all_events_event-newlistener">Event: <code>'newListener'</code></a></li>
<li><a href="#all_events_event-removelistener">Event: <code>'removeListener'</code></a></li>
<li><a href="#all_events_emitteraddlistenereventname-listener"><code>emitter.addListener(eventName, listener)</code></a></li>
<li><a href="#all_events_emitteremiteventname-args"><code>emitter.emit(eventName[, ...args])</code></a></li>
<li><a href="#all_events_emittereventnames"><code>emitter.eventNames()</code></a></li>
<li><a href="#all_events_emittergetmaxlisteners"><code>emitter.getMaxListeners()</code></a></li>
<li><a href="#all_events_emitterlistenercounteventname-listener"><code>emitter.listenerCount(eventName[, listener])</code></a></li>
<li><a href="#all_events_emitterlistenerseventname"><code>emitter.listeners(eventName)</code></a></li>
<li><a href="#all_events_emitteroffeventname-listener"><code>emitter.off(eventName, listener)</code></a></li>
<li><a href="#all_events_emitteroneventname-listener"><code>emitter.on(eventName, listener)</code></a></li>
<li><a href="#all_events_emitteronceeventname-listener"><code>emitter.once(eventName, listener)</code></a></li>
<li><a href="#all_events_emitterprependlistenereventname-listener"><code>emitter.prependListener(eventName, listener)</code></a></li>
<li><a href="#all_events_emitterprependoncelistenereventname-listener"><code>emitter.prependOnceListener(eventName, listener)</code></a></li>
<li><a href="#all_events_emitterremovealllistenerseventname"><code>emitter.removeAllListeners([eventName])</code></a></li>
<li><a href="#all_events_emitterremovelistenereventname-listener"><code>emitter.removeListener(eventName, listener)</code></a></li>
<li><a href="#all_events_emittersetmaxlistenersn"><code>emitter.setMaxListeners(n)</code></a></li>
<li><a href="#all_events_emitterrawlistenerseventname"><code>emitter.rawListeners(eventName)</code></a></li>
<li><a href="#all_events_emittersymbolfornodejsrejectionerr-eventname-args"><code>emitter[Symbol.for('nodejs.rejection')](err, eventName[, ...args])</code></a></li>
</ul>
</li>
<li><a href="#all_events_eventsdefaultmaxlisteners"><code>events.defaultMaxListeners</code></a></li>
<li><a href="#all_events_eventserrormonitor"><code>events.errorMonitor</code></a></li>
<li><a href="#all_events_eventsgeteventlistenersemitterortarget-eventname"><code>events.getEventListeners(emitterOrTarget, eventName)</code></a></li>
<li><a href="#all_events_eventsgetmaxlistenersemitterortarget"><code>events.getMaxListeners(emitterOrTarget)</code></a></li>
<li><a href="#all_events_eventsonceemitter-name-options"><code>events.once(emitter, name[, options])</code></a>
<ul>
<li><a href="#all_events_awaiting-multiple-events-emitted-on-processnexttick">Awaiting multiple events emitted on <code>process.nextTick()</code></a></li>
</ul>
</li>
<li><a href="#all_events_eventscapturerejections"><code>events.captureRejections</code></a></li>
<li><a href="#all_events_eventscapturerejectionsymbol"><code>events.captureRejectionSymbol</code></a></li>
<li><span class="stability_0"><a href="#all_events_eventslistenercountemitter-eventname"><code>events.listenerCount(emitter, eventName)</code></a></span></li>
<li><a href="#all_events_eventsonemitter-eventname-options"><code>events.on(emitter, eventName[, options])</code></a></li>
<li><a href="#all_events_eventssetmaxlistenersn-eventtargets"><code>events.setMaxListeners(n[, ...eventTargets])</code></a></li>
<li><span class="stability_1"><a href="#all_events_eventsaddabortlistenersignal-listener"><code>events.addAbortListener(signal, listener)</code></a></span></li>
<li><a href="#all_events_class-eventseventemitterasyncresource-extends-eventemitter">Class: <code>events.EventEmitterAsyncResource extends EventEmitter</code></a>
<ul>
<li><a href="#all_events_new-eventseventemitterasyncresourceoptions"><code>new events.EventEmitterAsyncResource([options])</code></a></li>
<li><a href="#all_events_eventemitterasyncresourceasyncid"><code>eventemitterasyncresource.asyncId</code></a></li>
<li><a href="#all_events_eventemitterasyncresourceasyncresource"><code>eventemitterasyncresource.asyncResource</code></a></li>
<li><a href="#all_events_eventemitterasyncresourceemitdestroy"><code>eventemitterasyncresource.emitDestroy()</code></a></li>
<li><a href="#all_events_eventemitterasyncresourcetriggerasyncid"><code>eventemitterasyncresource.triggerAsyncId</code></a></li>
</ul>
</li>
<li><a href="#all_events_eventtarget-and-event-api"><code>EventTarget</code> and <code>Event</code> API</a>
<ul>
<li><a href="#all_events_nodejs-eventtarget-vs-dom-eventtarget">Node.js <code>EventTarget</code> vs. DOM <code>EventTarget</code></a></li>
<li><a href="#all_events_nodeeventtarget-vs-eventemitter"><code>NodeEventTarget</code> vs. <code>EventEmitter</code></a></li>
<li><a href="#all_events_event-listener">Event listener</a></li>
<li><a href="#all_events_eventtarget-error-handling"><code>EventTarget</code> error handling</a></li>
<li><a href="#all_events_class-event">Class: <code>Event</code></a>
<ul>
<li><a href="#all_events_eventbubbles"><code>event.bubbles</code></a></li>
<li><span class="stability_3"><a href="#all_events_eventcancelbubble"><code>event.cancelBubble</code></a></span></li>
<li><a href="#all_events_eventcancelable"><code>event.cancelable</code></a></li>
<li><a href="#all_events_eventcomposed"><code>event.composed</code></a></li>
<li><a href="#all_events_eventcomposedpath"><code>event.composedPath()</code></a></li>
<li><a href="#all_events_eventcurrenttarget"><code>event.currentTarget</code></a></li>
<li><a href="#all_events_eventdefaultprevented"><code>event.defaultPrevented</code></a></li>
<li><a href="#all_events_eventeventphase"><code>event.eventPhase</code></a></li>
<li><span class="stability_3"><a href="#all_events_eventiniteventtype-bubbles-cancelable"><code>event.initEvent(type[, bubbles[, cancelable]])</code></a></span></li>
<li><a href="#all_events_eventistrusted"><code>event.isTrusted</code></a></li>
<li><a href="#all_events_eventpreventdefault"><code>event.preventDefault()</code></a></li>
<li><span class="stability_3"><a href="#all_events_eventreturnvalue"><code>event.returnValue</code></a></span></li>
<li><span class="stability_3"><a href="#all_events_eventsrcelement"><code>event.srcElement</code></a></span></li>
<li><a href="#all_events_eventstopimmediatepropagation"><code>event.stopImmediatePropagation()</code></a></li>
<li><a href="#all_events_eventstoppropagation"><code>event.stopPropagation()</code></a></li>
<li><a href="#all_events_eventtarget"><code>event.target</code></a></li>
<li><a href="#all_events_eventtimestamp"><code>event.timeStamp</code></a></li>
<li><a href="#all_events_eventtype"><code>event.type</code></a></li>
</ul>
</li>
<li><a href="#all_events_class-eventtarget">Class: <code>EventTarget</code></a>
<ul>
<li><a href="#all_events_eventtargetaddeventlistenertype-listener-options"><code>eventTarget.addEventListener(type, listener[, options])</code></a></li>
<li><a href="#all_events_eventtargetdispatcheventevent"><code>eventTarget.dispatchEvent(event)</code></a></li>
<li><a href="#all_events_eventtargetremoveeventlistenertype-listener-options"><code>eventTarget.removeEventListener(type, listener[, options])</code></a></li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_events_class-customevent">Class: <code>CustomEvent</code></a></span>
<ul>
<li><span class="stability_2"><a href="#all_events_eventdetail"><code>event.detail</code></a></span></li>
</ul>
</li>
<li><a href="#all_events_class-nodeeventtarget">Class: <code>NodeEventTarget</code></a>
<ul>
<li><a href="#all_events_nodeeventtargetaddlistenertype-listener"><code>nodeEventTarget.addListener(type, listener)</code></a></li>
<li><a href="#all_events_nodeeventtargetemittype-arg"><code>nodeEventTarget.emit(type, arg)</code></a></li>
<li><a href="#all_events_nodeeventtargeteventnames"><code>nodeEventTarget.eventNames()</code></a></li>
<li><a href="#all_events_nodeeventtargetlistenercounttype"><code>nodeEventTarget.listenerCount(type)</code></a></li>
<li><a href="#all_events_nodeeventtargetsetmaxlistenersn"><code>nodeEventTarget.setMaxListeners(n)</code></a></li>
<li><a href="#all_events_nodeeventtargetgetmaxlisteners"><code>nodeEventTarget.getMaxListeners()</code></a></li>
<li><a href="#all_events_nodeeventtargetofftype-listener-options"><code>nodeEventTarget.off(type, listener[, options])</code></a></li>
<li><a href="#all_events_nodeeventtargetontype-listener"><code>nodeEventTarget.on(type, listener)</code></a></li>
<li><a href="#all_events_nodeeventtargetoncetype-listener"><code>nodeEventTarget.once(type, listener)</code></a></li>
<li><a href="#all_events_nodeeventtargetremovealllistenerstype"><code>nodeEventTarget.removeAllListeners([type])</code></a></li>
<li><a href="#all_events_nodeeventtargetremovelistenertype-listener-options"><code>nodeEventTarget.removeListener(type, listener[, options])</code></a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_fs_file-system">File system</a></span>
<ul>
<li><a href="#all_fs_promise-example">Promise example</a></li>
<li><a href="#all_fs_callback-example">Callback example</a></li>
<li><a href="#all_fs_synchronous-example">Synchronous example</a></li>
<li><a href="#all_fs_promises-api">Promises API</a>
<ul>
<li><a href="#all_fs_class-filehandle">Class: <code>FileHandle</code></a>
<ul>
<li><a href="#all_fs_event-close">Event: <code>'close'</code></a></li>
<li><a href="#all_fs_filehandleappendfiledata-options"><code>filehandle.appendFile(data[, options])</code></a></li>
<li><a href="#all_fs_filehandlechmodmode"><code>filehandle.chmod(mode)</code></a></li>
<li><a href="#all_fs_filehandlechownuid-gid"><code>filehandle.chown(uid, gid)</code></a></li>
<li><a href="#all_fs_filehandleclose"><code>filehandle.close()</code></a></li>
<li><a href="#all_fs_filehandlecreatereadstreamoptions"><code>filehandle.createReadStream([options])</code></a></li>
<li><a href="#all_fs_filehandlecreatewritestreamoptions"><code>filehandle.createWriteStream([options])</code></a></li>
<li><a href="#all_fs_filehandledatasync"><code>filehandle.datasync()</code></a></li>
<li><a href="#all_fs_filehandlefd"><code>filehandle.fd</code></a></li>
<li><a href="#all_fs_filehandlereadbuffer-offset-length-position"><code>filehandle.read(buffer, offset, length, position)</code></a></li>
<li><a href="#all_fs_filehandlereadoptions"><code>filehandle.read([options])</code></a></li>
<li><a href="#all_fs_filehandlereadbuffer-options"><code>filehandle.read(buffer[, options])</code></a></li>
<li><span class="stability_1"><a href="#all_fs_filehandlereadablewebstreamoptions"><code>filehandle.readableWebStream([options])</code></a></span></li>
<li><a href="#all_fs_filehandlereadfileoptions"><code>filehandle.readFile(options)</code></a></li>
<li><a href="#all_fs_filehandlereadlinesoptions"><code>filehandle.readLines([options])</code></a></li>
<li><a href="#all_fs_filehandlereadvbuffers-position"><code>filehandle.readv(buffers[, position])</code></a></li>
<li><a href="#all_fs_filehandlestatoptions"><code>filehandle.stat([options])</code></a></li>
<li><a href="#all_fs_filehandlesync"><code>filehandle.sync()</code></a></li>
<li><a href="#all_fs_filehandletruncatelen"><code>filehandle.truncate(len)</code></a></li>
<li><a href="#all_fs_filehandleutimesatime-mtime"><code>filehandle.utimes(atime, mtime)</code></a></li>
<li><a href="#all_fs_filehandlewritebuffer-offset-length-position"><code>filehandle.write(buffer, offset[, length[, position]])</code></a></li>
<li><a href="#all_fs_filehandlewritebuffer-options"><code>filehandle.write(buffer[, options])</code></a></li>
<li><a href="#all_fs_filehandlewritestring-position-encoding"><code>filehandle.write(string[, position[, encoding]])</code></a></li>
<li><a href="#all_fs_filehandlewritefiledata-options"><code>filehandle.writeFile(data, options)</code></a></li>
<li><a href="#all_fs_filehandlewritevbuffers-position"><code>filehandle.writev(buffers[, position])</code></a></li>
<li><span class="stability_1"><a href="#all_fs_filehandlesymbolasyncdispose"><code>filehandle[Symbol.asyncDispose]()</code></a></span></li>
</ul>
</li>
<li><a href="#all_fs_fspromisesaccesspath-mode"><code>fsPromises.access(path[, mode])</code></a></li>
<li><a href="#all_fs_fspromisesappendfilepath-data-options"><code>fsPromises.appendFile(path, data[, options])</code></a></li>
<li><a href="#all_fs_fspromiseschmodpath-mode"><code>fsPromises.chmod(path, mode)</code></a></li>
<li><a href="#all_fs_fspromiseschownpath-uid-gid"><code>fsPromises.chown(path, uid, gid)</code></a></li>
<li><a href="#all_fs_fspromisescopyfilesrc-dest-mode"><code>fsPromises.copyFile(src, dest[, mode])</code></a></li>
<li><span class="stability_1"><a href="#all_fs_fspromisescpsrc-dest-options"><code>fsPromises.cp(src, dest[, options])</code></a></span></li>
<li><a href="#all_fs_fspromiseslchmodpath-mode"><code>fsPromises.lchmod(path, mode)</code></a></li>
<li><a href="#all_fs_fspromiseslchownpath-uid-gid"><code>fsPromises.lchown(path, uid, gid)</code></a></li>
<li><a href="#all_fs_fspromiseslutimespath-atime-mtime"><code>fsPromises.lutimes(path, atime, mtime)</code></a></li>
<li><a href="#all_fs_fspromiseslinkexistingpath-newpath"><code>fsPromises.link(existingPath, newPath)</code></a></li>
<li><a href="#all_fs_fspromiseslstatpath-options"><code>fsPromises.lstat(path[, options])</code></a></li>
<li><a href="#all_fs_fspromisesmkdirpath-options"><code>fsPromises.mkdir(path[, options])</code></a></li>
<li><a href="#all_fs_fspromisesmkdtempprefix-options"><code>fsPromises.mkdtemp(prefix[, options])</code></a></li>
<li><a href="#all_fs_fspromisesopenpath-flags-mode"><code>fsPromises.open(path, flags[, mode])</code></a></li>
<li><a href="#all_fs_fspromisesopendirpath-options"><code>fsPromises.opendir(path[, options])</code></a></li>
<li><a href="#all_fs_fspromisesreaddirpath-options"><code>fsPromises.readdir(path[, options])</code></a></li>
<li><a href="#all_fs_fspromisesreadfilepath-options"><code>fsPromises.readFile(path[, options])</code></a></li>
<li><a href="#all_fs_fspromisesreadlinkpath-options"><code>fsPromises.readlink(path[, options])</code></a></li>
<li><a href="#all_fs_fspromisesrealpathpath-options"><code>fsPromises.realpath(path[, options])</code></a></li>
<li><a href="#all_fs_fspromisesrenameoldpath-newpath"><code>fsPromises.rename(oldPath, newPath)</code></a></li>
<li><a href="#all_fs_fspromisesrmdirpath-options"><code>fsPromises.rmdir(path[, options])</code></a></li>
<li><a href="#all_fs_fspromisesrmpath-options"><code>fsPromises.rm(path[, options])</code></a></li>
<li><a href="#all_fs_fspromisesstatpath-options"><code>fsPromises.stat(path[, options])</code></a></li>
<li><a href="#all_fs_fspromisesstatfspath-options"><code>fsPromises.statfs(path[, options])</code></a></li>
<li><a href="#all_fs_fspromisessymlinktarget-path-type"><code>fsPromises.symlink(target, path[, type])</code></a></li>
<li><a href="#all_fs_fspromisestruncatepath-len"><code>fsPromises.truncate(path[, len])</code></a></li>
<li><a href="#all_fs_fspromisesunlinkpath"><code>fsPromises.unlink(path)</code></a></li>
<li><a href="#all_fs_fspromisesutimespath-atime-mtime"><code>fsPromises.utimes(path, atime, mtime)</code></a></li>
<li><a href="#all_fs_fspromiseswatchfilename-options"><code>fsPromises.watch(filename[, options])</code></a></li>
<li><a href="#all_fs_fspromiseswritefilefile-data-options"><code>fsPromises.writeFile(file, data[, options])</code></a></li>
<li><a href="#all_fs_fspromisesconstants"><code>fsPromises.constants</code></a></li>
</ul>
</li>
<li><a href="#all_fs_callback-api">Callback API</a>
<ul>
<li><a href="#all_fs_fsaccesspath-mode-callback"><code>fs.access(path[, mode], callback)</code></a></li>
<li><a href="#all_fs_fsappendfilepath-data-options-callback"><code>fs.appendFile(path, data[, options], callback)</code></a></li>
<li><a href="#all_fs_fschmodpath-mode-callback"><code>fs.chmod(path, mode, callback)</code></a>
<ul>
<li><a href="#all_fs_file-modes">File modes</a></li>
</ul>
</li>
<li><a href="#all_fs_fschownpath-uid-gid-callback"><code>fs.chown(path, uid, gid, callback)</code></a></li>
<li><a href="#all_fs_fsclosefd-callback"><code>fs.close(fd[, callback])</code></a></li>
<li><a href="#all_fs_fscopyfilesrc-dest-mode-callback"><code>fs.copyFile(src, dest[, mode], callback)</code></a></li>
<li><span class="stability_1"><a href="#all_fs_fscpsrc-dest-options-callback"><code>fs.cp(src, dest[, options], callback)</code></a></span></li>
<li><a href="#all_fs_fscreatereadstreampath-options"><code>fs.createReadStream(path[, options])</code></a></li>
<li><a href="#all_fs_fscreatewritestreampath-options"><code>fs.createWriteStream(path[, options])</code></a></li>
<li><span class="stability_0"><a href="#all_fs_fsexistspath-callback"><code>fs.exists(path, callback)</code></a></span></li>
<li><a href="#all_fs_fsfchmodfd-mode-callback"><code>fs.fchmod(fd, mode, callback)</code></a></li>
<li><a href="#all_fs_fsfchownfd-uid-gid-callback"><code>fs.fchown(fd, uid, gid, callback)</code></a></li>
<li><a href="#all_fs_fsfdatasyncfd-callback"><code>fs.fdatasync(fd, callback)</code></a></li>
<li><a href="#all_fs_fsfstatfd-options-callback"><code>fs.fstat(fd[, options], callback)</code></a></li>
<li><a href="#all_fs_fsfsyncfd-callback"><code>fs.fsync(fd, callback)</code></a></li>
<li><a href="#all_fs_fsftruncatefd-len-callback"><code>fs.ftruncate(fd[, len], callback)</code></a></li>
<li><a href="#all_fs_fsfutimesfd-atime-mtime-callback"><code>fs.futimes(fd, atime, mtime, callback)</code></a></li>
<li><a href="#all_fs_fslchmodpath-mode-callback"><code>fs.lchmod(path, mode, callback)</code></a></li>
<li><a href="#all_fs_fslchownpath-uid-gid-callback"><code>fs.lchown(path, uid, gid, callback)</code></a></li>
<li><a href="#all_fs_fslutimespath-atime-mtime-callback"><code>fs.lutimes(path, atime, mtime, callback)</code></a></li>
<li><a href="#all_fs_fslinkexistingpath-newpath-callback"><code>fs.link(existingPath, newPath, callback)</code></a></li>
<li><a href="#all_fs_fslstatpath-options-callback"><code>fs.lstat(path[, options], callback)</code></a></li>
<li><a href="#all_fs_fsmkdirpath-options-callback"><code>fs.mkdir(path[, options], callback)</code></a></li>
<li><a href="#all_fs_fsmkdtempprefix-options-callback"><code>fs.mkdtemp(prefix[, options], callback)</code></a></li>
<li><a href="#all_fs_fsopenpath-flags-mode-callback"><code>fs.open(path[, flags[, mode]], callback)</code></a></li>
<li><span class="stability_1"><a href="#all_fs_fsopenasblobpath-options"><code>fs.openAsBlob(path[, options])</code></a></span></li>
<li><a href="#all_fs_fsopendirpath-options-callback"><code>fs.opendir(path[, options], callback)</code></a></li>
<li><a href="#all_fs_fsreadfd-buffer-offset-length-position-callback"><code>fs.read(fd, buffer, offset, length, position, callback)</code></a></li>
<li><a href="#all_fs_fsreadfd-options-callback"><code>fs.read(fd[, options], callback)</code></a></li>
<li><a href="#all_fs_fsreadfd-buffer-options-callback"><code>fs.read(fd, buffer[, options], callback)</code></a></li>
<li><a href="#all_fs_fsreaddirpath-options-callback"><code>fs.readdir(path[, options], callback)</code></a></li>
<li><a href="#all_fs_fsreadfilepath-options-callback"><code>fs.readFile(path[, options], callback)</code></a>
<ul>
<li><a href="#all_fs_file-descriptors">File descriptors</a></li>
<li><a href="#all_fs_performance-considerations">Performance Considerations</a></li>
</ul>
</li>
<li><a href="#all_fs_fsreadlinkpath-options-callback"><code>fs.readlink(path[, options], callback)</code></a></li>
<li><a href="#all_fs_fsreadvfd-buffers-position-callback"><code>fs.readv(fd, buffers[, position], callback)</code></a></li>
<li><a href="#all_fs_fsrealpathpath-options-callback"><code>fs.realpath(path[, options], callback)</code></a></li>
<li><a href="#all_fs_fsrealpathnativepath-options-callback"><code>fs.realpath.native(path[, options], callback)</code></a></li>
<li><a href="#all_fs_fsrenameoldpath-newpath-callback"><code>fs.rename(oldPath, newPath, callback)</code></a></li>
<li><a href="#all_fs_fsrmdirpath-options-callback"><code>fs.rmdir(path[, options], callback)</code></a></li>
<li><a href="#all_fs_fsrmpath-options-callback"><code>fs.rm(path[, options], callback)</code></a></li>
<li><a href="#all_fs_fsstatpath-options-callback"><code>fs.stat(path[, options], callback)</code></a></li>
<li><a href="#all_fs_fsstatfspath-options-callback"><code>fs.statfs(path[, options], callback)</code></a></li>
<li><a href="#all_fs_fssymlinktarget-path-type-callback"><code>fs.symlink(target, path[, type], callback)</code></a></li>
<li><a href="#all_fs_fstruncatepath-len-callback"><code>fs.truncate(path[, len], callback)</code></a></li>
<li><a href="#all_fs_fsunlinkpath-callback"><code>fs.unlink(path, callback)</code></a></li>
<li><a href="#all_fs_fsunwatchfilefilename-listener"><code>fs.unwatchFile(filename[, listener])</code></a></li>
<li><a href="#all_fs_fsutimespath-atime-mtime-callback"><code>fs.utimes(path, atime, mtime, callback)</code></a></li>
<li><a href="#all_fs_fswatchfilename-options-listener"><code>fs.watch(filename[, options][, listener])</code></a>
<ul>
<li><a href="#all_fs_caveats">Caveats</a>
<ul>
<li><a href="#all_fs_availability">Availability</a></li>
<li><a href="#all_fs_inodes">Inodes</a></li>
<li><a href="#all_fs_filename-argument">Filename argument</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_fs_fswatchfilefilename-options-listener"><code>fs.watchFile(filename[, options], listener)</code></a></li>
<li><a href="#all_fs_fswritefd-buffer-offset-length-position-callback"><code>fs.write(fd, buffer, offset[, length[, position]], callback)</code></a></li>
<li><a href="#all_fs_fswritefd-buffer-options-callback"><code>fs.write(fd, buffer[, options], callback)</code></a></li>
<li><a href="#all_fs_fswritefd-string-position-encoding-callback"><code>fs.write(fd, string[, position[, encoding]], callback)</code></a></li>
<li><a href="#all_fs_fswritefilefile-data-options-callback"><code>fs.writeFile(file, data[, options], callback)</code></a>
<ul>
<li><a href="#all_fs_using-fswritefile-with-file-descriptors">Using <code>fs.writeFile()</code> with file descriptors</a></li>
</ul>
</li>
<li><a href="#all_fs_fswritevfd-buffers-position-callback"><code>fs.writev(fd, buffers[, position], callback)</code></a></li>
</ul>
</li>
<li><a href="#all_fs_synchronous-api">Synchronous API</a>
<ul>
<li><a href="#all_fs_fsaccesssyncpath-mode"><code>fs.accessSync(path[, mode])</code></a></li>
<li><a href="#all_fs_fsappendfilesyncpath-data-options"><code>fs.appendFileSync(path, data[, options])</code></a></li>
<li><a href="#all_fs_fschmodsyncpath-mode"><code>fs.chmodSync(path, mode)</code></a></li>
<li><a href="#all_fs_fschownsyncpath-uid-gid"><code>fs.chownSync(path, uid, gid)</code></a></li>
<li><a href="#all_fs_fsclosesyncfd"><code>fs.closeSync(fd)</code></a></li>
<li><a href="#all_fs_fscopyfilesyncsrc-dest-mode"><code>fs.copyFileSync(src, dest[, mode])</code></a></li>
<li><span class="stability_1"><a href="#all_fs_fscpsyncsrc-dest-options"><code>fs.cpSync(src, dest[, options])</code></a></span></li>
<li><a href="#all_fs_fsexistssyncpath"><code>fs.existsSync(path)</code></a></li>
<li><a href="#all_fs_fsfchmodsyncfd-mode"><code>fs.fchmodSync(fd, mode)</code></a></li>
<li><a href="#all_fs_fsfchownsyncfd-uid-gid"><code>fs.fchownSync(fd, uid, gid)</code></a></li>
<li><a href="#all_fs_fsfdatasyncsyncfd"><code>fs.fdatasyncSync(fd)</code></a></li>
<li><a href="#all_fs_fsfstatsyncfd-options"><code>fs.fstatSync(fd[, options])</code></a></li>
<li><a href="#all_fs_fsfsyncsyncfd"><code>fs.fsyncSync(fd)</code></a></li>
<li><a href="#all_fs_fsftruncatesyncfd-len"><code>fs.ftruncateSync(fd[, len])</code></a></li>
<li><a href="#all_fs_fsfutimessyncfd-atime-mtime"><code>fs.futimesSync(fd, atime, mtime)</code></a></li>
<li><a href="#all_fs_fslchmodsyncpath-mode"><code>fs.lchmodSync(path, mode)</code></a></li>
<li><a href="#all_fs_fslchownsyncpath-uid-gid"><code>fs.lchownSync(path, uid, gid)</code></a></li>
<li><a href="#all_fs_fslutimessyncpath-atime-mtime"><code>fs.lutimesSync(path, atime, mtime)</code></a></li>
<li><a href="#all_fs_fslinksyncexistingpath-newpath"><code>fs.linkSync(existingPath, newPath)</code></a></li>
<li><a href="#all_fs_fslstatsyncpath-options"><code>fs.lstatSync(path[, options])</code></a></li>
<li><a href="#all_fs_fsmkdirsyncpath-options"><code>fs.mkdirSync(path[, options])</code></a></li>
<li><a href="#all_fs_fsmkdtempsyncprefix-options"><code>fs.mkdtempSync(prefix[, options])</code></a></li>
<li><a href="#all_fs_fsopendirsyncpath-options"><code>fs.opendirSync(path[, options])</code></a></li>
<li><a href="#all_fs_fsopensyncpath-flags-mode"><code>fs.openSync(path[, flags[, mode]])</code></a></li>
<li><a href="#all_fs_fsreaddirsyncpath-options"><code>fs.readdirSync(path[, options])</code></a></li>
<li><a href="#all_fs_fsreadfilesyncpath-options"><code>fs.readFileSync(path[, options])</code></a></li>
<li><a href="#all_fs_fsreadlinksyncpath-options"><code>fs.readlinkSync(path[, options])</code></a></li>
<li><a href="#all_fs_fsreadsyncfd-buffer-offset-length-position"><code>fs.readSync(fd, buffer, offset, length[, position])</code></a></li>
<li><a href="#all_fs_fsreadsyncfd-buffer-options"><code>fs.readSync(fd, buffer[, options])</code></a></li>
<li><a href="#all_fs_fsreadvsyncfd-buffers-position"><code>fs.readvSync(fd, buffers[, position])</code></a></li>
<li><a href="#all_fs_fsrealpathsyncpath-options"><code>fs.realpathSync(path[, options])</code></a></li>
<li><a href="#all_fs_fsrealpathsyncnativepath-options"><code>fs.realpathSync.native(path[, options])</code></a></li>
<li><a href="#all_fs_fsrenamesyncoldpath-newpath"><code>fs.renameSync(oldPath, newPath)</code></a></li>
<li><a href="#all_fs_fsrmdirsyncpath-options"><code>fs.rmdirSync(path[, options])</code></a></li>
<li><a href="#all_fs_fsrmsyncpath-options"><code>fs.rmSync(path[, options])</code></a></li>
<li><a href="#all_fs_fsstatsyncpath-options"><code>fs.statSync(path[, options])</code></a></li>
<li><a href="#all_fs_fsstatfssyncpath-options"><code>fs.statfsSync(path[, options])</code></a></li>
<li><a href="#all_fs_fssymlinksynctarget-path-type"><code>fs.symlinkSync(target, path[, type])</code></a></li>
<li><a href="#all_fs_fstruncatesyncpath-len"><code>fs.truncateSync(path[, len])</code></a></li>
<li><a href="#all_fs_fsunlinksyncpath"><code>fs.unlinkSync(path)</code></a></li>
<li><a href="#all_fs_fsutimessyncpath-atime-mtime"><code>fs.utimesSync(path, atime, mtime)</code></a></li>
<li><a href="#all_fs_fswritefilesyncfile-data-options"><code>fs.writeFileSync(file, data[, options])</code></a></li>
<li><a href="#all_fs_fswritesyncfd-buffer-offset-length-position"><code>fs.writeSync(fd, buffer, offset[, length[, position]])</code></a></li>
<li><a href="#all_fs_fswritesyncfd-buffer-options"><code>fs.writeSync(fd, buffer[, options])</code></a></li>
<li><a href="#all_fs_fswritesyncfd-string-position-encoding"><code>fs.writeSync(fd, string[, position[, encoding]])</code></a></li>
<li><a href="#all_fs_fswritevsyncfd-buffers-position"><code>fs.writevSync(fd, buffers[, position])</code></a></li>
</ul>
</li>
<li><a href="#all_fs_common-objects">Common Objects</a>
<ul>
<li><a href="#all_fs_class-fsdir">Class: <code>fs.Dir</code></a>
<ul>
<li><a href="#all_fs_dirclose"><code>dir.close()</code></a></li>
<li><a href="#all_fs_dirclosecallback"><code>dir.close(callback)</code></a></li>
<li><a href="#all_fs_dirclosesync"><code>dir.closeSync()</code></a></li>
<li><a href="#all_fs_dirpath"><code>dir.path</code></a></li>
<li><a href="#all_fs_dirread"><code>dir.read()</code></a></li>
<li><a href="#all_fs_dirreadcallback"><code>dir.read(callback)</code></a></li>
<li><a href="#all_fs_dirreadsync"><code>dir.readSync()</code></a></li>
<li><a href="#all_fs_dirsymbolasynciterator"><code>dir[Symbol.asyncIterator]()</code></a></li>
</ul>
</li>
<li><a href="#all_fs_class-fsdirent">Class: <code>fs.Dirent</code></a>
<ul>
<li><a href="#all_fs_direntisblockdevice"><code>dirent.isBlockDevice()</code></a></li>
<li><a href="#all_fs_direntischaracterdevice"><code>dirent.isCharacterDevice()</code></a></li>
<li><a href="#all_fs_direntisdirectory"><code>dirent.isDirectory()</code></a></li>
<li><a href="#all_fs_direntisfifo"><code>dirent.isFIFO()</code></a></li>
<li><a href="#all_fs_direntisfile"><code>dirent.isFile()</code></a></li>
<li><a href="#all_fs_direntissocket"><code>dirent.isSocket()</code></a></li>
<li><a href="#all_fs_direntissymboliclink"><code>dirent.isSymbolicLink()</code></a></li>
<li><a href="#all_fs_direntname"><code>dirent.name</code></a></li>
<li><span class="stability_1"><a href="#all_fs_direntparentpath"><code>dirent.parentPath</code></a></span></li>
<li><span class="stability_0"><a href="#all_fs_direntpath"><code>dirent.path</code></a></span></li>
</ul>
</li>
<li><a href="#all_fs_class-fsfswatcher">Class: <code>fs.FSWatcher</code></a>
<ul>
<li><a href="#all_fs_event-change">Event: <code>'change'</code></a></li>
<li><a href="#all_fs_event-close_1">Event: <code>'close'</code></a></li>
<li><a href="#all_fs_event-error">Event: <code>'error'</code></a></li>
<li><a href="#all_fs_watcherclose"><code>watcher.close()</code></a></li>
<li><a href="#all_fs_watcherref"><code>watcher.ref()</code></a></li>
<li><a href="#all_fs_watcherunref"><code>watcher.unref()</code></a></li>
</ul>
</li>
<li><a href="#all_fs_class-fsstatwatcher">Class: <code>fs.StatWatcher</code></a>
<ul>
<li><a href="#all_fs_watcherref_1"><code>watcher.ref()</code></a></li>
<li><a href="#all_fs_watcherunref_1"><code>watcher.unref()</code></a></li>
</ul>
</li>
<li><a href="#all_fs_class-fsreadstream">Class: <code>fs.ReadStream</code></a>
<ul>
<li><a href="#all_fs_event-close_2">Event: <code>'close'</code></a></li>
<li><a href="#all_fs_event-open">Event: <code>'open'</code></a></li>
<li><a href="#all_fs_event-ready">Event: <code>'ready'</code></a></li>
<li><a href="#all_fs_readstreambytesread"><code>readStream.bytesRead</code></a></li>
<li><a href="#all_fs_readstreampath"><code>readStream.path</code></a></li>
<li><a href="#all_fs_readstreampending"><code>readStream.pending</code></a></li>
</ul>
</li>
<li><a href="#all_fs_class-fsstats">Class: <code>fs.Stats</code></a>
<ul>
<li><a href="#all_fs_statsisblockdevice"><code>stats.isBlockDevice()</code></a></li>
<li><a href="#all_fs_statsischaracterdevice"><code>stats.isCharacterDevice()</code></a></li>
<li><a href="#all_fs_statsisdirectory"><code>stats.isDirectory()</code></a></li>
<li><a href="#all_fs_statsisfifo"><code>stats.isFIFO()</code></a></li>
<li><a href="#all_fs_statsisfile"><code>stats.isFile()</code></a></li>
<li><a href="#all_fs_statsissocket"><code>stats.isSocket()</code></a></li>
<li><a href="#all_fs_statsissymboliclink"><code>stats.isSymbolicLink()</code></a></li>
<li><a href="#all_fs_statsdev"><code>stats.dev</code></a></li>
<li><a href="#all_fs_statsino"><code>stats.ino</code></a></li>
<li><a href="#all_fs_statsmode"><code>stats.mode</code></a></li>
<li><a href="#all_fs_statsnlink"><code>stats.nlink</code></a></li>
<li><a href="#all_fs_statsuid"><code>stats.uid</code></a></li>
<li><a href="#all_fs_statsgid"><code>stats.gid</code></a></li>
<li><a href="#all_fs_statsrdev"><code>stats.rdev</code></a></li>
<li><a href="#all_fs_statssize"><code>stats.size</code></a></li>
<li><a href="#all_fs_statsblksize"><code>stats.blksize</code></a></li>
<li><a href="#all_fs_statsblocks"><code>stats.blocks</code></a></li>
<li><a href="#all_fs_statsatimems"><code>stats.atimeMs</code></a></li>
<li><a href="#all_fs_statsmtimems"><code>stats.mtimeMs</code></a></li>
<li><a href="#all_fs_statsctimems"><code>stats.ctimeMs</code></a></li>
<li><a href="#all_fs_statsbirthtimems"><code>stats.birthtimeMs</code></a></li>
<li><a href="#all_fs_statsatimens"><code>stats.atimeNs</code></a></li>
<li><a href="#all_fs_statsmtimens"><code>stats.mtimeNs</code></a></li>
<li><a href="#all_fs_statsctimens"><code>stats.ctimeNs</code></a></li>
<li><a href="#all_fs_statsbirthtimens"><code>stats.birthtimeNs</code></a></li>
<li><a href="#all_fs_statsatime"><code>stats.atime</code></a></li>
<li><a href="#all_fs_statsmtime"><code>stats.mtime</code></a></li>
<li><a href="#all_fs_statsctime"><code>stats.ctime</code></a></li>
<li><a href="#all_fs_statsbirthtime"><code>stats.birthtime</code></a></li>
<li><a href="#all_fs_stat-time-values">Stat time values</a></li>
</ul>
</li>
<li><a href="#all_fs_class-fsstatfs">Class: <code>fs.StatFs</code></a>
<ul>
<li><a href="#all_fs_statfsbavail"><code>statfs.bavail</code></a></li>
<li><a href="#all_fs_statfsbfree"><code>statfs.bfree</code></a></li>
<li><a href="#all_fs_statfsblocks"><code>statfs.blocks</code></a></li>
<li><a href="#all_fs_statfsbsize"><code>statfs.bsize</code></a></li>
<li><a href="#all_fs_statfsffree"><code>statfs.ffree</code></a></li>
<li><a href="#all_fs_statfsfiles"><code>statfs.files</code></a></li>
<li><a href="#all_fs_statfstype"><code>statfs.type</code></a></li>
</ul>
</li>
<li><a href="#all_fs_class-fswritestream">Class: <code>fs.WriteStream</code></a>
<ul>
<li><a href="#all_fs_event-close_3">Event: <code>'close'</code></a></li>
<li><a href="#all_fs_event-open_1">Event: <code>'open'</code></a></li>
<li><a href="#all_fs_event-ready_1">Event: <code>'ready'</code></a></li>
<li><a href="#all_fs_writestreambyteswritten"><code>writeStream.bytesWritten</code></a></li>
<li><a href="#all_fs_writestreamclosecallback"><code>writeStream.close([callback])</code></a></li>
<li><a href="#all_fs_writestreampath"><code>writeStream.path</code></a></li>
<li><a href="#all_fs_writestreampending"><code>writeStream.pending</code></a></li>
</ul>
</li>
<li><a href="#all_fs_fsconstants"><code>fs.constants</code></a>
<ul>
<li><a href="#all_fs_fs-constants">FS constants</a>
<ul>
<li><a href="#all_fs_file-access-constants">File access constants</a></li>
<li><a href="#all_fs_file-copy-constants">File copy constants</a></li>
<li><a href="#all_fs_file-open-constants">File open constants</a></li>
<li><a href="#all_fs_file-type-constants">File type constants</a></li>
<li><a href="#all_fs_file-mode-constants">File mode constants</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_fs_notes">Notes</a>
<ul>
<li><a href="#all_fs_ordering-of-callback-and-promise-based-operations">Ordering of callback and promise-based operations</a></li>
<li><a href="#all_fs_file-paths">File paths</a>
<ul>
<li><a href="#all_fs_string-paths">String paths</a></li>
<li><a href="#all_fs_file-url-paths">File URL paths</a>
<ul>
<li><a href="#all_fs_platform-specific-considerations">Platform-specific considerations</a></li>
</ul>
</li>
<li><a href="#all_fs_buffer-paths">Buffer paths</a></li>
<li><a href="#all_fs_per-drive-working-directories-on-windows">Per-drive working directories on Windows</a></li>
</ul>
</li>
<li><a href="#all_fs_file-descriptors_1">File descriptors</a></li>
<li><a href="#all_fs_threadpool-usage">Threadpool usage</a></li>
<li><a href="#all_fs_file-system-flags">File system flags</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_globals_global-objects">Global objects</a>
<ul>
<li><a href="#all_globals_class-abortcontroller">Class: <code>AbortController</code></a>
<ul>
<li><a href="#all_globals_abortcontrollerabortreason"><code>abortController.abort([reason])</code></a></li>
<li><a href="#all_globals_abortcontrollersignal"><code>abortController.signal</code></a></li>
<li><a href="#all_globals_class-abortsignal">Class: <code>AbortSignal</code></a>
<ul>
<li><a href="#all_globals_static-method-abortsignalabortreason">Static method: <code>AbortSignal.abort([reason])</code></a></li>
<li><a href="#all_globals_static-method-abortsignaltimeoutdelay">Static method: <code>AbortSignal.timeout(delay)</code></a></li>
<li><a href="#all_globals_static-method-abortsignalanysignals">Static method: <code>AbortSignal.any(signals)</code></a></li>
<li><a href="#all_globals_event-abort">Event: <code>'abort'</code></a></li>
<li><a href="#all_globals_abortsignalaborted"><code>abortSignal.aborted</code></a></li>
<li><a href="#all_globals_abortsignalonabort"><code>abortSignal.onabort</code></a></li>
<li><a href="#all_globals_abortsignalreason"><code>abortSignal.reason</code></a></li>
<li><a href="#all_globals_abortsignalthrowifaborted"><code>abortSignal.throwIfAborted()</code></a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_globals_class-blob">Class: <code>Blob</code></a></li>
<li><a href="#all_globals_class-buffer">Class: <code>Buffer</code></a></li>
<li><span class="stability_1"><a href="#all_globals_class-bytelengthqueuingstrategy">Class: <code>ByteLengthQueuingStrategy</code></a></span></li>
<li><a href="#all_globals___dirname"><code>__dirname</code></a></li>
<li><a href="#all_globals___filename"><code>__filename</code></a></li>
<li><span class="stability_3"><a href="#all_globals_atobdata"><code>atob(data)</code></a></span></li>
<li><a href="#all_globals_broadcastchannel"><code>BroadcastChannel</code></a></li>
<li><span class="stability_3"><a href="#all_globals_btoadata"><code>btoa(data)</code></a></span></li>
<li><a href="#all_globals_clearimmediateimmediateobject"><code>clearImmediate(immediateObject)</code></a></li>
<li><a href="#all_globals_clearintervalintervalobject"><code>clearInterval(intervalObject)</code></a></li>
<li><a href="#all_globals_cleartimeouttimeoutobject"><code>clearTimeout(timeoutObject)</code></a></li>
<li><span class="stability_1"><a href="#all_globals_class-compressionstream">Class: <code>CompressionStream</code></a></span></li>
<li><a href="#all_globals_console"><code>console</code></a></li>
<li><span class="stability_1"><a href="#all_globals_class-countqueuingstrategy">Class: <code>CountQueuingStrategy</code></a></span></li>
<li><span class="stability_1"><a href="#all_globals_crypto"><code>Crypto</code></a></span></li>
<li><span class="stability_1"><a href="#all_globals_crypto_1"><code>crypto</code></a></span></li>
<li><span class="stability_1"><a href="#all_globals_cryptokey"><code>CryptoKey</code></a></span></li>
<li><span class="stability_1"><a href="#all_globals_customevent"><code>CustomEvent</code></a></span></li>
<li><span class="stability_1"><a href="#all_globals_class-decompressionstream">Class: <code>DecompressionStream</code></a></span></li>
<li><a href="#all_globals_event"><code>Event</code></a></li>
<li><span class="stability_1"><a href="#all_globals_eventsource"><code>EventSource</code></a></span></li>
<li><a href="#all_globals_eventtarget"><code>EventTarget</code></a></li>
<li><a href="#all_globals_exports"><code>exports</code></a></li>
<li><span class="stability_1"><a href="#all_globals_fetch"><code>fetch</code></a></span></li>
<li><a href="#all_globals_class-file">Class: <code>File</code></a></li>
<li><span class="stability_1"><a href="#all_globals_class-formdata">Class <code>FormData</code></a></span></li>
<li><span class="stability_3"><a href="#all_globals_global"><code>global</code></a></span></li>
<li><span class="stability_1"><a href="#all_globals_class-headers">Class <code>Headers</code></a></span></li>
<li><a href="#all_globals_messagechannel"><code>MessageChannel</code></a></li>
<li><a href="#all_globals_messageevent"><code>MessageEvent</code></a></li>
<li><a href="#all_globals_messageport"><code>MessagePort</code></a></li>
<li><a href="#all_globals_module"><code>module</code></a></li>
<li><a href="#all_globals_performanceentry"><code>PerformanceEntry</code></a></li>
<li><a href="#all_globals_performancemark"><code>PerformanceMark</code></a></li>
<li><a href="#all_globals_performancemeasure"><code>PerformanceMeasure</code></a></li>
<li><a href="#all_globals_performanceobserver"><code>PerformanceObserver</code></a></li>
<li><a href="#all_globals_performanceobserverentrylist"><code>PerformanceObserverEntryList</code></a></li>
<li><a href="#all_globals_performanceresourcetiming"><code>PerformanceResourceTiming</code></a></li>
<li><a href="#all_globals_performance"><code>performance</code></a></li>
<li><a href="#all_globals_process"><code>process</code></a></li>
<li><a href="#all_globals_queuemicrotaskcallback"><code>queueMicrotask(callback)</code></a></li>
<li><span class="stability_1"><a href="#all_globals_class-readablebytestreamcontroller">Class: <code>ReadableByteStreamController</code></a></span></li>
<li><span class="stability_1"><a href="#all_globals_class-readablestream">Class: <code>ReadableStream</code></a></span></li>
<li><span class="stability_1"><a href="#all_globals_class-readablestreambyobreader">Class: <code>ReadableStreamBYOBReader</code></a></span></li>
<li><span class="stability_1"><a href="#all_globals_class-readablestreambyobrequest">Class: <code>ReadableStreamBYOBRequest</code></a></span></li>
<li><span class="stability_1"><a href="#all_globals_class-readablestreamdefaultcontroller">Class: <code>ReadableStreamDefaultController</code></a></span></li>
<li><span class="stability_1"><a href="#all_globals_class-readablestreamdefaultreader">Class: <code>ReadableStreamDefaultReader</code></a></span></li>
<li><a href="#all_globals_require"><code>require()</code></a></li>
<li><span class="stability_1"><a href="#all_globals_response"><code>Response</code></a></span></li>
<li><span class="stability_1"><a href="#all_globals_request"><code>Request</code></a></span></li>
<li><a href="#all_globals_setimmediatecallback-args"><code>setImmediate(callback[, ...args])</code></a></li>
<li><a href="#all_globals_setintervalcallback-delay-args"><code>setInterval(callback, delay[, ...args])</code></a></li>
<li><a href="#all_globals_settimeoutcallback-delay-args"><code>setTimeout(callback, delay[, ...args])</code></a></li>
<li><a href="#all_globals_structuredclonevalue-options"><code>structuredClone(value[, options])</code></a></li>
<li><span class="stability_1"><a href="#all_globals_subtlecrypto"><code>SubtleCrypto</code></a></span></li>
<li><a href="#all_globals_domexception"><code>DOMException</code></a></li>
<li><a href="#all_globals_textdecoder"><code>TextDecoder</code></a></li>
<li><span class="stability_1"><a href="#all_globals_class-textdecoderstream">Class: <code>TextDecoderStream</code></a></span></li>
<li><a href="#all_globals_textencoder"><code>TextEncoder</code></a></li>
<li><span class="stability_1"><a href="#all_globals_class-textencoderstream">Class: <code>TextEncoderStream</code></a></span></li>
<li><span class="stability_1"><a href="#all_globals_class-transformstream">Class: <code>TransformStream</code></a></span></li>
<li><span class="stability_1"><a href="#all_globals_class-transformstreamdefaultcontroller">Class: <code>TransformStreamDefaultController</code></a></span></li>
<li><a href="#all_globals_url"><code>URL</code></a></li>
<li><a href="#all_globals_urlsearchparams"><code>URLSearchParams</code></a></li>
<li><a href="#all_globals_webassembly"><code>WebAssembly</code></a></li>
<li><span class="stability_1"><a href="#all_globals_websocket"><code>WebSocket</code></a></span></li>
<li><span class="stability_1"><a href="#all_globals_class-writablestream">Class: <code>WritableStream</code></a></span></li>
<li><span class="stability_1"><a href="#all_globals_class-writablestreamdefaultcontroller">Class: <code>WritableStreamDefaultController</code></a></span></li>
<li><span class="stability_1"><a href="#all_globals_class-writablestreamdefaultwriter">Class: <code>WritableStreamDefaultWriter</code></a></span></li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_http_http">HTTP</a></span>
<ul>
<li><a href="#all_http_class-httpagent">Class: <code>http.Agent</code></a>
<ul>
<li><a href="#all_http_new-agentoptions"><code>new Agent([options])</code></a></li>
<li><a href="#all_http_agentcreateconnectionoptions-callback"><code>agent.createConnection(options[, callback])</code></a></li>
<li><a href="#all_http_agentkeepsocketalivesocket"><code>agent.keepSocketAlive(socket)</code></a></li>
<li><a href="#all_http_agentreusesocketsocket-request"><code>agent.reuseSocket(socket, request)</code></a></li>
<li><a href="#all_http_agentdestroy"><code>agent.destroy()</code></a></li>
<li><a href="#all_http_agentfreesockets"><code>agent.freeSockets</code></a></li>
<li><a href="#all_http_agentgetnameoptions"><code>agent.getName([options])</code></a></li>
<li><a href="#all_http_agentmaxfreesockets"><code>agent.maxFreeSockets</code></a></li>
<li><a href="#all_http_agentmaxsockets"><code>agent.maxSockets</code></a></li>
<li><a href="#all_http_agentmaxtotalsockets"><code>agent.maxTotalSockets</code></a></li>
<li><a href="#all_http_agentrequests"><code>agent.requests</code></a></li>
<li><a href="#all_http_agentsockets"><code>agent.sockets</code></a></li>
</ul>
</li>
<li><a href="#all_http_class-httpclientrequest">Class: <code>http.ClientRequest</code></a>
<ul>
<li><span class="stability_0"><a href="#all_http_event-abort">Event: <code>'abort'</code></a></span></li>
<li><a href="#all_http_event-close">Event: <code>'close'</code></a></li>
<li><a href="#all_http_event-connect">Event: <code>'connect'</code></a></li>
<li><a href="#all_http_event-continue">Event: <code>'continue'</code></a></li>
<li><a href="#all_http_event-finish">Event: <code>'finish'</code></a></li>
<li><a href="#all_http_event-information">Event: <code>'information'</code></a></li>
<li><a href="#all_http_event-response">Event: <code>'response'</code></a></li>
<li><a href="#all_http_event-socket">Event: <code>'socket'</code></a></li>
<li><a href="#all_http_event-timeout">Event: <code>'timeout'</code></a></li>
<li><a href="#all_http_event-upgrade">Event: <code>'upgrade'</code></a></li>
<li><span class="stability_0"><a href="#all_http_requestabort"><code>request.abort()</code></a></span></li>
<li><span class="stability_0"><a href="#all_http_requestaborted"><code>request.aborted</code></a></span></li>
<li><span class="stability_0"><a href="#all_http_requestconnection"><code>request.connection</code></a></span></li>
<li><a href="#all_http_requestcork"><code>request.cork()</code></a></li>
<li><a href="#all_http_requestenddata-encoding-callback"><code>request.end([data[, encoding]][, callback])</code></a></li>
<li><a href="#all_http_requestdestroyerror"><code>request.destroy([error])</code></a>
<ul>
<li><a href="#all_http_requestdestroyed"><code>request.destroyed</code></a></li>
</ul>
</li>
<li><span class="stability_0"><a href="#all_http_requestfinished"><code>request.finished</code></a></span></li>
<li><a href="#all_http_requestflushheaders"><code>request.flushHeaders()</code></a></li>
<li><a href="#all_http_requestgetheadername"><code>request.getHeader(name)</code></a></li>
<li><a href="#all_http_requestgetheadernames"><code>request.getHeaderNames()</code></a></li>
<li><a href="#all_http_requestgetheaders"><code>request.getHeaders()</code></a></li>
<li><a href="#all_http_requestgetrawheadernames"><code>request.getRawHeaderNames()</code></a></li>
<li><a href="#all_http_requesthasheadername"><code>request.hasHeader(name)</code></a></li>
<li><a href="#all_http_requestmaxheaderscount"><code>request.maxHeadersCount</code></a></li>
<li><a href="#all_http_requestpath"><code>request.path</code></a></li>
<li><a href="#all_http_requestmethod"><code>request.method</code></a></li>
<li><a href="#all_http_requesthost"><code>request.host</code></a></li>
<li><a href="#all_http_requestprotocol"><code>request.protocol</code></a></li>
<li><a href="#all_http_requestremoveheadername"><code>request.removeHeader(name)</code></a></li>
<li><a href="#all_http_requestreusedsocket"><code>request.reusedSocket</code></a></li>
<li><a href="#all_http_requestsetheadername-value"><code>request.setHeader(name, value)</code></a></li>
<li><a href="#all_http_requestsetnodelaynodelay"><code>request.setNoDelay([noDelay])</code></a></li>
<li><a href="#all_http_requestsetsocketkeepaliveenable-initialdelay"><code>request.setSocketKeepAlive([enable][, initialDelay])</code></a></li>
<li><a href="#all_http_requestsettimeouttimeout-callback"><code>request.setTimeout(timeout[, callback])</code></a></li>
<li><a href="#all_http_requestsocket"><code>request.socket</code></a></li>
<li><a href="#all_http_requestuncork"><code>request.uncork()</code></a></li>
<li><a href="#all_http_requestwritableended"><code>request.writableEnded</code></a></li>
<li><a href="#all_http_requestwritablefinished"><code>request.writableFinished</code></a></li>
<li><a href="#all_http_requestwritechunk-encoding-callback"><code>request.write(chunk[, encoding][, callback])</code></a></li>
</ul>
</li>
<li><a href="#all_http_class-httpserver">Class: <code>http.Server</code></a>
<ul>
<li><a href="#all_http_event-checkcontinue">Event: <code>'checkContinue'</code></a></li>
<li><a href="#all_http_event-checkexpectation">Event: <code>'checkExpectation'</code></a></li>
<li><a href="#all_http_event-clienterror">Event: <code>'clientError'</code></a></li>
<li><a href="#all_http_event-close_1">Event: <code>'close'</code></a></li>
<li><a href="#all_http_event-connect_1">Event: <code>'connect'</code></a></li>
<li><a href="#all_http_event-connection">Event: <code>'connection'</code></a></li>
<li><a href="#all_http_event-droprequest">Event: <code>'dropRequest'</code></a></li>
<li><a href="#all_http_event-request">Event: <code>'request'</code></a></li>
<li><a href="#all_http_event-upgrade_1">Event: <code>'upgrade'</code></a></li>
<li><a href="#all_http_serverclosecallback"><code>server.close([callback])</code></a></li>
<li><a href="#all_http_servercloseallconnections"><code>server.closeAllConnections()</code></a></li>
<li><a href="#all_http_servercloseidleconnections"><code>server.closeIdleConnections()</code></a></li>
<li><a href="#all_http_serverheaderstimeout"><code>server.headersTimeout</code></a></li>
<li><a href="#all_http_serverlisten"><code>server.listen()</code></a></li>
<li><a href="#all_http_serverlistening"><code>server.listening</code></a></li>
<li><a href="#all_http_servermaxheaderscount"><code>server.maxHeadersCount</code></a></li>
<li><a href="#all_http_serverrequesttimeout"><code>server.requestTimeout</code></a></li>
<li><a href="#all_http_serversettimeoutmsecs-callback"><code>server.setTimeout([msecs][, callback])</code></a></li>
<li><a href="#all_http_servermaxrequestspersocket"><code>server.maxRequestsPerSocket</code></a></li>
<li><a href="#all_http_servertimeout"><code>server.timeout</code></a></li>
<li><a href="#all_http_serverkeepalivetimeout"><code>server.keepAliveTimeout</code></a></li>
<li><span class="stability_1"><a href="#all_http_serversymbolasyncdispose"><code>server[Symbol.asyncDispose]()</code></a></span></li>
</ul>
</li>
<li><a href="#all_http_class-httpserverresponse">Class: <code>http.ServerResponse</code></a>
<ul>
<li><a href="#all_http_event-close_2">Event: <code>'close'</code></a></li>
<li><a href="#all_http_event-finish_1">Event: <code>'finish'</code></a></li>
<li><a href="#all_http_responseaddtrailersheaders"><code>response.addTrailers(headers)</code></a></li>
<li><span class="stability_0"><a href="#all_http_responseconnection"><code>response.connection</code></a></span></li>
<li><a href="#all_http_responsecork"><code>response.cork()</code></a></li>
<li><a href="#all_http_responseenddata-encoding-callback"><code>response.end([data[, encoding]][, callback])</code></a></li>
<li><span class="stability_0"><a href="#all_http_responsefinished"><code>response.finished</code></a></span></li>
<li><a href="#all_http_responseflushheaders"><code>response.flushHeaders()</code></a></li>
<li><a href="#all_http_responsegetheadername"><code>response.getHeader(name)</code></a></li>
<li><a href="#all_http_responsegetheadernames"><code>response.getHeaderNames()</code></a></li>
<li><a href="#all_http_responsegetheaders"><code>response.getHeaders()</code></a></li>
<li><a href="#all_http_responsehasheadername"><code>response.hasHeader(name)</code></a></li>
<li><a href="#all_http_responseheaderssent"><code>response.headersSent</code></a></li>
<li><a href="#all_http_responseremoveheadername"><code>response.removeHeader(name)</code></a></li>
<li><a href="#all_http_responsereq"><code>response.req</code></a></li>
<li><a href="#all_http_responsesenddate"><code>response.sendDate</code></a></li>
<li><a href="#all_http_responsesetheadername-value"><code>response.setHeader(name, value)</code></a></li>
<li><a href="#all_http_responsesettimeoutmsecs-callback"><code>response.setTimeout(msecs[, callback])</code></a></li>
<li><a href="#all_http_responsesocket"><code>response.socket</code></a></li>
<li><a href="#all_http_responsestatuscode"><code>response.statusCode</code></a></li>
<li><a href="#all_http_responsestatusmessage"><code>response.statusMessage</code></a></li>
<li><a href="#all_http_responsestrictcontentlength"><code>response.strictContentLength</code></a></li>
<li><a href="#all_http_responseuncork"><code>response.uncork()</code></a></li>
<li><a href="#all_http_responsewritableended"><code>response.writableEnded</code></a></li>
<li><a href="#all_http_responsewritablefinished"><code>response.writableFinished</code></a></li>
<li><a href="#all_http_responsewritechunk-encoding-callback"><code>response.write(chunk[, encoding][, callback])</code></a></li>
<li><a href="#all_http_responsewritecontinue"><code>response.writeContinue()</code></a></li>
<li><a href="#all_http_responsewriteearlyhintshints-callback"><code>response.writeEarlyHints(hints[, callback])</code></a></li>
<li><a href="#all_http_responsewriteheadstatuscode-statusmessage-headers"><code>response.writeHead(statusCode[, statusMessage][, headers])</code></a></li>
<li><a href="#all_http_responsewriteprocessing"><code>response.writeProcessing()</code></a></li>
</ul>
</li>
<li><a href="#all_http_class-httpincomingmessage">Class: <code>http.IncomingMessage</code></a>
<ul>
<li><span class="stability_0"><a href="#all_http_event-aborted">Event: <code>'aborted'</code></a></span></li>
<li><a href="#all_http_event-close_3">Event: <code>'close'</code></a></li>
<li><span class="stability_0"><a href="#all_http_messageaborted"><code>message.aborted</code></a></span></li>
<li><a href="#all_http_messagecomplete"><code>message.complete</code></a></li>
<li><span class="stability_0"><a href="#all_http_messageconnection"><code>message.connection</code></a></span></li>
<li><a href="#all_http_messagedestroyerror"><code>message.destroy([error])</code></a></li>
<li><a href="#all_http_messageheaders"><code>message.headers</code></a></li>
<li><a href="#all_http_messageheadersdistinct"><code>message.headersDistinct</code></a></li>
<li><a href="#all_http_messagehttpversion"><code>message.httpVersion</code></a></li>
<li><a href="#all_http_messagemethod"><code>message.method</code></a></li>
<li><a href="#all_http_messagerawheaders"><code>message.rawHeaders</code></a></li>
<li><a href="#all_http_messagerawtrailers"><code>message.rawTrailers</code></a></li>
<li><a href="#all_http_messagesettimeoutmsecs-callback"><code>message.setTimeout(msecs[, callback])</code></a></li>
<li><a href="#all_http_messagesocket"><code>message.socket</code></a></li>
<li><a href="#all_http_messagestatuscode"><code>message.statusCode</code></a></li>
<li><a href="#all_http_messagestatusmessage"><code>message.statusMessage</code></a></li>
<li><a href="#all_http_messagetrailers"><code>message.trailers</code></a></li>
<li><a href="#all_http_messagetrailersdistinct"><code>message.trailersDistinct</code></a></li>
<li><a href="#all_http_messageurl"><code>message.url</code></a></li>
</ul>
</li>
<li><a href="#all_http_class-httpoutgoingmessage">Class: <code>http.OutgoingMessage</code></a>
<ul>
<li><a href="#all_http_event-drain">Event: <code>'drain'</code></a></li>
<li><a href="#all_http_event-finish_2">Event: <code>'finish'</code></a></li>
<li><a href="#all_http_event-prefinish">Event: <code>'prefinish'</code></a></li>
<li><a href="#all_http_outgoingmessageaddtrailersheaders"><code>outgoingMessage.addTrailers(headers)</code></a></li>
<li><a href="#all_http_outgoingmessageappendheadername-value"><code>outgoingMessage.appendHeader(name, value)</code></a></li>
<li><span class="stability_0"><a href="#all_http_outgoingmessageconnection"><code>outgoingMessage.connection</code></a></span></li>
<li><a href="#all_http_outgoingmessagecork"><code>outgoingMessage.cork()</code></a></li>
<li><a href="#all_http_outgoingmessagedestroyerror"><code>outgoingMessage.destroy([error])</code></a></li>
<li><a href="#all_http_outgoingmessageendchunk-encoding-callback"><code>outgoingMessage.end(chunk[, encoding][, callback])</code></a></li>
<li><a href="#all_http_outgoingmessageflushheaders"><code>outgoingMessage.flushHeaders()</code></a></li>
<li><a href="#all_http_outgoingmessagegetheadername"><code>outgoingMessage.getHeader(name)</code></a></li>
<li><a href="#all_http_outgoingmessagegetheadernames"><code>outgoingMessage.getHeaderNames()</code></a></li>
<li><a href="#all_http_outgoingmessagegetheaders"><code>outgoingMessage.getHeaders()</code></a></li>
<li><a href="#all_http_outgoingmessagehasheadername"><code>outgoingMessage.hasHeader(name)</code></a></li>
<li><a href="#all_http_outgoingmessageheaderssent"><code>outgoingMessage.headersSent</code></a></li>
<li><a href="#all_http_outgoingmessagepipe"><code>outgoingMessage.pipe()</code></a></li>
<li><a href="#all_http_outgoingmessageremoveheadername"><code>outgoingMessage.removeHeader(name)</code></a></li>
<li><a href="#all_http_outgoingmessagesetheadername-value"><code>outgoingMessage.setHeader(name, value)</code></a></li>
<li><a href="#all_http_outgoingmessagesetheadersheaders"><code>outgoingMessage.setHeaders(headers)</code></a></li>
<li><a href="#all_http_outgoingmessagesettimeoutmsesc-callback"><code>outgoingMessage.setTimeout(msesc[, callback])</code></a></li>
<li><a href="#all_http_outgoingmessagesocket"><code>outgoingMessage.socket</code></a></li>
<li><a href="#all_http_outgoingmessageuncork"><code>outgoingMessage.uncork()</code></a></li>
<li><a href="#all_http_outgoingmessagewritablecorked"><code>outgoingMessage.writableCorked</code></a></li>
<li><a href="#all_http_outgoingmessagewritableended"><code>outgoingMessage.writableEnded</code></a></li>
<li><a href="#all_http_outgoingmessagewritablefinished"><code>outgoingMessage.writableFinished</code></a></li>
<li><a href="#all_http_outgoingmessagewritablehighwatermark"><code>outgoingMessage.writableHighWaterMark</code></a></li>
<li><a href="#all_http_outgoingmessagewritablelength"><code>outgoingMessage.writableLength</code></a></li>
<li><a href="#all_http_outgoingmessagewritableobjectmode"><code>outgoingMessage.writableObjectMode</code></a></li>
<li><a href="#all_http_outgoingmessagewritechunk-encoding-callback"><code>outgoingMessage.write(chunk[, encoding][, callback])</code></a></li>
</ul>
</li>
<li><a href="#all_http_httpmethods"><code>http.METHODS</code></a></li>
<li><a href="#all_http_httpstatus_codes"><code>http.STATUS_CODES</code></a></li>
<li><a href="#all_http_httpcreateserveroptions-requestlistener"><code>http.createServer([options][, requestListener])</code></a></li>
<li><a href="#all_http_httpgetoptions-callback"><code>http.get(options[, callback])</code></a></li>
<li><a href="#all_http_httpgeturl-options-callback"><code>http.get(url[, options][, callback])</code></a></li>
<li><a href="#all_http_httpglobalagent"><code>http.globalAgent</code></a></li>
<li><a href="#all_http_httpmaxheadersize"><code>http.maxHeaderSize</code></a></li>
<li><a href="#all_http_httprequestoptions-callback"><code>http.request(options[, callback])</code></a></li>
<li><a href="#all_http_httprequesturl-options-callback"><code>http.request(url[, options][, callback])</code></a></li>
<li><a href="#all_http_httpvalidateheadernamename-label"><code>http.validateHeaderName(name[, label])</code></a></li>
<li><a href="#all_http_httpvalidateheadervaluename-value"><code>http.validateHeaderValue(name, value)</code></a></li>
<li><a href="#all_http_httpsetmaxidlehttpparsersmax"><code>http.setMaxIdleHTTPParsers(max)</code></a></li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_http2_http2">HTTP/2</a></span>
<ul>
<li><a href="#all_http2_determining-if-crypto-support-is-unavailable">Determining if crypto support is unavailable</a></li>
<li><a href="#all_http2_core-api">Core API</a>
<ul>
<li><a href="#all_http2_server-side-example">Server-side example</a></li>
<li><a href="#all_http2_client-side-example">Client-side example</a></li>
<li><a href="#all_http2_class-http2session">Class: <code>Http2Session</code></a>
<ul>
<li><a href="#all_http2_http2session-and-sockets"><code>Http2Session</code> and sockets</a></li>
<li><a href="#all_http2_event-close">Event: <code>'close'</code></a></li>
<li><a href="#all_http2_event-connect">Event: <code>'connect'</code></a></li>
<li><a href="#all_http2_event-error">Event: <code>'error'</code></a></li>
<li><a href="#all_http2_event-frameerror">Event: <code>'frameError'</code></a></li>
<li><a href="#all_http2_event-goaway">Event: <code>'goaway'</code></a></li>
<li><a href="#all_http2_event-localsettings">Event: <code>'localSettings'</code></a></li>
<li><a href="#all_http2_event-ping">Event: <code>'ping'</code></a></li>
<li><a href="#all_http2_event-remotesettings">Event: <code>'remoteSettings'</code></a></li>
<li><a href="#all_http2_event-stream">Event: <code>'stream'</code></a></li>
<li><a href="#all_http2_event-timeout">Event: <code>'timeout'</code></a></li>
<li><a href="#all_http2_http2sessionalpnprotocol"><code>http2session.alpnProtocol</code></a></li>
<li><a href="#all_http2_http2sessionclosecallback"><code>http2session.close([callback])</code></a></li>
<li><a href="#all_http2_http2sessionclosed"><code>http2session.closed</code></a></li>
<li><a href="#all_http2_http2sessionconnecting"><code>http2session.connecting</code></a></li>
<li><a href="#all_http2_http2sessiondestroyerror-code"><code>http2session.destroy([error][, code])</code></a></li>
<li><a href="#all_http2_http2sessiondestroyed"><code>http2session.destroyed</code></a></li>
<li><a href="#all_http2_http2sessionencrypted"><code>http2session.encrypted</code></a></li>
<li><a href="#all_http2_http2sessiongoawaycode-laststreamid-opaquedata"><code>http2session.goaway([code[, lastStreamID[, opaqueData]]])</code></a></li>
<li><a href="#all_http2_http2sessionlocalsettings"><code>http2session.localSettings</code></a></li>
<li><a href="#all_http2_http2sessionoriginset"><code>http2session.originSet</code></a></li>
<li><a href="#all_http2_http2sessionpendingsettingsack"><code>http2session.pendingSettingsAck</code></a></li>
<li><a href="#all_http2_http2sessionpingpayload-callback"><code>http2session.ping([payload, ]callback)</code></a></li>
<li><a href="#all_http2_http2sessionref"><code>http2session.ref()</code></a></li>
<li><a href="#all_http2_http2sessionremotesettings"><code>http2session.remoteSettings</code></a></li>
<li><a href="#all_http2_http2sessionsetlocalwindowsizewindowsize"><code>http2session.setLocalWindowSize(windowSize)</code></a></li>
<li><a href="#all_http2_http2sessionsettimeoutmsecs-callback"><code>http2session.setTimeout(msecs, callback)</code></a></li>
<li><a href="#all_http2_http2sessionsocket"><code>http2session.socket</code></a></li>
<li><a href="#all_http2_http2sessionstate"><code>http2session.state</code></a></li>
<li><a href="#all_http2_http2sessionsettingssettings-callback"><code>http2session.settings([settings][, callback])</code></a></li>
<li><a href="#all_http2_http2sessiontype"><code>http2session.type</code></a></li>
<li><a href="#all_http2_http2sessionunref"><code>http2session.unref()</code></a></li>
</ul>
</li>
<li><a href="#all_http2_class-serverhttp2session">Class: <code>ServerHttp2Session</code></a>
<ul>
<li><a href="#all_http2_serverhttp2sessionaltsvcalt-originorstream"><code>serverhttp2session.altsvc(alt, originOrStream)</code></a></li>
<li><a href="#all_http2_specifying-alternative-services">Specifying alternative services</a></li>
<li><a href="#all_http2_serverhttp2sessionoriginorigins"><code>serverhttp2session.origin(...origins)</code></a></li>
</ul>
</li>
<li><a href="#all_http2_class-clienthttp2session">Class: <code>ClientHttp2Session</code></a>
<ul>
<li><a href="#all_http2_event-altsvc">Event: <code>'altsvc'</code></a></li>
<li><a href="#all_http2_event-origin">Event: <code>'origin'</code></a></li>
<li><a href="#all_http2_clienthttp2sessionrequestheaders-options"><code>clienthttp2session.request(headers[, options])</code></a></li>
</ul>
</li>
<li><a href="#all_http2_class-http2stream">Class: <code>Http2Stream</code></a>
<ul>
<li><a href="#all_http2_http2stream-lifecycle"><code>Http2Stream</code> Lifecycle</a>
<ul>
<li><a href="#all_http2_creation">Creation</a></li>
<li><a href="#all_http2_destruction">Destruction</a></li>
</ul>
</li>
<li><a href="#all_http2_event-aborted">Event: <code>'aborted'</code></a></li>
<li><a href="#all_http2_event-close_1">Event: <code>'close'</code></a></li>
<li><a href="#all_http2_event-error_1">Event: <code>'error'</code></a></li>
<li><a href="#all_http2_event-frameerror_1">Event: <code>'frameError'</code></a></li>
<li><a href="#all_http2_event-ready">Event: <code>'ready'</code></a></li>
<li><a href="#all_http2_event-timeout_1">Event: <code>'timeout'</code></a></li>
<li><a href="#all_http2_event-trailers">Event: <code>'trailers'</code></a></li>
<li><a href="#all_http2_event-wanttrailers">Event: <code>'wantTrailers'</code></a></li>
<li><a href="#all_http2_http2streamaborted"><code>http2stream.aborted</code></a></li>
<li><a href="#all_http2_http2streambuffersize"><code>http2stream.bufferSize</code></a></li>
<li><a href="#all_http2_http2streamclosecode-callback"><code>http2stream.close(code[, callback])</code></a></li>
<li><a href="#all_http2_http2streamclosed"><code>http2stream.closed</code></a></li>
<li><a href="#all_http2_http2streamdestroyed"><code>http2stream.destroyed</code></a></li>
<li><a href="#all_http2_http2streamendafterheaders"><code>http2stream.endAfterHeaders</code></a></li>
<li><a href="#all_http2_http2streamid"><code>http2stream.id</code></a></li>
<li><a href="#all_http2_http2streampending"><code>http2stream.pending</code></a></li>
<li><a href="#all_http2_http2streampriorityoptions"><code>http2stream.priority(options)</code></a></li>
<li><a href="#all_http2_http2streamrstcode"><code>http2stream.rstCode</code></a></li>
<li><a href="#all_http2_http2streamsentheaders"><code>http2stream.sentHeaders</code></a></li>
<li><a href="#all_http2_http2streamsentinfoheaders"><code>http2stream.sentInfoHeaders</code></a></li>
<li><a href="#all_http2_http2streamsenttrailers"><code>http2stream.sentTrailers</code></a></li>
<li><a href="#all_http2_http2streamsession"><code>http2stream.session</code></a></li>
<li><a href="#all_http2_http2streamsettimeoutmsecs-callback"><code>http2stream.setTimeout(msecs, callback)</code></a></li>
<li><a href="#all_http2_http2streamstate"><code>http2stream.state</code></a></li>
<li><a href="#all_http2_http2streamsendtrailersheaders"><code>http2stream.sendTrailers(headers)</code></a></li>
</ul>
</li>
<li><a href="#all_http2_class-clienthttp2stream">Class: <code>ClientHttp2Stream</code></a>
<ul>
<li><a href="#all_http2_event-continue">Event: <code>'continue'</code></a></li>
<li><a href="#all_http2_event-headers">Event: <code>'headers'</code></a></li>
<li><a href="#all_http2_event-push">Event: <code>'push'</code></a></li>
<li><a href="#all_http2_event-response">Event: <code>'response'</code></a></li>
</ul>
</li>
<li><a href="#all_http2_class-serverhttp2stream">Class: <code>ServerHttp2Stream</code></a>
<ul>
<li><a href="#all_http2_http2streamadditionalheadersheaders"><code>http2stream.additionalHeaders(headers)</code></a></li>
<li><a href="#all_http2_http2streamheaderssent"><code>http2stream.headersSent</code></a></li>
<li><a href="#all_http2_http2streampushallowed"><code>http2stream.pushAllowed</code></a></li>
<li><a href="#all_http2_http2streampushstreamheaders-options-callback"><code>http2stream.pushStream(headers[, options], callback)</code></a></li>
<li><a href="#all_http2_http2streamrespondheaders-options"><code>http2stream.respond([headers[, options]])</code></a></li>
<li><a href="#all_http2_http2streamrespondwithfdfd-headers-options"><code>http2stream.respondWithFD(fd[, headers[, options]])</code></a></li>
<li><a href="#all_http2_http2streamrespondwithfilepath-headers-options"><code>http2stream.respondWithFile(path[, headers[, options]])</code></a></li>
</ul>
</li>
<li><a href="#all_http2_class-http2server">Class: <code>Http2Server</code></a>
<ul>
<li><a href="#all_http2_event-checkcontinue">Event: <code>'checkContinue'</code></a></li>
<li><a href="#all_http2_event-connection">Event: <code>'connection'</code></a></li>
<li><a href="#all_http2_event-request">Event: <code>'request'</code></a></li>
<li><a href="#all_http2_event-session">Event: <code>'session'</code></a></li>
<li><a href="#all_http2_event-sessionerror">Event: <code>'sessionError'</code></a></li>
<li><a href="#all_http2_event-stream_1">Event: <code>'stream'</code></a></li>
<li><a href="#all_http2_event-timeout_2">Event: <code>'timeout'</code></a></li>
<li><a href="#all_http2_serverclosecallback"><code>server.close([callback])</code></a></li>
<li><span class="stability_1"><a href="#all_http2_serversymbolasyncdispose"><code>server[Symbol.asyncDispose]()</code></a></span></li>
<li><a href="#all_http2_serversettimeoutmsecs-callback"><code>server.setTimeout([msecs][, callback])</code></a></li>
<li><a href="#all_http2_servertimeout"><code>server.timeout</code></a></li>
<li><a href="#all_http2_serverupdatesettingssettings"><code>server.updateSettings([settings])</code></a></li>
</ul>
</li>
<li><a href="#all_http2_class-http2secureserver">Class: <code>Http2SecureServer</code></a>
<ul>
<li><a href="#all_http2_event-checkcontinue_1">Event: <code>'checkContinue'</code></a></li>
<li><a href="#all_http2_event-connection_1">Event: <code>'connection'</code></a></li>
<li><a href="#all_http2_event-request_1">Event: <code>'request'</code></a></li>
<li><a href="#all_http2_event-session_1">Event: <code>'session'</code></a></li>
<li><a href="#all_http2_event-sessionerror_1">Event: <code>'sessionError'</code></a></li>
<li><a href="#all_http2_event-stream_2">Event: <code>'stream'</code></a></li>
<li><a href="#all_http2_event-timeout_3">Event: <code>'timeout'</code></a></li>
<li><a href="#all_http2_event-unknownprotocol">Event: <code>'unknownProtocol'</code></a></li>
<li><a href="#all_http2_serverclosecallback_1"><code>server.close([callback])</code></a></li>
<li><a href="#all_http2_serversettimeoutmsecs-callback_1"><code>server.setTimeout([msecs][, callback])</code></a></li>
<li><a href="#all_http2_servertimeout_1"><code>server.timeout</code></a></li>
<li><a href="#all_http2_serverupdatesettingssettings_1"><code>server.updateSettings([settings])</code></a></li>
</ul>
</li>
<li><a href="#all_http2_http2createserveroptions-onrequesthandler"><code>http2.createServer([options][, onRequestHandler])</code></a></li>
<li><a href="#all_http2_http2createsecureserveroptions-onrequesthandler"><code>http2.createSecureServer(options[, onRequestHandler])</code></a></li>
<li><a href="#all_http2_http2connectauthority-options-listener"><code>http2.connect(authority[, options][, listener])</code></a></li>
<li><a href="#all_http2_http2constants"><code>http2.constants</code></a>
<ul>
<li><a href="#all_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="#all_http2_http2getdefaultsettings"><code>http2.getDefaultSettings()</code></a></li>
<li><a href="#all_http2_http2getpackedsettingssettings"><code>http2.getPackedSettings([settings])</code></a></li>
<li><a href="#all_http2_http2getunpackedsettingsbuf"><code>http2.getUnpackedSettings(buf)</code></a></li>
<li><a href="#all_http2_http2performserverhandshakesocket-options"><code>http2.performServerHandshake(socket[, options])</code></a></li>
<li><a href="#all_http2_http2sensitiveheaders"><code>http2.sensitiveHeaders</code></a></li>
<li><a href="#all_http2_headers-object">Headers object</a>
<ul>
<li><a href="#all_http2_sensitive-headers">Sensitive headers</a></li>
</ul>
</li>
<li><a href="#all_http2_settings-object">Settings object</a></li>
<li><a href="#all_http2_error-handling">Error handling</a></li>
<li><a href="#all_http2_invalid-character-handling-in-header-names-and-values">Invalid character handling in header names and values</a></li>
<li><a href="#all_http2_push-streams-on-the-client">Push streams on the client</a></li>
<li><a href="#all_http2_supporting-the-connect-method">Supporting the <code>CONNECT</code> method</a></li>
<li><a href="#all_http2_the-extended-connect-protocol">The extended <code>CONNECT</code> protocol</a></li>
</ul>
</li>
<li><a href="#all_http2_compatibility-api">Compatibility API</a>
<ul>
<li><a href="#all_http2_alpn-negotiation">ALPN negotiation</a></li>
<li><a href="#all_http2_class-http2http2serverrequest">Class: <code>http2.Http2ServerRequest</code></a>
<ul>
<li><a href="#all_http2_event-aborted_1">Event: <code>'aborted'</code></a></li>
<li><a href="#all_http2_event-close_2">Event: <code>'close'</code></a></li>
<li><a href="#all_http2_requestaborted"><code>request.aborted</code></a></li>
<li><a href="#all_http2_requestauthority"><code>request.authority</code></a></li>
<li><a href="#all_http2_requestcomplete"><code>request.complete</code></a></li>
<li><span class="stability_0"><a href="#all_http2_requestconnection"><code>request.connection</code></a></span></li>
<li><a href="#all_http2_requestdestroyerror"><code>request.destroy([error])</code></a></li>
<li><a href="#all_http2_requestheaders"><code>request.headers</code></a></li>
<li><a href="#all_http2_requesthttpversion"><code>request.httpVersion</code></a></li>
<li><a href="#all_http2_requestmethod"><code>request.method</code></a></li>
<li><a href="#all_http2_requestrawheaders"><code>request.rawHeaders</code></a></li>
<li><a href="#all_http2_requestrawtrailers"><code>request.rawTrailers</code></a></li>
<li><a href="#all_http2_requestscheme"><code>request.scheme</code></a></li>
<li><a href="#all_http2_requestsettimeoutmsecs-callback"><code>request.setTimeout(msecs, callback)</code></a></li>
<li><a href="#all_http2_requestsocket"><code>request.socket</code></a></li>
<li><a href="#all_http2_requeststream"><code>request.stream</code></a></li>
<li><a href="#all_http2_requesttrailers"><code>request.trailers</code></a></li>
<li><a href="#all_http2_requesturl"><code>request.url</code></a></li>
</ul>
</li>
<li><a href="#all_http2_class-http2http2serverresponse">Class: <code>http2.Http2ServerResponse</code></a>
<ul>
<li><a href="#all_http2_event-close_3">Event: <code>'close'</code></a></li>
<li><a href="#all_http2_event-finish">Event: <code>'finish'</code></a></li>
<li><a href="#all_http2_responseaddtrailersheaders"><code>response.addTrailers(headers)</code></a></li>
<li><a href="#all_http2_responseappendheadername-value"><code>response.appendHeader(name, value)</code></a></li>
<li><span class="stability_0"><a href="#all_http2_responseconnection"><code>response.connection</code></a></span></li>
<li><a href="#all_http2_responsecreatepushresponseheaders-callback"><code>response.createPushResponse(headers, callback)</code></a></li>
<li><a href="#all_http2_responseenddata-encoding-callback"><code>response.end([data[, encoding]][, callback])</code></a></li>
<li><span class="stability_0"><a href="#all_http2_responsefinished"><code>response.finished</code></a></span></li>
<li><a href="#all_http2_responsegetheadername"><code>response.getHeader(name)</code></a></li>
<li><a href="#all_http2_responsegetheadernames"><code>response.getHeaderNames()</code></a></li>
<li><a href="#all_http2_responsegetheaders"><code>response.getHeaders()</code></a></li>
<li><a href="#all_http2_responsehasheadername"><code>response.hasHeader(name)</code></a></li>
<li><a href="#all_http2_responseheaderssent"><code>response.headersSent</code></a></li>
<li><a href="#all_http2_responseremoveheadername"><code>response.removeHeader(name)</code></a></li>
<li><a href="#all_http2_responsereq"><code>response.req</code></a></li>
<li><a href="#all_http2_responsesenddate"><code>response.sendDate</code></a></li>
<li><a href="#all_http2_responsesetheadername-value"><code>response.setHeader(name, value)</code></a></li>
<li><a href="#all_http2_responsesettimeoutmsecs-callback"><code>response.setTimeout(msecs[, callback])</code></a></li>
<li><a href="#all_http2_responsesocket"><code>response.socket</code></a></li>
<li><a href="#all_http2_responsestatuscode"><code>response.statusCode</code></a></li>
<li><a href="#all_http2_responsestatusmessage"><code>response.statusMessage</code></a></li>
<li><a href="#all_http2_responsestream"><code>response.stream</code></a></li>
<li><a href="#all_http2_responsewritableended"><code>response.writableEnded</code></a></li>
<li><a href="#all_http2_responsewritechunk-encoding-callback"><code>response.write(chunk[, encoding][, callback])</code></a></li>
<li><a href="#all_http2_responsewritecontinue"><code>response.writeContinue()</code></a></li>
<li><a href="#all_http2_responsewriteearlyhintshints"><code>response.writeEarlyHints(hints)</code></a></li>
<li><a href="#all_http2_responsewriteheadstatuscode-statusmessage-headers"><code>response.writeHead(statusCode[, statusMessage][, headers])</code></a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_http2_collecting-http2-performance-metrics">Collecting HTTP/2 performance metrics</a></li>
<li><a href="#all_http2_note-on-authority-and-host">Note on <code>:authority</code> and <code>host</code></a></li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_https_https">HTTPS</a></span>
<ul>
<li><a href="#all_https_determining-if-crypto-support-is-unavailable">Determining if crypto support is unavailable</a></li>
<li><a href="#all_https_class-httpsagent">Class: <code>https.Agent</code></a>
<ul>
<li><a href="#all_https_new-agentoptions"><code>new Agent([options])</code></a>
<ul>
<li><a href="#all_https_event-keylog">Event: <code>'keylog'</code></a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_https_class-httpsserver">Class: <code>https.Server</code></a>
<ul>
<li><a href="#all_https_serverclosecallback"><code>server.close([callback])</code></a></li>
<li><span class="stability_1"><a href="#all_https_serversymbolasyncdispose"><code>server[Symbol.asyncDispose]()</code></a></span></li>
<li><a href="#all_https_servercloseallconnections"><code>server.closeAllConnections()</code></a></li>
<li><a href="#all_https_servercloseidleconnections"><code>server.closeIdleConnections()</code></a></li>
<li><a href="#all_https_serverheaderstimeout"><code>server.headersTimeout</code></a></li>
<li><a href="#all_https_serverlisten"><code>server.listen()</code></a></li>
<li><a href="#all_https_servermaxheaderscount"><code>server.maxHeadersCount</code></a></li>
<li><a href="#all_https_serverrequesttimeout"><code>server.requestTimeout</code></a></li>
<li><a href="#all_https_serversettimeoutmsecs-callback"><code>server.setTimeout([msecs][, callback])</code></a></li>
<li><a href="#all_https_servertimeout"><code>server.timeout</code></a></li>
<li><a href="#all_https_serverkeepalivetimeout"><code>server.keepAliveTimeout</code></a></li>
</ul>
</li>
<li><a href="#all_https_httpscreateserveroptions-requestlistener"><code>https.createServer([options][, requestListener])</code></a></li>
<li><a href="#all_https_httpsgetoptions-callback"><code>https.get(options[, callback])</code></a></li>
<li><a href="#all_https_httpsgeturl-options-callback"><code>https.get(url[, options][, callback])</code></a></li>
<li><a href="#all_https_httpsglobalagent"><code>https.globalAgent</code></a></li>
<li><a href="#all_https_httpsrequestoptions-callback"><code>https.request(options[, callback])</code></a></li>
<li><a href="#all_https_httpsrequesturl-options-callback"><code>https.request(url[, options][, callback])</code></a></li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_inspector_inspector">Inspector</a></span>
<ul>
<li><span class="stability_1"><a href="#all_inspector_promises-api">Promises API</a></span>
<ul>
<li><a href="#all_inspector_class-inspectorsession">Class: <code>inspector.Session</code></a>
<ul>
<li><a href="#all_inspector_new-inspectorsession"><code>new inspector.Session()</code></a></li>
<li><a href="#all_inspector_event-inspectornotification">Event: <code>'inspectorNotification'</code></a></li>
<li><a href="#all_inspector_event-inspector-protocol-method">Event: <code>&#x3C;inspector-protocol-method></code>;</a></li>
<li><a href="#all_inspector_sessionconnect"><code>session.connect()</code></a></li>
<li><a href="#all_inspector_sessionconnecttomainthread"><code>session.connectToMainThread()</code></a></li>
<li><a href="#all_inspector_sessiondisconnect"><code>session.disconnect()</code></a></li>
<li><a href="#all_inspector_sessionpostmethod-params"><code>session.post(method[, params])</code></a></li>
<li><a href="#all_inspector_example-usage">Example usage</a>
<ul>
<li><a href="#all_inspector_cpu-profiler">CPU profiler</a></li>
<li><a href="#all_inspector_heap-profiler">Heap profiler</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_inspector_callback-api">Callback API</a>
<ul>
<li><a href="#all_inspector_class-inspectorsession_1">Class: <code>inspector.Session</code></a>
<ul>
<li><a href="#all_inspector_new-inspectorsession_1"><code>new inspector.Session()</code></a></li>
<li><a href="#all_inspector_event-inspectornotification_1">Event: <code>'inspectorNotification'</code></a></li>
<li><a href="#all_inspector_event-inspector-protocol-method_1">Event: <code>&#x3C;inspector-protocol-method></code>;</a></li>
<li><a href="#all_inspector_sessionconnect_1"><code>session.connect()</code></a></li>
<li><a href="#all_inspector_sessionconnecttomainthread_1"><code>session.connectToMainThread()</code></a></li>
<li><a href="#all_inspector_sessiondisconnect_1"><code>session.disconnect()</code></a></li>
<li><a href="#all_inspector_sessionpostmethod-params-callback"><code>session.post(method[, params][, callback])</code></a></li>
<li><a href="#all_inspector_example-usage_1">Example usage</a>
<ul>
<li><a href="#all_inspector_cpu-profiler_1">CPU profiler</a></li>
<li><a href="#all_inspector_heap-profiler_1">Heap profiler</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_inspector_common-objects">Common Objects</a>
<ul>
<li><a href="#all_inspector_inspectorclose"><code>inspector.close()</code></a></li>
<li><a href="#all_inspector_inspectorconsole"><code>inspector.console</code></a></li>
<li><a href="#all_inspector_inspectoropenport-host-wait"><code>inspector.open([port[, host[, wait]]])</code></a></li>
<li><a href="#all_inspector_inspectorurl"><code>inspector.url()</code></a></li>
<li><a href="#all_inspector_inspectorwaitfordebugger"><code>inspector.waitForDebugger()</code></a></li>
</ul>
</li>
<li><a href="#all_inspector_integration-with-devtools">Integration with DevTools</a>
<ul>
<li><span class="stability_1"><a href="#all_inspector_inspectornetworkrequestwillbesentparams"><code>inspector.Network.requestWillBeSent([params])</code></a></span></li>
<li><span class="stability_1"><a href="#all_inspector_inspectornetworkresponsereceivedparams"><code>inspector.Network.responseReceived([params])</code></a></span></li>
<li><span class="stability_1"><a href="#all_inspector_inspectornetworkloadingfinishedparams"><code>inspector.Network.loadingFinished([params])</code></a></span></li>
<li><span class="stability_1"><a href="#all_inspector_inspectornetworkloadingfailedparams"><code>inspector.Network.loadingFailed([params])</code></a></span></li>
</ul>
</li>
<li><a href="#all_inspector_support-of-breakpoints">Support of breakpoints</a></li>
</ul>
</li>
<li><a href="#all_intl_internationalization-support">Internationalization support</a>
<ul>
<li><a href="#all_intl_options-for-building-nodejs">Options for building Node.js</a>
<ul>
<li><a href="#all_intl_disable-all-internationalization-features-none">Disable all internationalization features (<code>none</code>)</a></li>
<li><a href="#all_intl_build-with-a-pre-installed-icu-system-icu">Build with a pre-installed ICU (<code>system-icu</code>)</a></li>
<li><a href="#all_intl_embed-a-limited-set-of-icu-data-small-icu">Embed a limited set of ICU data (<code>small-icu</code>)</a>
<ul>
<li><a href="#all_intl_providing-icu-data-at-runtime">Providing ICU data at runtime</a></li>
</ul>
</li>
<li><a href="#all_intl_embed-the-entire-icu-full-icu">Embed the entire ICU (<code>full-icu</code>)</a></li>
</ul>
</li>
<li><a href="#all_intl_detecting-internationalization-support">Detecting internationalization support</a></li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_modules_modules-commonjs-modules">Modules: CommonJS modules</a></span>
<ul>
<li><a href="#all_modules_enabling">Enabling</a></li>
<li><a href="#all_modules_accessing-the-main-module">Accessing the main module</a></li>
<li><a href="#all_modules_package-manager-tips">Package manager tips</a></li>
<li><a href="#all_modules_loading-ecmascript-modules-using-require">Loading ECMAScript modules using <code>require()</code></a></li>
<li><a href="#all_modules_all-together">All together</a></li>
<li><a href="#all_modules_caching">Caching</a>
<ul>
<li><a href="#all_modules_module-caching-caveats">Module caching caveats</a></li>
</ul>
</li>
<li><a href="#all_modules_built-in-modules">Built-in modules</a>
<ul>
<li><a href="#all_modules_built-in-modules-with-mandatory-node-prefix">Built-in modules with mandatory <code>node:</code> prefix</a></li>
</ul>
</li>
<li><a href="#all_modules_cycles">Cycles</a></li>
<li><a href="#all_modules_file-modules">File modules</a></li>
<li><span class="stability_3"><a href="#all_modules_folders-as-modules">Folders as modules</a></span></li>
<li><a href="#all_modules_loading-from-node_modules-folders">Loading from <code>node_modules</code> folders</a></li>
<li><a href="#all_modules_loading-from-the-global-folders">Loading from the global folders</a></li>
<li><a href="#all_modules_the-module-wrapper">The module wrapper</a></li>
<li><a href="#all_modules_the-module-scope">The module scope</a>
<ul>
<li><a href="#all_modules___dirname"><code>__dirname</code></a></li>
<li><a href="#all_modules___filename"><code>__filename</code></a></li>
<li><a href="#all_modules_exports"><code>exports</code></a></li>
<li><a href="#all_modules_module"><code>module</code></a></li>
<li><a href="#all_modules_requireid"><code>require(id)</code></a>
<ul>
<li><a href="#all_modules_requirecache"><code>require.cache</code></a></li>
<li><span class="stability_0"><a href="#all_modules_requireextensions"><code>require.extensions</code></a></span></li>
<li><a href="#all_modules_requiremain"><code>require.main</code></a></li>
<li><a href="#all_modules_requireresolverequest-options"><code>require.resolve(request[, options])</code></a>
<ul>
<li><a href="#all_modules_requireresolvepathsrequest"><code>require.resolve.paths(request)</code></a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_modules_the-module-object">The <code>module</code> object</a>
<ul>
<li><a href="#all_modules_modulechildren"><code>module.children</code></a></li>
<li><a href="#all_modules_moduleexports"><code>module.exports</code></a>
<ul>
<li><a href="#all_modules_exports-shortcut"><code>exports</code> shortcut</a></li>
</ul>
</li>
<li><a href="#all_modules_modulefilename"><code>module.filename</code></a></li>
<li><a href="#all_modules_moduleid"><code>module.id</code></a></li>
<li><a href="#all_modules_moduleispreloading"><code>module.isPreloading</code></a></li>
<li><a href="#all_modules_moduleloaded"><code>module.loaded</code></a></li>
<li><span class="stability_0"><a href="#all_modules_moduleparent"><code>module.parent</code></a></span></li>
<li><a href="#all_modules_modulepath"><code>module.path</code></a></li>
<li><a href="#all_modules_modulepaths"><code>module.paths</code></a></li>
<li><a href="#all_modules_modulerequireid"><code>module.require(id)</code></a></li>
</ul>
</li>
<li><a href="#all_modules_the-module-object_1">The <code>Module</code> object</a></li>
<li><a href="#all_modules_source-map-v3-support">Source map v3 support</a></li>
</ul>
</li>
<li><a href="#all_esm_modules-ecmascript-modules">Modules: ECMAScript modules</a>
<ul>
<li><a href="#all_esm_introduction">Introduction</a></li>
<li><a href="#all_esm_enabling">Enabling</a></li>
<li><a href="#all_esm_packages">Packages</a></li>
<li><a href="#all_esm_import-specifiers"><code>import</code> Specifiers</a>
<ul>
<li><a href="#all_esm_terminology">Terminology</a></li>
<li><a href="#all_esm_mandatory-file-extensions">Mandatory file extensions</a></li>
<li><a href="#all_esm_urls">URLs</a>
<ul>
<li><a href="#all_esm_file-urls"><code>file:</code> URLs</a></li>
<li><a href="#all_esm_data-imports"><code>data:</code> imports</a></li>
<li><a href="#all_esm_node-imports"><code>node:</code> imports</a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_esm_import-attributes">Import attributes</a></span></li>
<li><a href="#all_esm_built-in-modules">Built-in modules</a></li>
<li><a href="#all_esm_import-expressions"><code>import()</code> expressions</a></li>
<li><a href="#all_esm_importmeta"><code>import.meta</code></a>
<ul>
<li><span class="stability_1"><a href="#all_esm_importmetadirname"><code>import.meta.dirname</code></a></span></li>
<li><span class="stability_1"><a href="#all_esm_importmetafilename"><code>import.meta.filename</code></a></span></li>
<li><a href="#all_esm_importmetaurl"><code>import.meta.url</code></a></li>
<li><span class="stability_1"><a href="#all_esm_importmetaresolvespecifier"><code>import.meta.resolve(specifier)</code></a></span></li>
</ul>
</li>
<li><a href="#all_esm_interoperability-with-commonjs">Interoperability with CommonJS</a>
<ul>
<li><a href="#all_esm_import-statements"><code>import</code> statements</a></li>
<li><a href="#all_esm_require"><code>require</code></a></li>
<li><a href="#all_esm_commonjs-namespaces">CommonJS Namespaces</a></li>
<li><a href="#all_esm_differences-between-es-modules-and-commonjs">Differences between ES modules and CommonJS</a>
<ul>
<li><a href="#all_esm_no-require-exports-or-moduleexports">No <code>require</code>, <code>exports</code>, or <code>module.exports</code></a></li>
<li><a href="#all_esm_no-__filename-or-__dirname">No <code>__filename</code> or <code>__dirname</code></a></li>
<li><a href="#all_esm_no-addon-loading">No Addon Loading</a></li>
<li><a href="#all_esm_no-requireresolve">No <code>require.resolve</code></a></li>
<li><a href="#all_esm_no-node_path">No <code>NODE_PATH</code></a></li>
<li><a href="#all_esm_no-requireextensions">No <code>require.extensions</code></a></li>
<li><a href="#all_esm_no-requirecache">No <code>require.cache</code></a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_esm_json-modules">JSON modules</a></span></li>
<li><span class="stability_1"><a href="#all_esm_wasm-modules">Wasm modules</a></span></li>
<li><a href="#all_esm_top-level-await">Top-level <code>await</code></a></li>
<li><span class="stability_1"><a href="#all_esm_https-and-http-imports">HTTPS and HTTP imports</a></span>
<ul>
<li><a href="#all_esm_imports-are-limited-to-http1">Imports are limited to HTTP/1</a></li>
<li><a href="#all_esm_http-is-limited-to-loopback-addresses">HTTP is limited to loopback addresses</a></li>
<li><a href="#all_esm_authentication-is-never-sent-to-the-destination-server">Authentication is never sent to the destination server.</a></li>
<li><a href="#all_esm_cors-is-never-checked-on-the-destination-server">CORS is never checked on the destination server</a></li>
<li><a href="#all_esm_cannot-load-non-network-dependencies">Cannot load non-network dependencies</a></li>
<li><a href="#all_esm_network-based-loading-is-not-enabled-by-default">Network-based loading is not enabled by default</a></li>
</ul>
</li>
<li><a href="#all_esm_loaders">Loaders</a></li>
<li><a href="#all_esm_resolution-and-loading-algorithm">Resolution and loading algorithm</a>
<ul>
<li><a href="#all_esm_features">Features</a></li>
<li><a href="#all_esm_resolution-algorithm">Resolution algorithm</a></li>
<li><a href="#all_esm_resolution-algorithm-specification">Resolution Algorithm Specification</a></li>
<li><a href="#all_esm_customizing-esm-specifier-resolution-algorithm">Customizing ESM specifier resolution algorithm</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_module_modules-nodemodule-api">Modules: <code>node:module</code> API</a>
<ul>
<li><a href="#all_module_the-module-object">The <code>Module</code> object</a>
<ul>
<li><a href="#all_module_modulebuiltinmodules"><code>module.builtinModules</code></a></li>
<li><a href="#all_module_modulecreaterequirefilename"><code>module.createRequire(filename)</code></a></li>
<li><a href="#all_module_moduleisbuiltinmodulename"><code>module.isBuiltin(moduleName)</code></a></li>
<li><span class="stability_1"><a href="#all_module_moduleregisterspecifier-parenturl-options"><code>module.register(specifier[, parentURL][, options])</code></a></span></li>
<li><a href="#all_module_modulesyncbuiltinesmexports"><code>module.syncBuiltinESMExports()</code></a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_module_customization-hooks">Customization Hooks</a></span>
<ul>
<li><a href="#all_module_enabling">Enabling</a></li>
<li><a href="#all_module_chaining">Chaining</a></li>
<li><a href="#all_module_communication-with-module-customization-hooks">Communication with module customization hooks</a></li>
<li><a href="#all_module_hooks">Hooks</a>
<ul>
<li><span class="stability_1"><a href="#all_module_initialize"><code>initialize()</code></a></span></li>
<li><span class="stability_1"><a href="#all_module_resolvespecifier-context-nextresolve"><code>resolve(specifier, context, nextResolve)</code></a></span></li>
<li><span class="stability_1"><a href="#all_module_loadurl-context-nextload"><code>load(url, context, nextLoad)</code></a></span></li>
<li><span class="stability_1"><a href="#all_module_globalpreload"><code>globalPreload()</code></a></span></li>
</ul>
</li>
<li><a href="#all_module_examples">Examples</a>
<ul>
<li><a href="#all_module_import-from-https">Import from HTTPS</a></li>
<li><a href="#all_module_transpilation">Transpilation</a></li>
<li><a href="#all_module_import-maps">Import maps</a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_module_source-map-v3-support">Source map v3 support</a></span>
<ul>
<li><a href="#all_module_modulefindsourcemappath"><code>module.findSourceMap(path)</code></a></li>
<li><a href="#all_module_class-modulesourcemap">Class: <code>module.SourceMap</code></a>
<ul>
<li><a href="#all_module_new-sourcemappayload--linelengths-"><code>new SourceMap(payload[, { lineLengths }])</code></a></li>
<li><a href="#all_module_sourcemappayload"><code>sourceMap.payload</code></a></li>
<li><a href="#all_module_sourcemapfindentrylineoffset-columnoffset"><code>sourceMap.findEntry(lineOffset, columnOffset)</code></a></li>
<li><a href="#all_module_sourcemapfindoriginlinenumber-columnnumber"><code>sourceMap.findOrigin(lineNumber, columnNumber)</code></a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_packages_modules-packages">Modules: Packages</a>
<ul>
<li><a href="#all_packages_introduction">Introduction</a></li>
<li><a href="#all_packages_determining-module-system">Determining module system</a>
<ul>
<li><a href="#all_packages_introduction_1">Introduction</a></li>
<li><a href="#all_packages_modules-loaders">Modules loaders</a></li>
<li><a href="#all_packages_packagejson-and-file-extensions"><code>package.json</code> and file extensions</a></li>
<li><a href="#all_packages_--input-type-flag"><code>--input-type</code> flag</a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_packages_determining-package-manager">Determining package manager</a></span></li>
<li><a href="#all_packages_package-entry-points">Package entry points</a>
<ul>
<li><a href="#all_packages_main-entry-point-export">Main entry point export</a></li>
<li><a href="#all_packages_subpath-exports">Subpath exports</a>
<ul>
<li><a href="#all_packages_extensions-in-subpaths">Extensions in subpaths</a></li>
</ul>
</li>
<li><a href="#all_packages_exports-sugar">Exports sugar</a></li>
<li><a href="#all_packages_subpath-imports">Subpath imports</a></li>
<li><a href="#all_packages_subpath-patterns">Subpath patterns</a></li>
<li><a href="#all_packages_conditional-exports">Conditional exports</a></li>
<li><a href="#all_packages_nested-conditions">Nested conditions</a></li>
<li><a href="#all_packages_resolving-user-conditions">Resolving user conditions</a></li>
<li><a href="#all_packages_community-conditions-definitions">Community Conditions Definitions</a></li>
<li><a href="#all_packages_self-referencing-a-package-using-its-name">Self-referencing a package using its name</a></li>
</ul>
</li>
<li><a href="#all_packages_dual-commonjses-module-packages">Dual CommonJS/ES module packages</a>
<ul>
<li><a href="#all_packages_dual-package-hazard">Dual package hazard</a></li>
<li><a href="#all_packages_writing-dual-packages-while-avoiding-or-minimizing-hazards">Writing dual packages while avoiding or minimizing hazards</a>
<ul>
<li><a href="#all_packages_approach-1-use-an-es-module-wrapper">Approach #1: Use an ES module wrapper</a></li>
<li><a href="#all_packages_approach-2-isolate-state">Approach #2: Isolate state</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_packages_nodejs-packagejson-field-definitions">Node.js <code>package.json</code> field definitions</a>
<ul>
<li><a href="#all_packages_name"><code>"name"</code></a></li>
<li><a href="#all_packages_main"><code>"main"</code></a></li>
<li><span class="stability_1"><a href="#all_packages_packagemanager"><code>"packageManager"</code></a></span></li>
<li><a href="#all_packages_type"><code>"type"</code></a></li>
<li><a href="#all_packages_exports"><code>"exports"</code></a></li>
<li><a href="#all_packages_imports"><code>"imports"</code></a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_net_net">Net</a></span>
<ul>
<li><a href="#all_net_ipc-support">IPC support</a>
<ul>
<li><a href="#all_net_identifying-paths-for-ipc-connections">Identifying paths for IPC connections</a></li>
</ul>
</li>
<li><a href="#all_net_class-netblocklist">Class: <code>net.BlockList</code></a>
<ul>
<li><a href="#all_net_blocklistaddaddressaddress-type"><code>blockList.addAddress(address[, type])</code></a></li>
<li><a href="#all_net_blocklistaddrangestart-end-type"><code>blockList.addRange(start, end[, type])</code></a></li>
<li><a href="#all_net_blocklistaddsubnetnet-prefix-type"><code>blockList.addSubnet(net, prefix[, type])</code></a></li>
<li><a href="#all_net_blocklistcheckaddress-type"><code>blockList.check(address[, type])</code></a></li>
<li><a href="#all_net_blocklistrules"><code>blockList.rules</code></a></li>
</ul>
</li>
<li><a href="#all_net_class-netsocketaddress">Class: <code>net.SocketAddress</code></a>
<ul>
<li><a href="#all_net_new-netsocketaddressoptions"><code>new net.SocketAddress([options])</code></a></li>
<li><a href="#all_net_socketaddressaddress"><code>socketaddress.address</code></a></li>
<li><a href="#all_net_socketaddressfamily"><code>socketaddress.family</code></a></li>
<li><a href="#all_net_socketaddressflowlabel"><code>socketaddress.flowlabel</code></a></li>
<li><a href="#all_net_socketaddressport"><code>socketaddress.port</code></a></li>
</ul>
</li>
<li><a href="#all_net_class-netserver">Class: <code>net.Server</code></a>
<ul>
<li><a href="#all_net_new-netserveroptions-connectionlistener"><code>new net.Server([options][, connectionListener])</code></a></li>
<li><a href="#all_net_event-close">Event: <code>'close'</code></a></li>
<li><a href="#all_net_event-connection">Event: <code>'connection'</code></a></li>
<li><a href="#all_net_event-error">Event: <code>'error'</code></a></li>
<li><a href="#all_net_event-listening">Event: <code>'listening'</code></a></li>
<li><a href="#all_net_event-drop">Event: <code>'drop'</code></a></li>
<li><a href="#all_net_serveraddress"><code>server.address()</code></a></li>
<li><a href="#all_net_serverclosecallback"><code>server.close([callback])</code></a></li>
<li><span class="stability_1"><a href="#all_net_serversymbolasyncdispose"><code>server[Symbol.asyncDispose]()</code></a></span></li>
<li><a href="#all_net_servergetconnectionscallback"><code>server.getConnections(callback)</code></a></li>
<li><a href="#all_net_serverlisten"><code>server.listen()</code></a>
<ul>
<li><a href="#all_net_serverlistenhandle-backlog-callback"><code>server.listen(handle[, backlog][, callback])</code></a></li>
<li><a href="#all_net_serverlistenoptions-callback"><code>server.listen(options[, callback])</code></a></li>
<li><a href="#all_net_serverlistenpath-backlog-callback"><code>server.listen(path[, backlog][, callback])</code></a></li>
<li><a href="#all_net_serverlistenport-host-backlog-callback"><code>server.listen([port[, host[, backlog]]][, callback])</code></a></li>
</ul>
</li>
<li><a href="#all_net_serverlistening"><code>server.listening</code></a></li>
<li><a href="#all_net_servermaxconnections"><code>server.maxConnections</code></a></li>
<li><a href="#all_net_serverref"><code>server.ref()</code></a></li>
<li><a href="#all_net_serverunref"><code>server.unref()</code></a></li>
</ul>
</li>
<li><a href="#all_net_class-netsocket">Class: <code>net.Socket</code></a>
<ul>
<li><a href="#all_net_new-netsocketoptions"><code>new net.Socket([options])</code></a></li>
<li><a href="#all_net_event-close_1">Event: <code>'close'</code></a></li>
<li><a href="#all_net_event-connect">Event: <code>'connect'</code></a></li>
<li><a href="#all_net_event-connectionattempt">Event: <code>'connectionAttempt'</code></a></li>
<li><a href="#all_net_event-connectionattemptfailed">Event: <code>'connectionAttemptFailed'</code></a></li>
<li><a href="#all_net_event-connectionattempttimeout">Event: <code>'connectionAttemptTimeout'</code></a></li>
<li><a href="#all_net_event-data">Event: <code>'data'</code></a></li>
<li><a href="#all_net_event-drain">Event: <code>'drain'</code></a></li>
<li><a href="#all_net_event-end">Event: <code>'end'</code></a></li>
<li><a href="#all_net_event-error_1">Event: <code>'error'</code></a></li>
<li><a href="#all_net_event-lookup">Event: <code>'lookup'</code></a></li>
<li><a href="#all_net_event-ready">Event: <code>'ready'</code></a></li>
<li><a href="#all_net_event-timeout">Event: <code>'timeout'</code></a></li>
<li><a href="#all_net_socketaddress"><code>socket.address()</code></a></li>
<li><a href="#all_net_socketautoselectfamilyattemptedaddresses"><code>socket.autoSelectFamilyAttemptedAddresses</code></a></li>
<li><span class="stability_0"><a href="#all_net_socketbuffersize"><code>socket.bufferSize</code></a></span></li>
<li><a href="#all_net_socketbytesread"><code>socket.bytesRead</code></a></li>
<li><a href="#all_net_socketbyteswritten"><code>socket.bytesWritten</code></a></li>
<li><a href="#all_net_socketconnect"><code>socket.connect()</code></a>
<ul>
<li><a href="#all_net_socketconnectoptions-connectlistener"><code>socket.connect(options[, connectListener])</code></a></li>
<li><a href="#all_net_socketconnectpath-connectlistener"><code>socket.connect(path[, connectListener])</code></a></li>
<li><a href="#all_net_socketconnectport-host-connectlistener"><code>socket.connect(port[, host][, connectListener])</code></a></li>
</ul>
</li>
<li><a href="#all_net_socketconnecting"><code>socket.connecting</code></a></li>
<li><a href="#all_net_socketdestroyerror"><code>socket.destroy([error])</code></a></li>
<li><a href="#all_net_socketdestroyed"><code>socket.destroyed</code></a></li>
<li><a href="#all_net_socketdestroysoon"><code>socket.destroySoon()</code></a></li>
<li><a href="#all_net_socketenddata-encoding-callback"><code>socket.end([data[, encoding]][, callback])</code></a></li>
<li><a href="#all_net_socketlocaladdress"><code>socket.localAddress</code></a></li>
<li><a href="#all_net_socketlocalport"><code>socket.localPort</code></a></li>
<li><a href="#all_net_socketlocalfamily"><code>socket.localFamily</code></a></li>
<li><a href="#all_net_socketpause"><code>socket.pause()</code></a></li>
<li><a href="#all_net_socketpending"><code>socket.pending</code></a></li>
<li><a href="#all_net_socketref"><code>socket.ref()</code></a></li>
<li><a href="#all_net_socketremoteaddress"><code>socket.remoteAddress</code></a></li>
<li><a href="#all_net_socketremotefamily"><code>socket.remoteFamily</code></a></li>
<li><a href="#all_net_socketremoteport"><code>socket.remotePort</code></a></li>
<li><a href="#all_net_socketresetanddestroy"><code>socket.resetAndDestroy()</code></a></li>
<li><a href="#all_net_socketresume"><code>socket.resume()</code></a></li>
<li><a href="#all_net_socketsetencodingencoding"><code>socket.setEncoding([encoding])</code></a></li>
<li><a href="#all_net_socketsetkeepaliveenable-initialdelay"><code>socket.setKeepAlive([enable][, initialDelay])</code></a></li>
<li><a href="#all_net_socketsetnodelaynodelay"><code>socket.setNoDelay([noDelay])</code></a></li>
<li><a href="#all_net_socketsettimeouttimeout-callback"><code>socket.setTimeout(timeout[, callback])</code></a></li>
<li><a href="#all_net_sockettimeout"><code>socket.timeout</code></a></li>
<li><a href="#all_net_socketunref"><code>socket.unref()</code></a></li>
<li><a href="#all_net_socketwritedata-encoding-callback"><code>socket.write(data[, encoding][, callback])</code></a></li>
<li><a href="#all_net_socketreadystate"><code>socket.readyState</code></a></li>
</ul>
</li>
<li><a href="#all_net_netconnect"><code>net.connect()</code></a>
<ul>
<li><a href="#all_net_netconnectoptions-connectlistener"><code>net.connect(options[, connectListener])</code></a></li>
<li><a href="#all_net_netconnectpath-connectlistener"><code>net.connect(path[, connectListener])</code></a></li>
<li><a href="#all_net_netconnectport-host-connectlistener"><code>net.connect(port[, host][, connectListener])</code></a></li>
</ul>
</li>
<li><a href="#all_net_netcreateconnection"><code>net.createConnection()</code></a>
<ul>
<li><a href="#all_net_netcreateconnectionoptions-connectlistener"><code>net.createConnection(options[, connectListener])</code></a></li>
<li><a href="#all_net_netcreateconnectionpath-connectlistener"><code>net.createConnection(path[, connectListener])</code></a></li>
<li><a href="#all_net_netcreateconnectionport-host-connectlistener"><code>net.createConnection(port[, host][, connectListener])</code></a></li>
</ul>
</li>
<li><a href="#all_net_netcreateserveroptions-connectionlistener"><code>net.createServer([options][, connectionListener])</code></a></li>
<li><a href="#all_net_netgetdefaultautoselectfamily"><code>net.getDefaultAutoSelectFamily()</code></a></li>
<li><a href="#all_net_netsetdefaultautoselectfamilyvalue"><code>net.setDefaultAutoSelectFamily(value)</code></a></li>
<li><a href="#all_net_netgetdefaultautoselectfamilyattempttimeout"><code>net.getDefaultAutoSelectFamilyAttemptTimeout()</code></a></li>
<li><a href="#all_net_netsetdefaultautoselectfamilyattempttimeoutvalue"><code>net.setDefaultAutoSelectFamilyAttemptTimeout(value)</code></a></li>
<li><a href="#all_net_netisipinput"><code>net.isIP(input)</code></a></li>
<li><a href="#all_net_netisipv4input"><code>net.isIPv4(input)</code></a></li>
<li><a href="#all_net_netisipv6input"><code>net.isIPv6(input)</code></a></li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_os_os">OS</a></span>
<ul>
<li><a href="#all_os_oseol"><code>os.EOL</code></a></li>
<li><a href="#all_os_osavailableparallelism"><code>os.availableParallelism()</code></a></li>
<li><a href="#all_os_osarch"><code>os.arch()</code></a></li>
<li><a href="#all_os_osconstants"><code>os.constants</code></a></li>
<li><a href="#all_os_oscpus"><code>os.cpus()</code></a></li>
<li><a href="#all_os_osdevnull"><code>os.devNull</code></a></li>
<li><a href="#all_os_osendianness"><code>os.endianness()</code></a></li>
<li><a href="#all_os_osfreemem"><code>os.freemem()</code></a></li>
<li><a href="#all_os_osgetprioritypid"><code>os.getPriority([pid])</code></a></li>
<li><a href="#all_os_oshomedir"><code>os.homedir()</code></a></li>
<li><a href="#all_os_oshostname"><code>os.hostname()</code></a></li>
<li><a href="#all_os_osloadavg"><code>os.loadavg()</code></a></li>
<li><a href="#all_os_osmachine"><code>os.machine()</code></a></li>
<li><a href="#all_os_osnetworkinterfaces"><code>os.networkInterfaces()</code></a></li>
<li><a href="#all_os_osplatform"><code>os.platform()</code></a></li>
<li><a href="#all_os_osrelease"><code>os.release()</code></a></li>
<li><a href="#all_os_ossetprioritypid-priority"><code>os.setPriority([pid, ]priority)</code></a></li>
<li><a href="#all_os_ostmpdir"><code>os.tmpdir()</code></a></li>
<li><a href="#all_os_ostotalmem"><code>os.totalmem()</code></a></li>
<li><a href="#all_os_ostype"><code>os.type()</code></a></li>
<li><a href="#all_os_osuptime"><code>os.uptime()</code></a></li>
<li><a href="#all_os_osuserinfooptions"><code>os.userInfo([options])</code></a></li>
<li><a href="#all_os_osversion"><code>os.version()</code></a></li>
<li><a href="#all_os_os-constants">OS constants</a>
<ul>
<li><a href="#all_os_signal-constants">Signal constants</a></li>
<li><a href="#all_os_error-constants">Error constants</a>
<ul>
<li><a href="#all_os_posix-error-constants">POSIX error constants</a></li>
<li><a href="#all_os_windows-specific-error-constants">Windows-specific error constants</a></li>
</ul>
</li>
<li><a href="#all_os_dlopen-constants">dlopen constants</a></li>
<li><a href="#all_os_priority-constants">Priority constants</a></li>
<li><a href="#all_os_libuv-constants">libuv constants</a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_path_path">Path</a></span>
<ul>
<li><a href="#all_path_windows-vs-posix">Windows vs. POSIX</a></li>
<li><a href="#all_path_pathbasenamepath-suffix"><code>path.basename(path[, suffix])</code></a></li>
<li><a href="#all_path_pathdelimiter"><code>path.delimiter</code></a></li>
<li><a href="#all_path_pathdirnamepath"><code>path.dirname(path)</code></a></li>
<li><a href="#all_path_pathextnamepath"><code>path.extname(path)</code></a></li>
<li><a href="#all_path_pathformatpathobject"><code>path.format(pathObject)</code></a></li>
<li><span class="stability_1"><a href="#all_path_pathmatchesglobpath-pattern"><code>path.matchesGlob(path, pattern)</code></a></span></li>
<li><a href="#all_path_pathisabsolutepath"><code>path.isAbsolute(path)</code></a></li>
<li><a href="#all_path_pathjoinpaths"><code>path.join([...paths])</code></a></li>
<li><a href="#all_path_pathnormalizepath"><code>path.normalize(path)</code></a></li>
<li><a href="#all_path_pathparsepath"><code>path.parse(path)</code></a></li>
<li><a href="#all_path_pathposix"><code>path.posix</code></a></li>
<li><a href="#all_path_pathrelativefrom-to"><code>path.relative(from, to)</code></a></li>
<li><a href="#all_path_pathresolvepaths"><code>path.resolve([...paths])</code></a></li>
<li><a href="#all_path_pathsep"><code>path.sep</code></a></li>
<li><a href="#all_path_pathtonamespacedpathpath"><code>path.toNamespacedPath(path)</code></a></li>
<li><a href="#all_path_pathwin32"><code>path.win32</code></a></li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_perf_hooks_performance-measurement-apis">Performance measurement APIs</a></span>
<ul>
<li><a href="#all_perf_hooks_perf_hooksperformance"><code>perf_hooks.performance</code></a>
<ul>
<li><a href="#all_perf_hooks_performanceclearmarksname"><code>performance.clearMarks([name])</code></a></li>
<li><a href="#all_perf_hooks_performanceclearmeasuresname"><code>performance.clearMeasures([name])</code></a></li>
<li><a href="#all_perf_hooks_performanceclearresourcetimingsname"><code>performance.clearResourceTimings([name])</code></a></li>
<li><a href="#all_perf_hooks_performanceeventlooputilizationutilization1-utilization2"><code>performance.eventLoopUtilization([utilization1[, utilization2]])</code></a></li>
<li><a href="#all_perf_hooks_performancegetentries"><code>performance.getEntries()</code></a></li>
<li><a href="#all_perf_hooks_performancegetentriesbynamename-type"><code>performance.getEntriesByName(name[, type])</code></a></li>
<li><a href="#all_perf_hooks_performancegetentriesbytypetype"><code>performance.getEntriesByType(type)</code></a></li>
<li><a href="#all_perf_hooks_performancemarkname-options"><code>performance.mark(name[, options])</code></a></li>
<li><a href="#all_perf_hooks_performancemarkresourcetimingtiminginfo-requestedurl-initiatortype-global-cachemode"><code>performance.markResourceTiming(timingInfo, requestedUrl, initiatorType, global, cacheMode)</code></a></li>
<li><a href="#all_perf_hooks_performancemeasurename-startmarkoroptions-endmark"><code>performance.measure(name[, startMarkOrOptions[, endMark]])</code></a></li>
<li><a href="#all_perf_hooks_performancenodetiming"><code>performance.nodeTiming</code></a></li>
<li><a href="#all_perf_hooks_performancenow"><code>performance.now()</code></a></li>
<li><a href="#all_perf_hooks_performancesetresourcetimingbuffersizemaxsize"><code>performance.setResourceTimingBufferSize(maxSize)</code></a></li>
<li><a href="#all_perf_hooks_performancetimeorigin"><code>performance.timeOrigin</code></a></li>
<li><a href="#all_perf_hooks_performancetimerifyfn-options"><code>performance.timerify(fn[, options])</code></a></li>
<li><a href="#all_perf_hooks_performancetojson"><code>performance.toJSON()</code></a>
<ul>
<li><a href="#all_perf_hooks_event-resourcetimingbufferfull">Event: <code>'resourcetimingbufferfull'</code></a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_perf_hooks_class-performanceentry">Class: <code>PerformanceEntry</code></a>
<ul>
<li><a href="#all_perf_hooks_performanceentryduration"><code>performanceEntry.duration</code></a></li>
<li><a href="#all_perf_hooks_performanceentryentrytype"><code>performanceEntry.entryType</code></a></li>
<li><a href="#all_perf_hooks_performanceentryname"><code>performanceEntry.name</code></a></li>
<li><a href="#all_perf_hooks_performanceentrystarttime"><code>performanceEntry.startTime</code></a></li>
</ul>
</li>
<li><a href="#all_perf_hooks_class-performancemark">Class: <code>PerformanceMark</code></a>
<ul>
<li><a href="#all_perf_hooks_performancemarkdetail"><code>performanceMark.detail</code></a></li>
</ul>
</li>
<li><a href="#all_perf_hooks_class-performancemeasure">Class: <code>PerformanceMeasure</code></a>
<ul>
<li><a href="#all_perf_hooks_performancemeasuredetail"><code>performanceMeasure.detail</code></a></li>
</ul>
</li>
<li><a href="#all_perf_hooks_class-performancenodeentry">Class: <code>PerformanceNodeEntry</code></a>
<ul>
<li><a href="#all_perf_hooks_performancenodeentrydetail"><code>performanceNodeEntry.detail</code></a></li>
<li><span class="stability_0"><a href="#all_perf_hooks_performancenodeentryflags"><code>performanceNodeEntry.flags</code></a></span></li>
<li><span class="stability_0"><a href="#all_perf_hooks_performancenodeentrykind"><code>performanceNodeEntry.kind</code></a></span></li>
<li><a href="#all_perf_hooks_garbage-collection-gc-details">Garbage Collection ('gc') Details</a></li>
<li><a href="#all_perf_hooks_http-http-details">HTTP ('http') Details</a></li>
<li><a href="#all_perf_hooks_http2-http2-details">HTTP/2 ('http2') Details</a></li>
<li><a href="#all_perf_hooks_timerify-function-details">Timerify ('function') Details</a></li>
<li><a href="#all_perf_hooks_net-net-details">Net ('net') Details</a></li>
<li><a href="#all_perf_hooks_dns-dns-details">DNS ('dns') Details</a></li>
</ul>
</li>
<li><a href="#all_perf_hooks_class-performancenodetiming">Class: <code>PerformanceNodeTiming</code></a>
<ul>
<li><a href="#all_perf_hooks_performancenodetimingbootstrapcomplete"><code>performanceNodeTiming.bootstrapComplete</code></a></li>
<li><a href="#all_perf_hooks_performancenodetimingenvironment"><code>performanceNodeTiming.environment</code></a></li>
<li><a href="#all_perf_hooks_performancenodetimingidletime"><code>performanceNodeTiming.idleTime</code></a></li>
<li><a href="#all_perf_hooks_performancenodetimingloopexit"><code>performanceNodeTiming.loopExit</code></a></li>
<li><a href="#all_perf_hooks_performancenodetimingloopstart"><code>performanceNodeTiming.loopStart</code></a></li>
<li><a href="#all_perf_hooks_performancenodetimingnodestart"><code>performanceNodeTiming.nodeStart</code></a></li>
<li><a href="#all_perf_hooks_performancenodetiminguvmetricsinfo"><code>performanceNodeTiming.uvMetricsInfo</code></a></li>
<li><a href="#all_perf_hooks_performancenodetimingv8start"><code>performanceNodeTiming.v8Start</code></a></li>
</ul>
</li>
<li><a href="#all_perf_hooks_class-performanceresourcetiming">Class: <code>PerformanceResourceTiming</code></a>
<ul>
<li><a href="#all_perf_hooks_performanceresourcetimingworkerstart"><code>performanceResourceTiming.workerStart</code></a></li>
<li><a href="#all_perf_hooks_performanceresourcetimingredirectstart"><code>performanceResourceTiming.redirectStart</code></a></li>
<li><a href="#all_perf_hooks_performanceresourcetimingredirectend"><code>performanceResourceTiming.redirectEnd</code></a></li>
<li><a href="#all_perf_hooks_performanceresourcetimingfetchstart"><code>performanceResourceTiming.fetchStart</code></a></li>
<li><a href="#all_perf_hooks_performanceresourcetimingdomainlookupstart"><code>performanceResourceTiming.domainLookupStart</code></a></li>
<li><a href="#all_perf_hooks_performanceresourcetimingdomainlookupend"><code>performanceResourceTiming.domainLookupEnd</code></a></li>
<li><a href="#all_perf_hooks_performanceresourcetimingconnectstart"><code>performanceResourceTiming.connectStart</code></a></li>
<li><a href="#all_perf_hooks_performanceresourcetimingconnectend"><code>performanceResourceTiming.connectEnd</code></a></li>
<li><a href="#all_perf_hooks_performanceresourcetimingsecureconnectionstart"><code>performanceResourceTiming.secureConnectionStart</code></a></li>
<li><a href="#all_perf_hooks_performanceresourcetimingrequeststart"><code>performanceResourceTiming.requestStart</code></a></li>
<li><a href="#all_perf_hooks_performanceresourcetimingresponseend"><code>performanceResourceTiming.responseEnd</code></a></li>
<li><a href="#all_perf_hooks_performanceresourcetimingtransfersize"><code>performanceResourceTiming.transferSize</code></a></li>
<li><a href="#all_perf_hooks_performanceresourcetimingencodedbodysize"><code>performanceResourceTiming.encodedBodySize</code></a></li>
<li><a href="#all_perf_hooks_performanceresourcetimingdecodedbodysize"><code>performanceResourceTiming.decodedBodySize</code></a></li>
<li><a href="#all_perf_hooks_performanceresourcetimingtojson"><code>performanceResourceTiming.toJSON()</code></a></li>
</ul>
</li>
<li><a href="#all_perf_hooks_class-performanceobserver">Class: <code>PerformanceObserver</code></a>
<ul>
<li><a href="#all_perf_hooks_performanceobserversupportedentrytypes"><code>PerformanceObserver.supportedEntryTypes</code></a></li>
<li><a href="#all_perf_hooks_new-performanceobservercallback"><code>new PerformanceObserver(callback)</code></a></li>
<li><a href="#all_perf_hooks_performanceobserverdisconnect"><code>performanceObserver.disconnect()</code></a></li>
<li><a href="#all_perf_hooks_performanceobserverobserveoptions"><code>performanceObserver.observe(options)</code></a></li>
</ul>
</li>
<li><a href="#all_perf_hooks_class-performanceobserverentrylist">Class: <code>PerformanceObserverEntryList</code></a>
<ul>
<li><a href="#all_perf_hooks_performanceobserverentrylistgetentries"><code>performanceObserverEntryList.getEntries()</code></a></li>
<li><a href="#all_perf_hooks_performanceobserverentrylistgetentriesbynamename-type"><code>performanceObserverEntryList.getEntriesByName(name[, type])</code></a></li>
<li><a href="#all_perf_hooks_performanceobserverentrylistgetentriesbytypetype"><code>performanceObserverEntryList.getEntriesByType(type)</code></a></li>
</ul>
</li>
<li><a href="#all_perf_hooks_perf_hookscreatehistogramoptions"><code>perf_hooks.createHistogram([options])</code></a></li>
<li><a href="#all_perf_hooks_perf_hooksmonitoreventloopdelayoptions"><code>perf_hooks.monitorEventLoopDelay([options])</code></a></li>
<li><a href="#all_perf_hooks_class-histogram">Class: <code>Histogram</code></a>
<ul>
<li><a href="#all_perf_hooks_histogramcount"><code>histogram.count</code></a></li>
<li><a href="#all_perf_hooks_histogramcountbigint"><code>histogram.countBigInt</code></a></li>
<li><a href="#all_perf_hooks_histogramexceeds"><code>histogram.exceeds</code></a></li>
<li><a href="#all_perf_hooks_histogramexceedsbigint"><code>histogram.exceedsBigInt</code></a></li>
<li><a href="#all_perf_hooks_histogrammax"><code>histogram.max</code></a></li>
<li><a href="#all_perf_hooks_histogrammaxbigint"><code>histogram.maxBigInt</code></a></li>
<li><a href="#all_perf_hooks_histogrammean"><code>histogram.mean</code></a></li>
<li><a href="#all_perf_hooks_histogrammin"><code>histogram.min</code></a></li>
<li><a href="#all_perf_hooks_histogramminbigint"><code>histogram.minBigInt</code></a></li>
<li><a href="#all_perf_hooks_histogrampercentilepercentile"><code>histogram.percentile(percentile)</code></a></li>
<li><a href="#all_perf_hooks_histogrampercentilebigintpercentile"><code>histogram.percentileBigInt(percentile)</code></a></li>
<li><a href="#all_perf_hooks_histogrampercentiles"><code>histogram.percentiles</code></a></li>
<li><a href="#all_perf_hooks_histogrampercentilesbigint"><code>histogram.percentilesBigInt</code></a></li>
<li><a href="#all_perf_hooks_histogramreset"><code>histogram.reset()</code></a></li>
<li><a href="#all_perf_hooks_histogramstddev"><code>histogram.stddev</code></a></li>
</ul>
</li>
<li><a href="#all_perf_hooks_class-intervalhistogram-extends-histogram">Class: <code>IntervalHistogram extends Histogram</code></a>
<ul>
<li><a href="#all_perf_hooks_histogramdisable"><code>histogram.disable()</code></a></li>
<li><a href="#all_perf_hooks_histogramenable"><code>histogram.enable()</code></a></li>
<li><a href="#all_perf_hooks_cloning-an-intervalhistogram">Cloning an <code>IntervalHistogram</code></a></li>
</ul>
</li>
<li><a href="#all_perf_hooks_class-recordablehistogram-extends-histogram">Class: <code>RecordableHistogram extends Histogram</code></a>
<ul>
<li><a href="#all_perf_hooks_histogramaddother"><code>histogram.add(other)</code></a></li>
<li><a href="#all_perf_hooks_histogramrecordval"><code>histogram.record(val)</code></a></li>
<li><a href="#all_perf_hooks_histogramrecorddelta"><code>histogram.recordDelta()</code></a></li>
</ul>
</li>
<li><a href="#all_perf_hooks_examples">Examples</a>
<ul>
<li><a href="#all_perf_hooks_measuring-the-duration-of-async-operations">Measuring the duration of async operations</a></li>
<li><a href="#all_perf_hooks_measuring-how-long-it-takes-to-load-dependencies">Measuring how long it takes to load dependencies</a></li>
<li><a href="#all_perf_hooks_measuring-how-long-one-http-round-trip-takes">Measuring how long one HTTP round-trip takes</a></li>
<li><a href="#all_perf_hooks_measuring-how-long-the-netconnect-only-for-tcp-takes-when-the-connection-is-successful">Measuring how long the <code>net.connect</code> (only for TCP) takes when the connection is successful</a></li>
<li><a href="#all_perf_hooks_measuring-how-long-the-dns-takes-when-the-request-is-successful">Measuring how long the DNS takes when the request is successful</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_permissions_permissions">Permissions</a>
<ul>
<li><a href="#all_permissions_module-based-permissions">Module-based permissions</a>
<ul>
<li><span class="stability_0"><a href="#all_permissions_policies">Policies</a></span>
<ul>
<li><a href="#all_permissions_enabling">Enabling</a></li>
<li><a href="#all_permissions_features">Features</a>
<ul>
<li><a href="#all_permissions_error-behavior">Error behavior</a></li>
<li><a href="#all_permissions_integrity-checks">Integrity checks</a></li>
<li><a href="#all_permissions_dependency-redirection">Dependency redirection</a></li>
<li><a href="#all_permissions_example-patched-dependency">Example: Patched dependency</a></li>
</ul>
</li>
<li><a href="#all_permissions_scopes">Scopes</a>
<ul>
<li><a href="#all_permissions_example">Example</a></li>
<li><a href="#all_permissions_integrity-using-scopes">Integrity using scopes</a></li>
<li><a href="#all_permissions_dependency-redirection-using-scopes">Dependency redirection using scopes</a></li>
<li><a href="#all_permissions_example-import-maps-emulation">Example: import maps emulation</a></li>
</ul>
</li>
<li><a href="#all_permissions_guarantees">Guarantees</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_permissions_process-based-permissions">Process-based permissions</a>
<ul>
<li><span class="stability_1"><a href="#all_permissions_permission-model">Permission Model</a></span>
<ul>
<li><a href="#all_permissions_runtime-api">Runtime API</a>
<ul>
<li><a href="#all_permissions_permissionhasscope-reference"><code>permission.has(scope[, reference])</code></a></li>
</ul>
</li>
<li><a href="#all_permissions_file-system-permissions">File System Permissions</a></li>
<li><a href="#all_permissions_permission-model-constraints">Permission Model constraints</a></li>
<li><a href="#all_permissions_limitations-and-known-issues">Limitations and Known Issues</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_process_process">Process</a>
<ul>
<li><a href="#all_process_process-events">Process events</a>
<ul>
<li><a href="#all_process_event-beforeexit">Event: <code>'beforeExit'</code></a></li>
<li><a href="#all_process_event-disconnect">Event: <code>'disconnect'</code></a></li>
<li><a href="#all_process_event-exit">Event: <code>'exit'</code></a></li>
<li><a href="#all_process_event-message">Event: <code>'message'</code></a></li>
<li><span class="stability_0"><a href="#all_process_event-multipleresolves">Event: <code>'multipleResolves'</code></a></span></li>
<li><a href="#all_process_event-rejectionhandled">Event: <code>'rejectionHandled'</code></a></li>
<li><a href="#all_process_event-uncaughtexception">Event: <code>'uncaughtException'</code></a>
<ul>
<li><a href="#all_process_warning-using-uncaughtexception-correctly">Warning: Using <code>'uncaughtException'</code> correctly</a></li>
</ul>
</li>
<li><a href="#all_process_event-uncaughtexceptionmonitor">Event: <code>'uncaughtExceptionMonitor'</code></a></li>
<li><a href="#all_process_event-unhandledrejection">Event: <code>'unhandledRejection'</code></a></li>
<li><a href="#all_process_event-warning">Event: <code>'warning'</code></a>
<ul>
<li><a href="#all_process_emitting-custom-warnings">Emitting custom warnings</a></li>
<li><a href="#all_process_nodejs-warning-names">Node.js warning names</a></li>
</ul>
</li>
<li><a href="#all_process_event-worker">Event: <code>'worker'</code></a></li>
<li><a href="#all_process_signal-events">Signal events</a></li>
</ul>
</li>
<li><a href="#all_process_processabort"><code>process.abort()</code></a></li>
<li><a href="#all_process_processallowednodeenvironmentflags"><code>process.allowedNodeEnvironmentFlags</code></a></li>
<li><a href="#all_process_processarch"><code>process.arch</code></a></li>
<li><a href="#all_process_processargv"><code>process.argv</code></a></li>
<li><a href="#all_process_processargv0"><code>process.argv0</code></a></li>
<li><a href="#all_process_processchannel"><code>process.channel</code></a>
<ul>
<li><a href="#all_process_processchannelref"><code>process.channel.ref()</code></a></li>
<li><a href="#all_process_processchannelunref"><code>process.channel.unref()</code></a></li>
</ul>
</li>
<li><a href="#all_process_processchdirdirectory"><code>process.chdir(directory)</code></a></li>
<li><a href="#all_process_processconfig"><code>process.config</code></a></li>
<li><a href="#all_process_processconnected"><code>process.connected</code></a></li>
<li><span class="stability_1"><a href="#all_process_processconstrainedmemory"><code>process.constrainedMemory()</code></a></span></li>
<li><span class="stability_1"><a href="#all_process_processavailablememory"><code>process.availableMemory()</code></a></span></li>
<li><a href="#all_process_processcpuusagepreviousvalue"><code>process.cpuUsage([previousValue])</code></a></li>
<li><a href="#all_process_processcwd"><code>process.cwd()</code></a></li>
<li><a href="#all_process_processdebugport"><code>process.debugPort</code></a></li>
<li><a href="#all_process_processdisconnect"><code>process.disconnect()</code></a></li>
<li><a href="#all_process_processdlopenmodule-filename-flags"><code>process.dlopen(module, filename[, flags])</code></a></li>
<li><a href="#all_process_processemitwarningwarning-options"><code>process.emitWarning(warning[, options])</code></a></li>
<li><a href="#all_process_processemitwarningwarning-type-code-ctor"><code>process.emitWarning(warning[, type[, code]][, ctor])</code></a>
<ul>
<li><a href="#all_process_avoiding-duplicate-warnings">Avoiding duplicate warnings</a></li>
</ul>
</li>
<li><a href="#all_process_processenv"><code>process.env</code></a></li>
<li><a href="#all_process_processexecargv"><code>process.execArgv</code></a></li>
<li><a href="#all_process_processexecpath"><code>process.execPath</code></a></li>
<li><a href="#all_process_processexitcode"><code>process.exit([code])</code></a></li>
<li><a href="#all_process_processexitcode_1"><code>process.exitCode</code></a></li>
<li><span class="stability_1"><a href="#all_process_processgetactiveresourcesinfo"><code>process.getActiveResourcesInfo()</code></a></span></li>
<li><a href="#all_process_processgetbuiltinmoduleid"><code>process.getBuiltinModule(id)</code></a></li>
<li><a href="#all_process_processgetegid"><code>process.getegid()</code></a></li>
<li><a href="#all_process_processgeteuid"><code>process.geteuid()</code></a></li>
<li><a href="#all_process_processgetgid"><code>process.getgid()</code></a></li>
<li><a href="#all_process_processgetgroups"><code>process.getgroups()</code></a></li>
<li><a href="#all_process_processgetuid"><code>process.getuid()</code></a></li>
<li><a href="#all_process_processhasuncaughtexceptioncapturecallback"><code>process.hasUncaughtExceptionCaptureCallback()</code></a></li>
<li><span class="stability_3"><a href="#all_process_processhrtimetime"><code>process.hrtime([time])</code></a></span></li>
<li><a href="#all_process_processhrtimebigint"><code>process.hrtime.bigint()</code></a></li>
<li><a href="#all_process_processinitgroupsuser-extragroup"><code>process.initgroups(user, extraGroup)</code></a></li>
<li><a href="#all_process_processkillpid-signal"><code>process.kill(pid[, signal])</code></a></li>
<li><span class="stability_1"><a href="#all_process_processloadenvfilepath"><code>process.loadEnvFile(path)</code></a></span></li>
<li><span class="stability_0"><a href="#all_process_processmainmodule"><code>process.mainModule</code></a></span></li>
<li><a href="#all_process_processmemoryusage"><code>process.memoryUsage()</code></a></li>
<li><a href="#all_process_processmemoryusagerss"><code>process.memoryUsage.rss()</code></a></li>
<li><span class="stability_3"><a href="#all_process_processnexttickcallback-args"><code>process.nextTick(callback[, ...args])</code></a></span>
<ul>
<li><a href="#all_process_when-to-use-queuemicrotask-vs-processnexttick">When to use <code>queueMicrotask()</code> vs. <code>process.nextTick()</code></a></li>
</ul>
</li>
<li><a href="#all_process_processnodeprecation"><code>process.noDeprecation</code></a></li>
<li><a href="#all_process_processpermission"><code>process.permission</code></a>
<ul>
<li><a href="#all_process_processpermissionhasscope-reference"><code>process.permission.has(scope[, reference])</code></a></li>
</ul>
</li>
<li><a href="#all_process_processpid"><code>process.pid</code></a></li>
<li><a href="#all_process_processplatform"><code>process.platform</code></a></li>
<li><a href="#all_process_processppid"><code>process.ppid</code></a></li>
<li><a href="#all_process_processrelease"><code>process.release</code></a></li>
<li><a href="#all_process_processreport"><code>process.report</code></a>
<ul>
<li><a href="#all_process_processreportcompact"><code>process.report.compact</code></a></li>
<li><a href="#all_process_processreportdirectory"><code>process.report.directory</code></a></li>
<li><a href="#all_process_processreportfilename"><code>process.report.filename</code></a></li>
<li><a href="#all_process_processreportgetreporterr"><code>process.report.getReport([err])</code></a></li>
<li><a href="#all_process_processreportreportonfatalerror"><code>process.report.reportOnFatalError</code></a></li>
<li><a href="#all_process_processreportreportonsignal"><code>process.report.reportOnSignal</code></a></li>
<li><a href="#all_process_processreportreportonuncaughtexception"><code>process.report.reportOnUncaughtException</code></a></li>
<li><a href="#all_process_processreportsignal"><code>process.report.signal</code></a></li>
<li><a href="#all_process_processreportwritereportfilename-err"><code>process.report.writeReport([filename][, err])</code></a></li>
</ul>
</li>
<li><a href="#all_process_processresourceusage"><code>process.resourceUsage()</code></a></li>
<li><a href="#all_process_processsendmessage-sendhandle-options-callback"><code>process.send(message[, sendHandle[, options]][, callback])</code></a></li>
<li><a href="#all_process_processsetegidid"><code>process.setegid(id)</code></a></li>
<li><a href="#all_process_processseteuidid"><code>process.seteuid(id)</code></a></li>
<li><a href="#all_process_processsetgidid"><code>process.setgid(id)</code></a></li>
<li><a href="#all_process_processsetgroupsgroups"><code>process.setgroups(groups)</code></a></li>
<li><a href="#all_process_processsetuidid"><code>process.setuid(id)</code></a></li>
<li><span class="stability_1"><a href="#all_process_processsetsourcemapsenabledval"><code>process.setSourceMapsEnabled(val)</code></a></span></li>
<li><a href="#all_process_processsetuncaughtexceptioncapturecallbackfn"><code>process.setUncaughtExceptionCaptureCallback(fn)</code></a></li>
<li><span class="stability_1"><a href="#all_process_processsourcemapsenabled"><code>process.sourceMapsEnabled</code></a></span></li>
<li><a href="#all_process_processstderr"><code>process.stderr</code></a>
<ul>
<li><a href="#all_process_processstderrfd"><code>process.stderr.fd</code></a></li>
</ul>
</li>
<li><a href="#all_process_processstdin"><code>process.stdin</code></a>
<ul>
<li><a href="#all_process_processstdinfd"><code>process.stdin.fd</code></a></li>
</ul>
</li>
<li><a href="#all_process_processstdout"><code>process.stdout</code></a>
<ul>
<li><a href="#all_process_processstdoutfd"><code>process.stdout.fd</code></a></li>
<li><a href="#all_process_a-note-on-process-io">A note on process I/O</a></li>
</ul>
</li>
<li><a href="#all_process_processthrowdeprecation"><code>process.throwDeprecation</code></a></li>
<li><a href="#all_process_processtitle"><code>process.title</code></a></li>
<li><a href="#all_process_processtracedeprecation"><code>process.traceDeprecation</code></a></li>
<li><span class="stability_0"><a href="#all_process_processumask"><code>process.umask()</code></a></span></li>
<li><a href="#all_process_processumaskmask"><code>process.umask(mask)</code></a></li>
<li><a href="#all_process_processuptime"><code>process.uptime()</code></a></li>
<li><a href="#all_process_processversion"><code>process.version</code></a></li>
<li><a href="#all_process_processversions"><code>process.versions</code></a></li>
<li><a href="#all_process_exit-codes">Exit codes</a></li>
</ul>
</li>
<li><span class="stability_0"><a href="#all_punycode_punycode">Punycode</a></span>
<ul>
<li><a href="#all_punycode_punycodedecodestring"><code>punycode.decode(string)</code></a></li>
<li><a href="#all_punycode_punycodeencodestring"><code>punycode.encode(string)</code></a></li>
<li><a href="#all_punycode_punycodetoasciidomain"><code>punycode.toASCII(domain)</code></a></li>
<li><a href="#all_punycode_punycodetounicodedomain"><code>punycode.toUnicode(domain)</code></a></li>
<li><a href="#all_punycode_punycodeucs2"><code>punycode.ucs2</code></a>
<ul>
<li><a href="#all_punycode_punycodeucs2decodestring"><code>punycode.ucs2.decode(string)</code></a></li>
<li><a href="#all_punycode_punycodeucs2encodecodepoints"><code>punycode.ucs2.encode(codePoints)</code></a></li>
</ul>
</li>
<li><a href="#all_punycode_punycodeversion"><code>punycode.version</code></a></li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_querystring_query-string">Query string</a></span>
<ul>
<li><a href="#all_querystring_querystringdecode"><code>querystring.decode()</code></a></li>
<li><a href="#all_querystring_querystringencode"><code>querystring.encode()</code></a></li>
<li><a href="#all_querystring_querystringescapestr"><code>querystring.escape(str)</code></a></li>
<li><a href="#all_querystring_querystringparsestr-sep-eq-options"><code>querystring.parse(str[, sep[, eq[, options]]])</code></a></li>
<li><a href="#all_querystring_querystringstringifyobj-sep-eq-options"><code>querystring.stringify(obj[, sep[, eq[, options]]])</code></a></li>
<li><a href="#all_querystring_querystringunescapestr"><code>querystring.unescape(str)</code></a></li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_readline_readline">Readline</a></span>
<ul>
<li><a href="#all_readline_class-interfaceconstructor">Class: <code>InterfaceConstructor</code></a>
<ul>
<li><a href="#all_readline_event-close">Event: <code>'close'</code></a></li>
<li><a href="#all_readline_event-line">Event: <code>'line'</code></a></li>
<li><a href="#all_readline_event-history">Event: <code>'history'</code></a></li>
<li><a href="#all_readline_event-pause">Event: <code>'pause'</code></a></li>
<li><a href="#all_readline_event-resume">Event: <code>'resume'</code></a></li>
<li><a href="#all_readline_event-sigcont">Event: <code>'SIGCONT'</code></a></li>
<li><a href="#all_readline_event-sigint">Event: <code>'SIGINT'</code></a></li>
<li><a href="#all_readline_event-sigtstp">Event: <code>'SIGTSTP'</code></a></li>
<li><a href="#all_readline_rlclose"><code>rl.close()</code></a></li>
<li><a href="#all_readline_rlpause"><code>rl.pause()</code></a></li>
<li><a href="#all_readline_rlpromptpreservecursor"><code>rl.prompt([preserveCursor])</code></a></li>
<li><a href="#all_readline_rlresume"><code>rl.resume()</code></a></li>
<li><a href="#all_readline_rlsetpromptprompt"><code>rl.setPrompt(prompt)</code></a></li>
<li><a href="#all_readline_rlgetprompt"><code>rl.getPrompt()</code></a></li>
<li><a href="#all_readline_rlwritedata-key"><code>rl.write(data[, key])</code></a></li>
<li><a href="#all_readline_rlsymbolasynciterator"><code>rl[Symbol.asyncIterator]()</code></a></li>
<li><a href="#all_readline_rlline"><code>rl.line</code></a></li>
<li><a href="#all_readline_rlcursor"><code>rl.cursor</code></a></li>
<li><a href="#all_readline_rlgetcursorpos"><code>rl.getCursorPos()</code></a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_readline_promises-api">Promises API</a></span>
<ul>
<li><a href="#all_readline_class-readlinepromisesinterface">Class: <code>readlinePromises.Interface</code></a>
<ul>
<li><a href="#all_readline_rlquestionquery-options"><code>rl.question(query[, options])</code></a></li>
</ul>
</li>
<li><a href="#all_readline_class-readlinepromisesreadline">Class: <code>readlinePromises.Readline</code></a>
<ul>
<li><a href="#all_readline_new-readlinepromisesreadlinestream-options"><code>new readlinePromises.Readline(stream[, options])</code></a></li>
<li><a href="#all_readline_rlclearlinedir"><code>rl.clearLine(dir)</code></a></li>
<li><a href="#all_readline_rlclearscreendown"><code>rl.clearScreenDown()</code></a></li>
<li><a href="#all_readline_rlcommit"><code>rl.commit()</code></a></li>
<li><a href="#all_readline_rlcursortox-y"><code>rl.cursorTo(x[, y])</code></a></li>
<li><a href="#all_readline_rlmovecursordx-dy"><code>rl.moveCursor(dx, dy)</code></a></li>
<li><a href="#all_readline_rlrollback"><code>rl.rollback()</code></a></li>
</ul>
</li>
<li><a href="#all_readline_readlinepromisescreateinterfaceoptions"><code>readlinePromises.createInterface(options)</code></a>
<ul>
<li><a href="#all_readline_use-of-the-completer-function">Use of the <code>completer</code> function</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_readline_callback-api">Callback API</a>
<ul>
<li><a href="#all_readline_class-readlineinterface">Class: <code>readline.Interface</code></a>
<ul>
<li><a href="#all_readline_rlquestionquery-options-callback"><code>rl.question(query[, options], callback)</code></a></li>
</ul>
</li>
<li><a href="#all_readline_readlineclearlinestream-dir-callback"><code>readline.clearLine(stream, dir[, callback])</code></a></li>
<li><a href="#all_readline_readlineclearscreendownstream-callback"><code>readline.clearScreenDown(stream[, callback])</code></a></li>
<li><a href="#all_readline_readlinecreateinterfaceoptions"><code>readline.createInterface(options)</code></a>
<ul>
<li><a href="#all_readline_use-of-the-completer-function_1">Use of the <code>completer</code> function</a></li>
</ul>
</li>
<li><a href="#all_readline_readlinecursortostream-x-y-callback"><code>readline.cursorTo(stream, x[, y][, callback])</code></a></li>
<li><a href="#all_readline_readlinemovecursorstream-dx-dy-callback"><code>readline.moveCursor(stream, dx, dy[, callback])</code></a></li>
</ul>
</li>
<li><a href="#all_readline_readlineemitkeypresseventsstream-interface"><code>readline.emitKeypressEvents(stream[, interface])</code></a></li>
<li><a href="#all_readline_example-tiny-cli">Example: Tiny CLI</a></li>
<li><a href="#all_readline_example-read-file-stream-line-by-line">Example: Read file stream line-by-Line</a></li>
<li><a href="#all_readline_tty-keybindings">TTY keybindings</a></li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_repl_repl">REPL</a></span>
<ul>
<li><a href="#all_repl_design-and-features">Design and features</a>
<ul>
<li><a href="#all_repl_commands-and-special-keys">Commands and special keys</a></li>
<li><a href="#all_repl_default-evaluation">Default evaluation</a>
<ul>
<li><a href="#all_repl_javascript-expressions">JavaScript expressions</a></li>
<li><a href="#all_repl_global-and-local-scope">Global and local scope</a></li>
<li><a href="#all_repl_accessing-core-nodejs-modules">Accessing core Node.js modules</a></li>
<li><a href="#all_repl_global-uncaught-exceptions">Global uncaught exceptions</a></li>
<li><a href="#all_repl_assignment-of-the-_-underscore-variable">Assignment of the <code>_</code> (underscore) variable</a></li>
<li><a href="#all_repl_await-keyword"><code>await</code> keyword</a></li>
</ul>
</li>
<li><a href="#all_repl_reverse-i-search">Reverse-i-search</a></li>
<li><a href="#all_repl_custom-evaluation-functions">Custom evaluation functions</a>
<ul>
<li><a href="#all_repl_recoverable-errors">Recoverable errors</a></li>
</ul>
</li>
<li><a href="#all_repl_customizing-repl-output">Customizing REPL output</a></li>
</ul>
</li>
<li><a href="#all_repl_class-replserver">Class: <code>REPLServer</code></a>
<ul>
<li><a href="#all_repl_event-exit">Event: <code>'exit'</code></a></li>
<li><a href="#all_repl_event-reset">Event: <code>'reset'</code></a></li>
<li><a href="#all_repl_replserverdefinecommandkeyword-cmd"><code>replServer.defineCommand(keyword, cmd)</code></a></li>
<li><a href="#all_repl_replserverdisplaypromptpreservecursor"><code>replServer.displayPrompt([preserveCursor])</code></a></li>
<li><a href="#all_repl_replserverclearbufferedcommand"><code>replServer.clearBufferedCommand()</code></a></li>
<li><span class="stability_0"><a href="#all_repl_replserverparsereplkeywordkeyword-rest"><code>replServer.parseREPLKeyword(keyword[, rest])</code></a></span></li>
<li><a href="#all_repl_replserversetuphistoryhistorypath-callback"><code>replServer.setupHistory(historyPath, callback)</code></a></li>
</ul>
</li>
<li><a href="#all_repl_replbuiltinmodules"><code>repl.builtinModules</code></a></li>
<li><a href="#all_repl_replstartoptions"><code>repl.start([options])</code></a></li>
<li><a href="#all_repl_the-nodejs-repl">The Node.js REPL</a>
<ul>
<li><a href="#all_repl_environment-variable-options">Environment variable options</a></li>
<li><a href="#all_repl_persistent-history">Persistent history</a></li>
<li><a href="#all_repl_using-the-nodejs-repl-with-advanced-line-editors">Using the Node.js REPL with advanced line-editors</a></li>
<li><a href="#all_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><span class="stability_2"><a href="#all_report_diagnostic-report">Diagnostic report</a></span>
<ul>
<li><a href="#all_report_usage">Usage</a></li>
<li><a href="#all_report_configuration">Configuration</a></li>
<li><a href="#all_report_interaction-with-workers">Interaction with workers</a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_single-executable-applications_single-executable-applications">Single executable applications</a></span>
<ul>
<li><a href="#all_single-executable-applications_generating-single-executable-preparation-blobs">Generating single executable preparation blobs</a>
<ul>
<li><a href="#all_single-executable-applications_assets">Assets</a></li>
<li><a href="#all_single-executable-applications_startup-snapshot-support">Startup snapshot support</a></li>
<li><a href="#all_single-executable-applications_v8-code-cache-support">V8 code cache support</a></li>
</ul>
</li>
<li><a href="#all_single-executable-applications_in-the-injected-main-script">In the injected main script</a>
<ul>
<li><a href="#all_single-executable-applications_single-executable-application-api">Single-executable application API</a>
<ul>
<li><a href="#all_single-executable-applications_seaissea"><code>sea.isSea()</code></a></li>
</ul>
</li>
<li><a href="#all_single-executable-applications_seagetassetkey-encoding"><code>sea.getAsset(key[, encoding])</code></a></li>
<li><a href="#all_single-executable-applications_seagetassetasblobkey-options"><code>sea.getAssetAsBlob(key[, options])</code></a></li>
<li><a href="#all_single-executable-applications_seagetrawassetkey"><code>sea.getRawAsset(key)</code></a></li>
<li><a href="#all_single-executable-applications_requireid-in-the-injected-main-script-is-not-file-based"><code>require(id)</code> in the injected main script is not file based</a></li>
<li><a href="#all_single-executable-applications___filename-and-modulefilename-in-the-injected-main-script"><code>__filename</code> and <code>module.filename</code> in the injected main script</a></li>
<li><a href="#all_single-executable-applications___dirname-in-the-injected-main-script"><code>__dirname</code> in the injected main script</a></li>
</ul>
</li>
<li><a href="#all_single-executable-applications_notes">Notes</a>
<ul>
<li><a href="#all_single-executable-applications_single-executable-application-creation-process">Single executable application creation process</a></li>
<li><a href="#all_single-executable-applications_platform-support">Platform support</a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_stream_stream">Stream</a></span>
<ul>
<li><a href="#all_stream_organization-of-this-document">Organization of this document</a></li>
<li><a href="#all_stream_types-of-streams">Types of streams</a>
<ul>
<li><a href="#all_stream_streams-promises-api">Streams Promises API</a></li>
<li><a href="#all_stream_streampipelinesource-transforms-destination-options"><code>stream.pipeline(source[, ...transforms], destination[, options])</code></a></li>
<li><a href="#all_stream_streampipelinestreams-options"><code>stream.pipeline(streams[, options])</code></a></li>
<li><a href="#all_stream_streamfinishedstream-options"><code>stream.finished(stream[, options])</code></a></li>
<li><a href="#all_stream_object-mode">Object mode</a></li>
<li><a href="#all_stream_buffering">Buffering</a></li>
</ul>
</li>
<li><a href="#all_stream_api-for-stream-consumers">API for stream consumers</a>
<ul>
<li><a href="#all_stream_writable-streams">Writable streams</a>
<ul>
<li><a href="#all_stream_class-streamwritable">Class: <code>stream.Writable</code></a>
<ul>
<li><a href="#all_stream_event-close">Event: <code>'close'</code></a></li>
<li><a href="#all_stream_event-drain">Event: <code>'drain'</code></a></li>
<li><a href="#all_stream_event-error">Event: <code>'error'</code></a></li>
<li><a href="#all_stream_event-finish">Event: <code>'finish'</code></a></li>
<li><a href="#all_stream_event-pipe">Event: <code>'pipe'</code></a></li>
<li><a href="#all_stream_event-unpipe">Event: <code>'unpipe'</code></a></li>
<li><a href="#all_stream_writablecork"><code>writable.cork()</code></a></li>
<li><a href="#all_stream_writabledestroyerror"><code>writable.destroy([error])</code></a></li>
<li><a href="#all_stream_writableclosed"><code>writable.closed</code></a></li>
<li><a href="#all_stream_writabledestroyed"><code>writable.destroyed</code></a></li>
<li><a href="#all_stream_writableendchunk-encoding-callback"><code>writable.end([chunk[, encoding]][, callback])</code></a></li>
<li><a href="#all_stream_writablesetdefaultencodingencoding"><code>writable.setDefaultEncoding(encoding)</code></a></li>
<li><a href="#all_stream_writableuncork"><code>writable.uncork()</code></a></li>
<li><a href="#all_stream_writablewritable"><code>writable.writable</code></a></li>
<li><span class="stability_1"><a href="#all_stream_writablewritableaborted"><code>writable.writableAborted</code></a></span></li>
<li><a href="#all_stream_writablewritableended"><code>writable.writableEnded</code></a></li>
<li><a href="#all_stream_writablewritablecorked"><code>writable.writableCorked</code></a></li>
<li><a href="#all_stream_writableerrored"><code>writable.errored</code></a></li>
<li><a href="#all_stream_writablewritablefinished"><code>writable.writableFinished</code></a></li>
<li><a href="#all_stream_writablewritablehighwatermark"><code>writable.writableHighWaterMark</code></a></li>
<li><a href="#all_stream_writablewritablelength"><code>writable.writableLength</code></a></li>
<li><a href="#all_stream_writablewritableneeddrain"><code>writable.writableNeedDrain</code></a></li>
<li><a href="#all_stream_writablewritableobjectmode"><code>writable.writableObjectMode</code></a></li>
<li><span class="stability_1"><a href="#all_stream_writablesymbolasyncdispose"><code>writable[Symbol.asyncDispose]()</code></a></span></li>
<li><a href="#all_stream_writablewritechunk-encoding-callback"><code>writable.write(chunk[, encoding][, callback])</code></a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_stream_readable-streams">Readable streams</a>
<ul>
<li><a href="#all_stream_two-reading-modes">Two reading modes</a></li>
<li><a href="#all_stream_three-states">Three states</a></li>
<li><a href="#all_stream_choose-one-api-style">Choose one API style</a></li>
<li><a href="#all_stream_class-streamreadable">Class: <code>stream.Readable</code></a>
<ul>
<li><a href="#all_stream_event-close_1">Event: <code>'close'</code></a></li>
<li><a href="#all_stream_event-data">Event: <code>'data'</code></a></li>
<li><a href="#all_stream_event-end">Event: <code>'end'</code></a></li>
<li><a href="#all_stream_event-error_1">Event: <code>'error'</code></a></li>
<li><a href="#all_stream_event-pause">Event: <code>'pause'</code></a></li>
<li><a href="#all_stream_event-readable">Event: <code>'readable'</code></a></li>
<li><a href="#all_stream_event-resume">Event: <code>'resume'</code></a></li>
<li><a href="#all_stream_readabledestroyerror"><code>readable.destroy([error])</code></a></li>
<li><a href="#all_stream_readableclosed"><code>readable.closed</code></a></li>
<li><a href="#all_stream_readabledestroyed"><code>readable.destroyed</code></a></li>
<li><a href="#all_stream_readableispaused"><code>readable.isPaused()</code></a></li>
<li><a href="#all_stream_readablepause"><code>readable.pause()</code></a></li>
<li><a href="#all_stream_readablepipedestination-options"><code>readable.pipe(destination[, options])</code></a></li>
<li><a href="#all_stream_readablereadsize"><code>readable.read([size])</code></a></li>
<li><a href="#all_stream_readablereadable"><code>readable.readable</code></a></li>
<li><span class="stability_1"><a href="#all_stream_readablereadableaborted"><code>readable.readableAborted</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_readablereadabledidread"><code>readable.readableDidRead</code></a></span></li>
<li><a href="#all_stream_readablereadableencoding"><code>readable.readableEncoding</code></a></li>
<li><a href="#all_stream_readablereadableended"><code>readable.readableEnded</code></a></li>
<li><a href="#all_stream_readableerrored"><code>readable.errored</code></a></li>
<li><a href="#all_stream_readablereadableflowing"><code>readable.readableFlowing</code></a></li>
<li><a href="#all_stream_readablereadablehighwatermark"><code>readable.readableHighWaterMark</code></a></li>
<li><a href="#all_stream_readablereadablelength"><code>readable.readableLength</code></a></li>
<li><a href="#all_stream_readablereadableobjectmode"><code>readable.readableObjectMode</code></a></li>
<li><a href="#all_stream_readableresume"><code>readable.resume()</code></a></li>
<li><a href="#all_stream_readablesetencodingencoding"><code>readable.setEncoding(encoding)</code></a></li>
<li><a href="#all_stream_readableunpipedestination"><code>readable.unpipe([destination])</code></a></li>
<li><a href="#all_stream_readableunshiftchunk-encoding"><code>readable.unshift(chunk[, encoding])</code></a></li>
<li><a href="#all_stream_readablewrapstream"><code>readable.wrap(stream)</code></a></li>
<li><a href="#all_stream_readablesymbolasynciterator"><code>readable[Symbol.asyncIterator]()</code></a></li>
<li><span class="stability_1"><a href="#all_stream_readablesymbolasyncdispose"><code>readable[Symbol.asyncDispose]()</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_readablecomposestream-options"><code>readable.compose(stream[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_readableiteratoroptions"><code>readable.iterator([options])</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_readablemapfn-options"><code>readable.map(fn[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_readablefilterfn-options"><code>readable.filter(fn[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_readableforeachfn-options"><code>readable.forEach(fn[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_readabletoarrayoptions"><code>readable.toArray([options])</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_readablesomefn-options"><code>readable.some(fn[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_readablefindfn-options"><code>readable.find(fn[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_readableeveryfn-options"><code>readable.every(fn[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_readableflatmapfn-options"><code>readable.flatMap(fn[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_readabledroplimit-options"><code>readable.drop(limit[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_readabletakelimit-options"><code>readable.take(limit[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_readableasindexedpairsoptions"><code>readable.asIndexedPairs([options])</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_readablereducefn-initial-options"><code>readable.reduce(fn[, initial[, options]])</code></a></span></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_stream_duplex-and-transform-streams">Duplex and transform streams</a>
<ul>
<li><a href="#all_stream_class-streamduplex">Class: <code>stream.Duplex</code></a>
<ul>
<li><a href="#all_stream_duplexallowhalfopen"><code>duplex.allowHalfOpen</code></a></li>
</ul>
</li>
<li><a href="#all_stream_class-streamtransform">Class: <code>stream.Transform</code></a>
<ul>
<li><a href="#all_stream_transformdestroyerror"><code>transform.destroy([error])</code></a></li>
</ul>
</li>
<li><a href="#all_stream_streamduplexpairoptions"><code>stream.duplexPair([options])</code></a></li>
</ul>
</li>
<li><a href="#all_stream_streamfinishedstream-options-callback"><code>stream.finished(stream[, options], callback)</code></a></li>
<li><a href="#all_stream_streampipelinesource-transforms-destination-callback"><code>stream.pipeline(source[, ...transforms], destination, callback)</code></a></li>
<li><a href="#all_stream_streampipelinestreams-callback"><code>stream.pipeline(streams, callback)</code></a></li>
<li><span class="stability_1"><a href="#all_stream_streamcomposestreams"><code>stream.compose(...streams)</code></a></span></li>
<li><a href="#all_stream_streamreadablefromiterable-options"><code>stream.Readable.from(iterable[, options])</code></a></li>
<li><span class="stability_1"><a href="#all_stream_streamreadablefromwebreadablestream-options"><code>stream.Readable.fromWeb(readableStream[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_streamreadableisdisturbedstream"><code>stream.Readable.isDisturbed(stream)</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_streamiserroredstream"><code>stream.isErrored(stream)</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_streamisreadablestream"><code>stream.isReadable(stream)</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_streamreadabletowebstreamreadable-options"><code>stream.Readable.toWeb(streamReadable[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_streamwritablefromwebwritablestream-options"><code>stream.Writable.fromWeb(writableStream[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_streamwritabletowebstreamwritable"><code>stream.Writable.toWeb(streamWritable)</code></a></span></li>
<li><a href="#all_stream_streamduplexfromsrc"><code>stream.Duplex.from(src)</code></a></li>
<li><span class="stability_1"><a href="#all_stream_streamduplexfromwebpair-options"><code>stream.Duplex.fromWeb(pair[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#all_stream_streamduplextowebstreamduplex"><code>stream.Duplex.toWeb(streamDuplex)</code></a></span></li>
<li><a href="#all_stream_streamaddabortsignalsignal-stream"><code>stream.addAbortSignal(signal, stream)</code></a></li>
<li><a href="#all_stream_streamgetdefaulthighwatermarkobjectmode"><code>stream.getDefaultHighWaterMark(objectMode)</code></a></li>
<li><a href="#all_stream_streamsetdefaulthighwatermarkobjectmode-value"><code>stream.setDefaultHighWaterMark(objectMode, value)</code></a></li>
</ul>
</li>
<li><a href="#all_stream_api-for-stream-implementers">API for stream implementers</a>
<ul>
<li><a href="#all_stream_simplified-construction">Simplified construction</a></li>
<li><a href="#all_stream_implementing-a-writable-stream">Implementing a writable stream</a>
<ul>
<li><a href="#all_stream_new-streamwritableoptions"><code>new stream.Writable([options])</code></a></li>
<li><a href="#all_stream_writable_constructcallback"><code>writable._construct(callback)</code></a></li>
<li><a href="#all_stream_writable_writechunk-encoding-callback"><code>writable._write(chunk, encoding, callback)</code></a></li>
<li><a href="#all_stream_writable_writevchunks-callback"><code>writable._writev(chunks, callback)</code></a></li>
<li><a href="#all_stream_writable_destroyerr-callback"><code>writable._destroy(err, callback)</code></a></li>
<li><a href="#all_stream_writable_finalcallback"><code>writable._final(callback)</code></a></li>
<li><a href="#all_stream_errors-while-writing">Errors while writing</a></li>
<li><a href="#all_stream_an-example-writable-stream">An example writable stream</a></li>
<li><a href="#all_stream_decoding-buffers-in-a-writable-stream">Decoding buffers in a writable stream</a></li>
</ul>
</li>
<li><a href="#all_stream_implementing-a-readable-stream">Implementing a readable stream</a>
<ul>
<li><a href="#all_stream_new-streamreadableoptions"><code>new stream.Readable([options])</code></a></li>
<li><a href="#all_stream_readable_constructcallback"><code>readable._construct(callback)</code></a></li>
<li><a href="#all_stream_readable_readsize"><code>readable._read(size)</code></a></li>
<li><a href="#all_stream_readable_destroyerr-callback"><code>readable._destroy(err, callback)</code></a></li>
<li><a href="#all_stream_readablepushchunk-encoding"><code>readable.push(chunk[, encoding])</code></a></li>
<li><a href="#all_stream_errors-while-reading">Errors while reading</a></li>
<li><a href="#all_stream_an-example-counting-stream">An example counting stream</a></li>
</ul>
</li>
<li><a href="#all_stream_implementing-a-duplex-stream">Implementing a duplex stream</a>
<ul>
<li><a href="#all_stream_new-streamduplexoptions"><code>new stream.Duplex(options)</code></a></li>
<li><a href="#all_stream_an-example-duplex-stream">An example duplex stream</a></li>
<li><a href="#all_stream_object-mode-duplex-streams">Object mode duplex streams</a></li>
</ul>
</li>
<li><a href="#all_stream_implementing-a-transform-stream">Implementing a transform stream</a>
<ul>
<li><a href="#all_stream_new-streamtransformoptions"><code>new stream.Transform([options])</code></a></li>
<li><a href="#all_stream_event-end_1">Event: <code>'end'</code></a></li>
<li><a href="#all_stream_event-finish_1">Event: <code>'finish'</code></a></li>
<li><a href="#all_stream_transform_flushcallback"><code>transform._flush(callback)</code></a></li>
<li><a href="#all_stream_transform_transformchunk-encoding-callback"><code>transform._transform(chunk, encoding, callback)</code></a></li>
<li><a href="#all_stream_class-streampassthrough">Class: <code>stream.PassThrough</code></a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_stream_additional-notes">Additional notes</a>
<ul>
<li><a href="#all_stream_streams-compatibility-with-async-generators-and-async-iterators">Streams compatibility with async generators and async iterators</a>
<ul>
<li><a href="#all_stream_consuming-readable-streams-with-async-iterators">Consuming readable streams with async iterators</a></li>
<li><a href="#all_stream_creating-readable-streams-with-async-generators">Creating readable streams with async generators</a></li>
<li><a href="#all_stream_piping-to-writable-streams-from-async-iterators">Piping to writable streams from async iterators</a></li>
</ul>
</li>
<li><a href="#all_stream_compatibility-with-older-nodejs-versions">Compatibility with older Node.js versions</a></li>
<li><a href="#all_stream_readableread0"><code>readable.read(0)</code></a></li>
<li><a href="#all_stream_readablepush"><code>readable.push('')</code></a></li>
<li><a href="#all_stream_highwatermark-discrepancy-after-calling-readablesetencoding"><code>highWaterMark</code> discrepancy after calling <code>readable.setEncoding()</code></a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_string_decoder_string-decoder">String decoder</a></span>
<ul>
<li><a href="#all_string_decoder_class-stringdecoder">Class: <code>StringDecoder</code></a>
<ul>
<li><a href="#all_string_decoder_new-stringdecoderencoding"><code>new StringDecoder([encoding])</code></a></li>
<li><a href="#all_string_decoder_stringdecoderendbuffer"><code>stringDecoder.end([buffer])</code></a></li>
<li><a href="#all_string_decoder_stringdecoderwritebuffer"><code>stringDecoder.write(buffer)</code></a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_test_test-runner">Test runner</a></span>
<ul>
<li><a href="#all_test_subtests">Subtests</a></li>
<li><a href="#all_test_skipping-tests">Skipping tests</a></li>
<li><a href="#all_test_todo-tests">TODO tests</a></li>
<li><a href="#all_test_describe-and-it-aliases"><code>describe()</code> and <code>it()</code> aliases</a></li>
<li><a href="#all_test_only-tests"><code>only</code> tests</a></li>
<li><a href="#all_test_filtering-tests-by-name">Filtering tests by name</a></li>
<li><a href="#all_test_extraneous-asynchronous-activity">Extraneous asynchronous activity</a></li>
<li><span class="stability_1"><a href="#all_test_watch-mode">Watch mode</a></span></li>
<li><a href="#all_test_running-tests-from-the-command-line">Running tests from the command line</a>
<ul>
<li><a href="#all_test_test-runner-execution-model">Test runner execution model</a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_test_collecting-code-coverage">Collecting code coverage</a></span>
<ul>
<li><a href="#all_test_coverage-reporters">Coverage reporters</a></li>
<li><a href="#all_test_limitations">Limitations</a></li>
</ul>
</li>
<li><a href="#all_test_mocking">Mocking</a>
<ul>
<li><a href="#all_test_timers">Timers</a></li>
<li><a href="#all_test_dates">Dates</a></li>
</ul>
</li>
<li><a href="#all_test_test-reporters">Test reporters</a>
<ul>
<li><a href="#all_test_custom-reporters">Custom reporters</a></li>
<li><a href="#all_test_multiple-reporters">Multiple reporters</a></li>
</ul>
</li>
<li><a href="#all_test_runoptions"><code>run([options])</code></a></li>
<li><a href="#all_test_suitename-options-fn"><code>suite([name][, options][, fn])</code></a></li>
<li><a href="#all_test_suiteskipname-options-fn"><code>suite.skip([name][, options][, fn])</code></a></li>
<li><a href="#all_test_suitetodoname-options-fn"><code>suite.todo([name][, options][, fn])</code></a></li>
<li><a href="#all_test_suiteonlyname-options-fn"><code>suite.only([name][, options][, fn])</code></a></li>
<li><a href="#all_test_testname-options-fn"><code>test([name][, options][, fn])</code></a></li>
<li><a href="#all_test_testskipname-options-fn"><code>test.skip([name][, options][, fn])</code></a></li>
<li><a href="#all_test_testtodoname-options-fn"><code>test.todo([name][, options][, fn])</code></a></li>
<li><a href="#all_test_testonlyname-options-fn"><code>test.only([name][, options][, fn])</code></a></li>
<li><a href="#all_test_describename-options-fn"><code>describe([name][, options][, fn])</code></a></li>
<li><a href="#all_test_describeskipname-options-fn"><code>describe.skip([name][, options][, fn])</code></a></li>
<li><a href="#all_test_describetodoname-options-fn"><code>describe.todo([name][, options][, fn])</code></a></li>
<li><a href="#all_test_describeonlyname-options-fn"><code>describe.only([name][, options][, fn])</code></a></li>
<li><a href="#all_test_itname-options-fn"><code>it([name][, options][, fn])</code></a></li>
<li><a href="#all_test_itskipname-options-fn"><code>it.skip([name][, options][, fn])</code></a></li>
<li><a href="#all_test_ittodoname-options-fn"><code>it.todo([name][, options][, fn])</code></a></li>
<li><a href="#all_test_itonlyname-options-fn"><code>it.only([name][, options][, fn])</code></a></li>
<li><a href="#all_test_beforefn-options"><code>before([fn][, options])</code></a></li>
<li><a href="#all_test_afterfn-options"><code>after([fn][, options])</code></a></li>
<li><a href="#all_test_beforeeachfn-options"><code>beforeEach([fn][, options])</code></a></li>
<li><a href="#all_test_aftereachfn-options"><code>afterEach([fn][, options])</code></a></li>
<li><a href="#all_test_class-mockfunctioncontext">Class: <code>MockFunctionContext</code></a>
<ul>
<li><a href="#all_test_ctxcalls"><code>ctx.calls</code></a></li>
<li><a href="#all_test_ctxcallcount"><code>ctx.callCount()</code></a></li>
<li><a href="#all_test_ctxmockimplementationimplementation"><code>ctx.mockImplementation(implementation)</code></a></li>
<li><a href="#all_test_ctxmockimplementationonceimplementation-oncall"><code>ctx.mockImplementationOnce(implementation[, onCall])</code></a></li>
<li><a href="#all_test_ctxresetcalls"><code>ctx.resetCalls()</code></a></li>
<li><a href="#all_test_ctxrestore"><code>ctx.restore()</code></a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_test_class-mockmodulecontext">Class: <code>MockModuleContext</code></a></span>
<ul>
<li><a href="#all_test_ctxrestore_1"><code>ctx.restore()</code></a></li>
</ul>
</li>
<li><a href="#all_test_class-mocktracker">Class: <code>MockTracker</code></a>
<ul>
<li><a href="#all_test_mockfnoriginal-implementation-options"><code>mock.fn([original[, implementation]][, options])</code></a></li>
<li><a href="#all_test_mockgetterobject-methodname-implementation-options"><code>mock.getter(object, methodName[, implementation][, options])</code></a></li>
<li><a href="#all_test_mockmethodobject-methodname-implementation-options"><code>mock.method(object, methodName[, implementation][, options])</code></a></li>
<li><span class="stability_1"><a href="#all_test_mockmodulespecifier-options"><code>mock.module(specifier[, options])</code></a></span></li>
<li><a href="#all_test_mockreset"><code>mock.reset()</code></a></li>
<li><a href="#all_test_mockrestoreall"><code>mock.restoreAll()</code></a></li>
<li><a href="#all_test_mocksetterobject-methodname-implementation-options"><code>mock.setter(object, methodName[, implementation][, options])</code></a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_test_class-mocktimers">Class: <code>MockTimers</code></a></span>
<ul>
<li><a href="#all_test_timersenableenableoptions"><code>timers.enable([enableOptions])</code></a></li>
<li><a href="#all_test_timersreset"><code>timers.reset()</code></a></li>
<li><a href="#all_test_timerssymboldispose"><code>timers[Symbol.dispose]()</code></a></li>
<li><a href="#all_test_timerstickmilliseconds"><code>timers.tick([milliseconds])</code></a>
<ul>
<li><a href="#all_test_using-clear-functions">Using clear functions</a></li>
<li><a href="#all_test_working-with-nodejs-timers-modules">Working with Node.js timers modules</a></li>
</ul>
</li>
<li><a href="#all_test_timersrunall"><code>timers.runAll()</code></a></li>
<li><a href="#all_test_timerssettimemilliseconds"><code>timers.setTime(milliseconds)</code></a>
<ul>
<li><a href="#all_test_dates-and-timers-working-together">Dates and Timers working together</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_test_class-testsstream">Class: <code>TestsStream</code></a>
<ul>
<li><a href="#all_test_event-testcoverage">Event: <code>'test:coverage'</code></a></li>
<li><a href="#all_test_event-testcomplete">Event: <code>'test:complete'</code></a></li>
<li><a href="#all_test_event-testdequeue">Event: <code>'test:dequeue'</code></a></li>
<li><a href="#all_test_event-testdiagnostic">Event: <code>'test:diagnostic'</code></a></li>
<li><a href="#all_test_event-testenqueue">Event: <code>'test:enqueue'</code></a></li>
<li><a href="#all_test_event-testfail">Event: <code>'test:fail'</code></a></li>
<li><a href="#all_test_event-testpass">Event: <code>'test:pass'</code></a></li>
<li><a href="#all_test_event-testplan">Event: <code>'test:plan'</code></a></li>
<li><a href="#all_test_event-teststart">Event: <code>'test:start'</code></a></li>
<li><a href="#all_test_event-teststderr">Event: <code>'test:stderr'</code></a></li>
<li><a href="#all_test_event-teststdout">Event: <code>'test:stdout'</code></a></li>
<li><a href="#all_test_event-testwatchdrained">Event: <code>'test:watch:drained'</code></a></li>
</ul>
</li>
<li><a href="#all_test_class-testcontext">Class: <code>TestContext</code></a>
<ul>
<li><a href="#all_test_contextbeforefn-options"><code>context.before([fn][, options])</code></a></li>
<li><a href="#all_test_contextbeforeeachfn-options"><code>context.beforeEach([fn][, options])</code></a></li>
<li><a href="#all_test_contextafterfn-options"><code>context.after([fn][, options])</code></a></li>
<li><a href="#all_test_contextaftereachfn-options"><code>context.afterEach([fn][, options])</code></a></li>
<li><a href="#all_test_contextassert"><code>context.assert</code></a></li>
<li><a href="#all_test_contextdiagnosticmessage"><code>context.diagnostic(message)</code></a></li>
<li><a href="#all_test_contextfullname"><code>context.fullName</code></a></li>
<li><a href="#all_test_contextname"><code>context.name</code></a></li>
<li><span class="stability_1"><a href="#all_test_contextplancount"><code>context.plan(count)</code></a></span></li>
<li><a href="#all_test_contextrunonlyshouldrunonlytests"><code>context.runOnly(shouldRunOnlyTests)</code></a></li>
<li><a href="#all_test_contextsignal"><code>context.signal</code></a></li>
<li><a href="#all_test_contextskipmessage"><code>context.skip([message])</code></a></li>
<li><a href="#all_test_contexttodomessage"><code>context.todo([message])</code></a></li>
<li><a href="#all_test_contexttestname-options-fn"><code>context.test([name][, options][, fn])</code></a></li>
</ul>
</li>
<li><a href="#all_test_class-suitecontext">Class: <code>SuiteContext</code></a>
<ul>
<li><a href="#all_test_contextname_1"><code>context.name</code></a></li>
<li><a href="#all_test_contextsignal_1"><code>context.signal</code></a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_timers_timers">Timers</a></span>
<ul>
<li><a href="#all_timers_class-immediate">Class: <code>Immediate</code></a>
<ul>
<li><a href="#all_timers_immediatehasref"><code>immediate.hasRef()</code></a></li>
<li><a href="#all_timers_immediateref"><code>immediate.ref()</code></a></li>
<li><a href="#all_timers_immediateunref"><code>immediate.unref()</code></a></li>
<li><span class="stability_1"><a href="#all_timers_immediatesymboldispose"><code>immediate[Symbol.dispose]()</code></a></span></li>
</ul>
</li>
<li><a href="#all_timers_class-timeout">Class: <code>Timeout</code></a>
<ul>
<li><span class="stability_3"><a href="#all_timers_timeoutclose"><code>timeout.close()</code></a></span></li>
<li><a href="#all_timers_timeouthasref"><code>timeout.hasRef()</code></a></li>
<li><a href="#all_timers_timeoutref"><code>timeout.ref()</code></a></li>
<li><a href="#all_timers_timeoutrefresh"><code>timeout.refresh()</code></a></li>
<li><a href="#all_timers_timeoutunref"><code>timeout.unref()</code></a></li>
<li><a href="#all_timers_timeoutsymboltoprimitive"><code>timeout[Symbol.toPrimitive]()</code></a></li>
<li><span class="stability_1"><a href="#all_timers_timeoutsymboldispose"><code>timeout[Symbol.dispose]()</code></a></span></li>
</ul>
</li>
<li><a href="#all_timers_scheduling-timers">Scheduling timers</a>
<ul>
<li><a href="#all_timers_setimmediatecallback-args"><code>setImmediate(callback[, ...args])</code></a></li>
<li><a href="#all_timers_setintervalcallback-delay-args"><code>setInterval(callback[, delay[, ...args]])</code></a></li>
<li><a href="#all_timers_settimeoutcallback-delay-args"><code>setTimeout(callback[, delay[, ...args]])</code></a></li>
</ul>
</li>
<li><a href="#all_timers_cancelling-timers">Cancelling timers</a>
<ul>
<li><a href="#all_timers_clearimmediateimmediate"><code>clearImmediate(immediate)</code></a></li>
<li><a href="#all_timers_clearintervaltimeout"><code>clearInterval(timeout)</code></a></li>
<li><a href="#all_timers_cleartimeouttimeout"><code>clearTimeout(timeout)</code></a></li>
</ul>
</li>
<li><a href="#all_timers_timers-promises-api">Timers Promises API</a>
<ul>
<li><a href="#all_timers_timerspromisessettimeoutdelay-value-options"><code>timersPromises.setTimeout([delay[, value[, options]]])</code></a></li>
<li><a href="#all_timers_timerspromisessetimmediatevalue-options"><code>timersPromises.setImmediate([value[, options]])</code></a></li>
<li><a href="#all_timers_timerspromisessetintervaldelay-value-options"><code>timersPromises.setInterval([delay[, value[, options]]])</code></a></li>
<li><span class="stability_1"><a href="#all_timers_timerspromisesschedulerwaitdelay-options"><code>timersPromises.scheduler.wait(delay[, options])</code></a></span></li>
<li><span class="stability_1"><a href="#all_timers_timerspromisesscheduleryield"><code>timersPromises.scheduler.yield()</code></a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_tls_tls-ssl">TLS (SSL)</a></span>
<ul>
<li><a href="#all_tls_determining-if-crypto-support-is-unavailable">Determining if crypto support is unavailable</a></li>
<li><a href="#all_tls_tlsssl-concepts">TLS/SSL concepts</a>
<ul>
<li><a href="#all_tls_perfect-forward-secrecy">Perfect forward secrecy</a></li>
<li><a href="#all_tls_alpn-and-sni">ALPN and SNI</a></li>
<li><a href="#all_tls_pre-shared-keys">Pre-shared keys</a></li>
<li><a href="#all_tls_client-initiated-renegotiation-attack-mitigation">Client-initiated renegotiation attack mitigation</a></li>
<li><a href="#all_tls_session-resumption">Session resumption</a>
<ul>
<li><a href="#all_tls_session-identifiers">Session identifiers</a></li>
<li><a href="#all_tls_session-tickets">Session tickets</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_tls_modifying-the-default-tls-cipher-suite">Modifying the default TLS cipher suite</a></li>
<li><a href="#all_tls_x509-certificate-error-codes">X509 certificate error codes</a></li>
<li><span class="stability_0"><a href="#all_tls_class-tlscryptostream">Class: <code>tls.CryptoStream</code></a></span>
<ul>
<li><a href="#all_tls_cryptostreambyteswritten"><code>cryptoStream.bytesWritten</code></a></li>
</ul>
</li>
<li><span class="stability_0"><a href="#all_tls_class-tlssecurepair">Class: <code>tls.SecurePair</code></a></span>
<ul>
<li><a href="#all_tls_event-secure">Event: <code>'secure'</code></a></li>
</ul>
</li>
<li><a href="#all_tls_class-tlsserver">Class: <code>tls.Server</code></a>
<ul>
<li><a href="#all_tls_event-connection">Event: <code>'connection'</code></a></li>
<li><a href="#all_tls_event-keylog">Event: <code>'keylog'</code></a></li>
<li><a href="#all_tls_event-newsession">Event: <code>'newSession'</code></a></li>
<li><a href="#all_tls_event-ocsprequest">Event: <code>'OCSPRequest'</code></a></li>
<li><a href="#all_tls_event-resumesession">Event: <code>'resumeSession'</code></a></li>
<li><a href="#all_tls_event-secureconnection">Event: <code>'secureConnection'</code></a></li>
<li><a href="#all_tls_event-tlsclienterror">Event: <code>'tlsClientError'</code></a></li>
<li><a href="#all_tls_serveraddcontexthostname-context"><code>server.addContext(hostname, context)</code></a></li>
<li><a href="#all_tls_serveraddress"><code>server.address()</code></a></li>
<li><a href="#all_tls_serverclosecallback"><code>server.close([callback])</code></a></li>
<li><a href="#all_tls_servergetticketkeys"><code>server.getTicketKeys()</code></a></li>
<li><a href="#all_tls_serverlisten"><code>server.listen()</code></a></li>
<li><a href="#all_tls_serversetsecurecontextoptions"><code>server.setSecureContext(options)</code></a></li>
<li><a href="#all_tls_serversetticketkeyskeys"><code>server.setTicketKeys(keys)</code></a></li>
</ul>
</li>
<li><a href="#all_tls_class-tlstlssocket">Class: <code>tls.TLSSocket</code></a>
<ul>
<li><a href="#all_tls_new-tlstlssocketsocket-options"><code>new tls.TLSSocket(socket[, options])</code></a></li>
<li><a href="#all_tls_event-keylog_1">Event: <code>'keylog'</code></a></li>
<li><a href="#all_tls_event-ocspresponse">Event: <code>'OCSPResponse'</code></a></li>
<li><a href="#all_tls_event-secureconnect">Event: <code>'secureConnect'</code></a></li>
<li><a href="#all_tls_event-session">Event: <code>'session'</code></a></li>
<li><a href="#all_tls_tlssocketaddress"><code>tlsSocket.address()</code></a></li>
<li><a href="#all_tls_tlssocketauthorizationerror"><code>tlsSocket.authorizationError</code></a></li>
<li><a href="#all_tls_tlssocketauthorized"><code>tlsSocket.authorized</code></a></li>
<li><a href="#all_tls_tlssocketdisablerenegotiation"><code>tlsSocket.disableRenegotiation()</code></a></li>
<li><a href="#all_tls_tlssocketenabletrace"><code>tlsSocket.enableTrace()</code></a></li>
<li><a href="#all_tls_tlssocketencrypted"><code>tlsSocket.encrypted</code></a></li>
<li><a href="#all_tls_tlssocketexportkeyingmateriallength-label-context"><code>tlsSocket.exportKeyingMaterial(length, label[, context])</code></a></li>
<li><a href="#all_tls_tlssocketgetcertificate"><code>tlsSocket.getCertificate()</code></a></li>
<li><a href="#all_tls_tlssocketgetcipher"><code>tlsSocket.getCipher()</code></a></li>
<li><a href="#all_tls_tlssocketgetephemeralkeyinfo"><code>tlsSocket.getEphemeralKeyInfo()</code></a></li>
<li><a href="#all_tls_tlssocketgetfinished"><code>tlsSocket.getFinished()</code></a></li>
<li><a href="#all_tls_tlssocketgetpeercertificatedetailed"><code>tlsSocket.getPeerCertificate([detailed])</code></a>
<ul>
<li><a href="#all_tls_certificate-object">Certificate object</a></li>
</ul>
</li>
<li><a href="#all_tls_tlssocketgetpeerfinished"><code>tlsSocket.getPeerFinished()</code></a></li>
<li><a href="#all_tls_tlssocketgetpeerx509certificate"><code>tlsSocket.getPeerX509Certificate()</code></a></li>
<li><a href="#all_tls_tlssocketgetprotocol"><code>tlsSocket.getProtocol()</code></a></li>
<li><a href="#all_tls_tlssocketgetsession"><code>tlsSocket.getSession()</code></a></li>
<li><a href="#all_tls_tlssocketgetsharedsigalgs"><code>tlsSocket.getSharedSigalgs()</code></a></li>
<li><a href="#all_tls_tlssocketgettlsticket"><code>tlsSocket.getTLSTicket()</code></a></li>
<li><a href="#all_tls_tlssocketgetx509certificate"><code>tlsSocket.getX509Certificate()</code></a></li>
<li><a href="#all_tls_tlssocketissessionreused"><code>tlsSocket.isSessionReused()</code></a></li>
<li><a href="#all_tls_tlssocketlocaladdress"><code>tlsSocket.localAddress</code></a></li>
<li><a href="#all_tls_tlssocketlocalport"><code>tlsSocket.localPort</code></a></li>
<li><a href="#all_tls_tlssocketremoteaddress"><code>tlsSocket.remoteAddress</code></a></li>
<li><a href="#all_tls_tlssocketremotefamily"><code>tlsSocket.remoteFamily</code></a></li>
<li><a href="#all_tls_tlssocketremoteport"><code>tlsSocket.remotePort</code></a></li>
<li><a href="#all_tls_tlssocketrenegotiateoptions-callback"><code>tlsSocket.renegotiate(options, callback)</code></a></li>
<li><a href="#all_tls_tlssocketsetkeycertcontext"><code>tlsSocket.setKeyCert(context)</code></a></li>
<li><a href="#all_tls_tlssocketsetmaxsendfragmentsize"><code>tlsSocket.setMaxSendFragment(size)</code></a></li>
</ul>
</li>
<li><a href="#all_tls_tlscheckserveridentityhostname-cert"><code>tls.checkServerIdentity(hostname, cert)</code></a></li>
<li><a href="#all_tls_tlsconnectoptions-callback"><code>tls.connect(options[, callback])</code></a></li>
<li><a href="#all_tls_tlsconnectpath-options-callback"><code>tls.connect(path[, options][, callback])</code></a></li>
<li><a href="#all_tls_tlsconnectport-host-options-callback"><code>tls.connect(port[, host][, options][, callback])</code></a></li>
<li><a href="#all_tls_tlscreatesecurecontextoptions"><code>tls.createSecureContext([options])</code></a></li>
<li><span class="stability_0"><a href="#all_tls_tlscreatesecurepaircontext-isserver-requestcert-rejectunauthorized-options"><code>tls.createSecurePair([context][, isServer][, requestCert][, rejectUnauthorized][, options])</code></a></span></li>
<li><a href="#all_tls_tlscreateserveroptions-secureconnectionlistener"><code>tls.createServer([options][, secureConnectionListener])</code></a></li>
<li><a href="#all_tls_tlsgetciphers"><code>tls.getCiphers()</code></a></li>
<li><a href="#all_tls_tlsrootcertificates"><code>tls.rootCertificates</code></a></li>
<li><a href="#all_tls_tlsdefault_ecdh_curve"><code>tls.DEFAULT_ECDH_CURVE</code></a></li>
<li><a href="#all_tls_tlsdefault_max_version"><code>tls.DEFAULT_MAX_VERSION</code></a></li>
<li><a href="#all_tls_tlsdefault_min_version"><code>tls.DEFAULT_MIN_VERSION</code></a></li>
<li><a href="#all_tls_tlsdefault_ciphers"><code>tls.DEFAULT_CIPHERS</code></a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_tracing_trace-events">Trace events</a></span>
<ul>
<li><a href="#all_tracing_the-nodetrace_events-module">The <code>node:trace_events</code> module</a>
<ul>
<li><a href="#all_tracing_tracing-object"><code>Tracing</code> object</a>
<ul>
<li><a href="#all_tracing_tracingcategories"><code>tracing.categories</code></a></li>
<li><a href="#all_tracing_tracingdisable"><code>tracing.disable()</code></a></li>
<li><a href="#all_tracing_tracingenable"><code>tracing.enable()</code></a></li>
<li><a href="#all_tracing_tracingenabled"><code>tracing.enabled</code></a></li>
</ul>
</li>
<li><a href="#all_tracing_trace_eventscreatetracingoptions"><code>trace_events.createTracing(options)</code></a></li>
<li><a href="#all_tracing_trace_eventsgetenabledcategories"><code>trace_events.getEnabledCategories()</code></a></li>
</ul>
</li>
<li><a href="#all_tracing_examples">Examples</a>
<ul>
<li><a href="#all_tracing_collect-trace-events-data-by-inspector">Collect trace events data by inspector</a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_tty_tty">TTY</a></span>
<ul>
<li><a href="#all_tty_class-ttyreadstream">Class: <code>tty.ReadStream</code></a>
<ul>
<li><a href="#all_tty_readstreamisraw"><code>readStream.isRaw</code></a></li>
<li><a href="#all_tty_readstreamistty"><code>readStream.isTTY</code></a></li>
<li><a href="#all_tty_readstreamsetrawmodemode"><code>readStream.setRawMode(mode)</code></a></li>
</ul>
</li>
<li><a href="#all_tty_class-ttywritestream">Class: <code>tty.WriteStream</code></a>
<ul>
<li><a href="#all_tty_new-ttyreadstreamfd-options"><code>new tty.ReadStream(fd[, options])</code></a></li>
<li><a href="#all_tty_new-ttywritestreamfd"><code>new tty.WriteStream(fd)</code></a></li>
<li><a href="#all_tty_event-resize">Event: <code>'resize'</code></a></li>
<li><a href="#all_tty_writestreamclearlinedir-callback"><code>writeStream.clearLine(dir[, callback])</code></a></li>
<li><a href="#all_tty_writestreamclearscreendowncallback"><code>writeStream.clearScreenDown([callback])</code></a></li>
<li><a href="#all_tty_writestreamcolumns"><code>writeStream.columns</code></a></li>
<li><a href="#all_tty_writestreamcursortox-y-callback"><code>writeStream.cursorTo(x[, y][, callback])</code></a></li>
<li><a href="#all_tty_writestreamgetcolordepthenv"><code>writeStream.getColorDepth([env])</code></a></li>
<li><a href="#all_tty_writestreamgetwindowsize"><code>writeStream.getWindowSize()</code></a></li>
<li><a href="#all_tty_writestreamhascolorscount-env"><code>writeStream.hasColors([count][, env])</code></a></li>
<li><a href="#all_tty_writestreamistty"><code>writeStream.isTTY</code></a></li>
<li><a href="#all_tty_writestreammovecursordx-dy-callback"><code>writeStream.moveCursor(dx, dy[, callback])</code></a></li>
<li><a href="#all_tty_writestreamrows"><code>writeStream.rows</code></a></li>
</ul>
</li>
<li><a href="#all_tty_ttyisattyfd"><code>tty.isatty(fd)</code></a></li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_dgram_udpdatagram-sockets">UDP/datagram sockets</a></span>
<ul>
<li><a href="#all_dgram_class-dgramsocket">Class: <code>dgram.Socket</code></a>
<ul>
<li><a href="#all_dgram_event-close">Event: <code>'close'</code></a></li>
<li><a href="#all_dgram_event-connect">Event: <code>'connect'</code></a></li>
<li><a href="#all_dgram_event-error">Event: <code>'error'</code></a></li>
<li><a href="#all_dgram_event-listening">Event: <code>'listening'</code></a></li>
<li><a href="#all_dgram_event-message">Event: <code>'message'</code></a></li>
<li><a href="#all_dgram_socketaddmembershipmulticastaddress-multicastinterface"><code>socket.addMembership(multicastAddress[, multicastInterface])</code></a></li>
<li><a href="#all_dgram_socketaddsourcespecificmembershipsourceaddress-groupaddress-multicastinterface"><code>socket.addSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])</code></a></li>
<li><a href="#all_dgram_socketaddress"><code>socket.address()</code></a></li>
<li><a href="#all_dgram_socketbindport-address-callback"><code>socket.bind([port][, address][, callback])</code></a></li>
<li><a href="#all_dgram_socketbindoptions-callback"><code>socket.bind(options[, callback])</code></a></li>
<li><a href="#all_dgram_socketclosecallback"><code>socket.close([callback])</code></a></li>
<li><span class="stability_1"><a href="#all_dgram_socketsymbolasyncdispose"><code>socket[Symbol.asyncDispose]()</code></a></span></li>
<li><a href="#all_dgram_socketconnectport-address-callback"><code>socket.connect(port[, address][, callback])</code></a></li>
<li><a href="#all_dgram_socketdisconnect"><code>socket.disconnect()</code></a></li>
<li><a href="#all_dgram_socketdropmembershipmulticastaddress-multicastinterface"><code>socket.dropMembership(multicastAddress[, multicastInterface])</code></a></li>
<li><a href="#all_dgram_socketdropsourcespecificmembershipsourceaddress-groupaddress-multicastinterface"><code>socket.dropSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])</code></a></li>
<li><a href="#all_dgram_socketgetrecvbuffersize"><code>socket.getRecvBufferSize()</code></a></li>
<li><a href="#all_dgram_socketgetsendbuffersize"><code>socket.getSendBufferSize()</code></a></li>
<li><a href="#all_dgram_socketgetsendqueuesize"><code>socket.getSendQueueSize()</code></a></li>
<li><a href="#all_dgram_socketgetsendqueuecount"><code>socket.getSendQueueCount()</code></a></li>
<li><a href="#all_dgram_socketref"><code>socket.ref()</code></a></li>
<li><a href="#all_dgram_socketremoteaddress"><code>socket.remoteAddress()</code></a></li>
<li><a href="#all_dgram_socketsendmsg-offset-length-port-address-callback"><code>socket.send(msg[, offset, length][, port][, address][, callback])</code></a>
<ul>
<li><a href="#all_dgram_note-about-udp-datagram-size">Note about UDP datagram size</a></li>
</ul>
</li>
<li><a href="#all_dgram_socketsetbroadcastflag"><code>socket.setBroadcast(flag)</code></a></li>
<li><a href="#all_dgram_socketsetmulticastinterfacemulticastinterface"><code>socket.setMulticastInterface(multicastInterface)</code></a>
<ul>
<li><a href="#all_dgram_example-ipv6-outgoing-multicast-interface">Example: IPv6 outgoing multicast interface</a></li>
<li><a href="#all_dgram_example-ipv4-outgoing-multicast-interface">Example: IPv4 outgoing multicast interface</a></li>
<li><a href="#all_dgram_call-results">Call results</a></li>
</ul>
</li>
<li><a href="#all_dgram_socketsetmulticastloopbackflag"><code>socket.setMulticastLoopback(flag)</code></a></li>
<li><a href="#all_dgram_socketsetmulticastttlttl"><code>socket.setMulticastTTL(ttl)</code></a></li>
<li><a href="#all_dgram_socketsetrecvbuffersizesize"><code>socket.setRecvBufferSize(size)</code></a></li>
<li><a href="#all_dgram_socketsetsendbuffersizesize"><code>socket.setSendBufferSize(size)</code></a></li>
<li><a href="#all_dgram_socketsetttlttl"><code>socket.setTTL(ttl)</code></a></li>
<li><a href="#all_dgram_socketunref"><code>socket.unref()</code></a></li>
</ul>
</li>
<li><a href="#all_dgram_nodedgram-module-functions"><code>node:dgram</code> module functions</a>
<ul>
<li><a href="#all_dgram_dgramcreatesocketoptions-callback"><code>dgram.createSocket(options[, callback])</code></a></li>
<li><a href="#all_dgram_dgramcreatesockettype-callback"><code>dgram.createSocket(type[, callback])</code></a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_url_url">URL</a></span>
<ul>
<li><a href="#all_url_url-strings-and-url-objects">URL strings and URL objects</a>
<ul>
<li><a href="#all_url_constructing-a-url-from-component-parts-and-getting-the-constructed-string">Constructing a URL from component parts and getting the constructed string</a></li>
</ul>
</li>
<li><a href="#all_url_the-whatwg-url-api">The WHATWG URL API</a>
<ul>
<li><a href="#all_url_class-url">Class: <code>URL</code></a>
<ul>
<li><a href="#all_url_new-urlinput-base"><code>new URL(input[, base])</code></a></li>
<li><a href="#all_url_urlhash"><code>url.hash</code></a></li>
<li><a href="#all_url_urlhost"><code>url.host</code></a></li>
<li><a href="#all_url_urlhostname"><code>url.hostname</code></a></li>
<li><a href="#all_url_urlhref"><code>url.href</code></a></li>
<li><a href="#all_url_urlorigin"><code>url.origin</code></a></li>
<li><a href="#all_url_urlpassword"><code>url.password</code></a></li>
<li><a href="#all_url_urlpathname"><code>url.pathname</code></a></li>
<li><a href="#all_url_urlport"><code>url.port</code></a></li>
<li><a href="#all_url_urlprotocol"><code>url.protocol</code></a>
<ul>
<li><a href="#all_url_special-schemes">Special schemes</a></li>
</ul>
</li>
<li><a href="#all_url_urlsearch"><code>url.search</code></a></li>
<li><a href="#all_url_urlsearchparams"><code>url.searchParams</code></a></li>
<li><a href="#all_url_urlusername"><code>url.username</code></a></li>
<li><a href="#all_url_urltostring"><code>url.toString()</code></a></li>
<li><a href="#all_url_urltojson"><code>url.toJSON()</code></a></li>
<li><span class="stability_1"><a href="#all_url_urlcreateobjecturlblob"><code>URL.createObjectURL(blob)</code></a></span></li>
<li><span class="stability_1"><a href="#all_url_urlrevokeobjecturlid"><code>URL.revokeObjectURL(id)</code></a></span></li>
<li><a href="#all_url_urlcanparseinput-base"><code>URL.canParse(input[, base])</code></a></li>
<li><a href="#all_url_urlparseinput-base"><code>URL.parse(input[, base])</code></a></li>
</ul>
</li>
<li><a href="#all_url_class-urlsearchparams">Class: <code>URLSearchParams</code></a>
<ul>
<li><a href="#all_url_new-urlsearchparams"><code>new URLSearchParams()</code></a></li>
<li><a href="#all_url_new-urlsearchparamsstring"><code>new URLSearchParams(string)</code></a></li>
<li><a href="#all_url_new-urlsearchparamsobj"><code>new URLSearchParams(obj)</code></a></li>
<li><a href="#all_url_new-urlsearchparamsiterable"><code>new URLSearchParams(iterable)</code></a></li>
<li><a href="#all_url_urlsearchparamsappendname-value"><code>urlSearchParams.append(name, value)</code></a></li>
<li><a href="#all_url_urlsearchparamsdeletename-value"><code>urlSearchParams.delete(name[, value])</code></a></li>
<li><a href="#all_url_urlsearchparamsentries"><code>urlSearchParams.entries()</code></a></li>
<li><a href="#all_url_urlsearchparamsforeachfn-thisarg"><code>urlSearchParams.forEach(fn[, thisArg])</code></a></li>
<li><a href="#all_url_urlsearchparamsgetname"><code>urlSearchParams.get(name)</code></a></li>
<li><a href="#all_url_urlsearchparamsgetallname"><code>urlSearchParams.getAll(name)</code></a></li>
<li><a href="#all_url_urlsearchparamshasname-value"><code>urlSearchParams.has(name[, value])</code></a></li>
<li><a href="#all_url_urlsearchparamskeys"><code>urlSearchParams.keys()</code></a></li>
<li><a href="#all_url_urlsearchparamssetname-value"><code>urlSearchParams.set(name, value)</code></a></li>
<li><a href="#all_url_urlsearchparamssize"><code>urlSearchParams.size</code></a></li>
<li><a href="#all_url_urlsearchparamssort"><code>urlSearchParams.sort()</code></a></li>
<li><a href="#all_url_urlsearchparamstostring"><code>urlSearchParams.toString()</code></a></li>
<li><a href="#all_url_urlsearchparamsvalues"><code>urlSearchParams.values()</code></a></li>
<li><a href="#all_url_urlsearchparamssymboliterator"><code>urlSearchParams[Symbol.iterator]()</code></a></li>
</ul>
</li>
<li><a href="#all_url_urldomaintoasciidomain"><code>url.domainToASCII(domain)</code></a></li>
<li><a href="#all_url_urldomaintounicodedomain"><code>url.domainToUnicode(domain)</code></a></li>
<li><a href="#all_url_urlfileurltopathurl-options"><code>url.fileURLToPath(url[, options])</code></a></li>
<li><a href="#all_url_urlformaturl-options"><code>url.format(URL[, options])</code></a></li>
<li><a href="#all_url_urlpathtofileurlpath-options"><code>url.pathToFileURL(path[, options])</code></a></li>
<li><a href="#all_url_urlurltohttpoptionsurl"><code>url.urlToHttpOptions(url)</code></a></li>
</ul>
</li>
<li><span class="stability_3"><a href="#all_url_legacy-url-api">Legacy URL API</a></span>
<ul>
<li><span class="stability_3"><a href="#all_url_legacy-urlobject">Legacy <code>urlObject</code></a></span>
<ul>
<li><a href="#all_url_urlobjectauth"><code>urlObject.auth</code></a></li>
<li><a href="#all_url_urlobjecthash"><code>urlObject.hash</code></a></li>
<li><a href="#all_url_urlobjecthost"><code>urlObject.host</code></a></li>
<li><a href="#all_url_urlobjecthostname"><code>urlObject.hostname</code></a></li>
<li><a href="#all_url_urlobjecthref"><code>urlObject.href</code></a></li>
<li><a href="#all_url_urlobjectpath"><code>urlObject.path</code></a></li>
<li><a href="#all_url_urlobjectpathname"><code>urlObject.pathname</code></a></li>
<li><a href="#all_url_urlobjectport"><code>urlObject.port</code></a></li>
<li><a href="#all_url_urlobjectprotocol"><code>urlObject.protocol</code></a></li>
<li><a href="#all_url_urlobjectquery"><code>urlObject.query</code></a></li>
<li><a href="#all_url_urlobjectsearch"><code>urlObject.search</code></a></li>
<li><a href="#all_url_urlobjectslashes"><code>urlObject.slashes</code></a></li>
</ul>
</li>
<li><span class="stability_3"><a href="#all_url_urlformaturlobject"><code>url.format(urlObject)</code></a></span></li>
<li><span class="stability_0"><a href="#all_url_urlparseurlstring-parsequerystring-slashesdenotehost"><code>url.parse(urlString[, parseQueryString[, slashesDenoteHost]])</code></a></span></li>
<li><span class="stability_3"><a href="#all_url_urlresolvefrom-to"><code>url.resolve(from, to)</code></a></span></li>
</ul>
</li>
<li><a href="#all_url_percent-encoding-in-urls">Percent-encoding in URLs</a>
<ul>
<li><a href="#all_url_legacy-api">Legacy API</a></li>
<li><a href="#all_url_whatwg-api">WHATWG API</a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_util_util">Util</a></span>
<ul>
<li><a href="#all_util_utilcallbackifyoriginal"><code>util.callbackify(original)</code></a></li>
<li><a href="#all_util_utildebuglogsection-callback"><code>util.debuglog(section[, callback])</code></a>
<ul>
<li><a href="#all_util_debuglogenabled"><code>debuglog().enabled</code></a></li>
</ul>
</li>
<li><a href="#all_util_utildebugsection"><code>util.debug(section)</code></a></li>
<li><a href="#all_util_utildeprecatefn-msg-code"><code>util.deprecate(fn, msg[, code])</code></a></li>
<li><a href="#all_util_utilformatformat-args"><code>util.format(format[, ...args])</code></a></li>
<li><a href="#all_util_utilformatwithoptionsinspectoptions-format-args"><code>util.formatWithOptions(inspectOptions, format[, ...args])</code></a></li>
<li><a href="#all_util_utilgetsystemerrornameerr"><code>util.getSystemErrorName(err)</code></a></li>
<li><a href="#all_util_utilgetsystemerrormap"><code>util.getSystemErrorMap()</code></a></li>
<li><span class="stability_3"><a href="#all_util_utilinheritsconstructor-superconstructor"><code>util.inherits(constructor, superConstructor)</code></a></span></li>
<li><a href="#all_util_utilinspectobject-options"><code>util.inspect(object[, options])</code></a></li>
<li><a href="#all_util_utilinspectobject-showhidden-depth-colors"><code>util.inspect(object[, showHidden[, depth[, colors]]])</code></a>
<ul>
<li><a href="#all_util_customizing-utilinspect-colors">Customizing <code>util.inspect</code> colors</a>
<ul>
<li><a href="#all_util_modifiers">Modifiers</a></li>
<li><a href="#all_util_foreground-colors">Foreground colors</a></li>
<li><a href="#all_util_background-colors">Background colors</a></li>
</ul>
</li>
<li><a href="#all_util_custom-inspection-functions-on-objects">Custom inspection functions on objects</a></li>
<li><a href="#all_util_utilinspectcustom"><code>util.inspect.custom</code></a></li>
<li><a href="#all_util_utilinspectdefaultoptions"><code>util.inspect.defaultOptions</code></a></li>
</ul>
</li>
<li><a href="#all_util_utilisdeepstrictequalval1-val2"><code>util.isDeepStrictEqual(val1, val2)</code></a></li>
<li><span class="stability_1"><a href="#all_util_class-utilmimetype">Class: <code>util.MIMEType</code></a></span>
<ul>
<li><a href="#all_util_constructor-new-mimetypeinput">Constructor: <code>new MIMEType(input)</code></a></li>
<li><a href="#all_util_mimetype"><code>mime.type</code></a></li>
<li><a href="#all_util_mimesubtype"><code>mime.subtype</code></a></li>
<li><a href="#all_util_mimeessence"><code>mime.essence</code></a></li>
<li><a href="#all_util_mimeparams"><code>mime.params</code></a></li>
<li><a href="#all_util_mimetostring"><code>mime.toString()</code></a></li>
<li><a href="#all_util_mimetojson"><code>mime.toJSON()</code></a></li>
</ul>
</li>
<li><a href="#all_util_class-utilmimeparams">Class: <code>util.MIMEParams</code></a>
<ul>
<li><a href="#all_util_constructor-new-mimeparams">Constructor: <code>new MIMEParams()</code></a></li>
<li><a href="#all_util_mimeparamsdeletename"><code>mimeParams.delete(name)</code></a></li>
<li><a href="#all_util_mimeparamsentries"><code>mimeParams.entries()</code></a></li>
<li><a href="#all_util_mimeparamsgetname"><code>mimeParams.get(name)</code></a></li>
<li><a href="#all_util_mimeparamshasname"><code>mimeParams.has(name)</code></a></li>
<li><a href="#all_util_mimeparamskeys"><code>mimeParams.keys()</code></a></li>
<li><a href="#all_util_mimeparamssetname-value"><code>mimeParams.set(name, value)</code></a></li>
<li><a href="#all_util_mimeparamsvalues"><code>mimeParams.values()</code></a></li>
<li><a href="#all_util_mimeparamsiterator"><code>mimeParams[@@iterator]()</code></a></li>
</ul>
</li>
<li><a href="#all_util_utilparseargsconfig"><code>util.parseArgs([config])</code></a>
<ul>
<li><a href="#all_util_parseargs-tokens"><code>parseArgs</code> <code>tokens</code></a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_util_utilparseenvcontent"><code>util.parseEnv(content)</code></a></span></li>
<li><a href="#all_util_utilpromisifyoriginal"><code>util.promisify(original)</code></a>
<ul>
<li><a href="#all_util_custom-promisified-functions">Custom promisified functions</a></li>
<li><a href="#all_util_utilpromisifycustom"><code>util.promisify.custom</code></a></li>
</ul>
</li>
<li><a href="#all_util_utilstripvtcontrolcharactersstr"><code>util.stripVTControlCharacters(str)</code></a></li>
<li><span class="stability_1"><a href="#all_util_utilstyletextformat-text-options"><code>util.styleText(format, text[, options])</code></a></span></li>
<li><a href="#all_util_class-utiltextdecoder">Class: <code>util.TextDecoder</code></a>
<ul>
<li><a href="#all_util_whatwg-supported-encodings">WHATWG supported encodings</a>
<ul>
<li><a href="#all_util_encodings-supported-by-default-with-full-icu-data">Encodings supported by default (with full ICU data)</a></li>
<li><a href="#all_util_encodings-supported-when-nodejs-is-built-with-the-small-icu-option">Encodings supported when Node.js is built with the <code>small-icu</code> option</a></li>
<li><a href="#all_util_encodings-supported-when-icu-is-disabled">Encodings supported when ICU is disabled</a></li>
</ul>
</li>
<li><a href="#all_util_new-textdecoderencoding-options"><code>new TextDecoder([encoding[, options]])</code></a></li>
<li><a href="#all_util_textdecoderdecodeinput-options"><code>textDecoder.decode([input[, options]])</code></a></li>
<li><a href="#all_util_textdecoderencoding"><code>textDecoder.encoding</code></a></li>
<li><a href="#all_util_textdecoderfatal"><code>textDecoder.fatal</code></a></li>
<li><a href="#all_util_textdecoderignorebom"><code>textDecoder.ignoreBOM</code></a></li>
</ul>
</li>
<li><a href="#all_util_class-utiltextencoder">Class: <code>util.TextEncoder</code></a>
<ul>
<li><a href="#all_util_textencoderencodeinput"><code>textEncoder.encode([input])</code></a></li>
<li><a href="#all_util_textencoderencodeintosrc-dest"><code>textEncoder.encodeInto(src, dest)</code></a></li>
<li><a href="#all_util_textencoderencoding"><code>textEncoder.encoding</code></a></li>
</ul>
</li>
<li><a href="#all_util_utiltousvstringstring"><code>util.toUSVString(string)</code></a></li>
<li><span class="stability_1"><a href="#all_util_utiltransferableabortcontroller"><code>util.transferableAbortController()</code></a></span></li>
<li><span class="stability_1"><a href="#all_util_utiltransferableabortsignalsignal"><code>util.transferableAbortSignal(signal)</code></a></span></li>
<li><span class="stability_1"><a href="#all_util_utilabortedsignal-resource"><code>util.aborted(signal, resource)</code></a></span></li>
<li><a href="#all_util_utiltypes"><code>util.types</code></a>
<ul>
<li><a href="#all_util_utiltypesisanyarraybuffervalue"><code>util.types.isAnyArrayBuffer(value)</code></a></li>
<li><a href="#all_util_utiltypesisarraybufferviewvalue"><code>util.types.isArrayBufferView(value)</code></a></li>
<li><a href="#all_util_utiltypesisargumentsobjectvalue"><code>util.types.isArgumentsObject(value)</code></a></li>
<li><a href="#all_util_utiltypesisarraybuffervalue"><code>util.types.isArrayBuffer(value)</code></a></li>
<li><a href="#all_util_utiltypesisasyncfunctionvalue"><code>util.types.isAsyncFunction(value)</code></a></li>
<li><a href="#all_util_utiltypesisbigint64arrayvalue"><code>util.types.isBigInt64Array(value)</code></a></li>
<li><a href="#all_util_utiltypesisbiguint64arrayvalue"><code>util.types.isBigUint64Array(value)</code></a></li>
<li><a href="#all_util_utiltypesisbooleanobjectvalue"><code>util.types.isBooleanObject(value)</code></a></li>
<li><a href="#all_util_utiltypesisboxedprimitivevalue"><code>util.types.isBoxedPrimitive(value)</code></a></li>
<li><a href="#all_util_utiltypesiscryptokeyvalue"><code>util.types.isCryptoKey(value)</code></a></li>
<li><a href="#all_util_utiltypesisdataviewvalue"><code>util.types.isDataView(value)</code></a></li>
<li><a href="#all_util_utiltypesisdatevalue"><code>util.types.isDate(value)</code></a></li>
<li><a href="#all_util_utiltypesisexternalvalue"><code>util.types.isExternal(value)</code></a></li>
<li><a href="#all_util_utiltypesisfloat32arrayvalue"><code>util.types.isFloat32Array(value)</code></a></li>
<li><a href="#all_util_utiltypesisfloat64arrayvalue"><code>util.types.isFloat64Array(value)</code></a></li>
<li><a href="#all_util_utiltypesisgeneratorfunctionvalue"><code>util.types.isGeneratorFunction(value)</code></a></li>
<li><a href="#all_util_utiltypesisgeneratorobjectvalue"><code>util.types.isGeneratorObject(value)</code></a></li>
<li><a href="#all_util_utiltypesisint8arrayvalue"><code>util.types.isInt8Array(value)</code></a></li>
<li><a href="#all_util_utiltypesisint16arrayvalue"><code>util.types.isInt16Array(value)</code></a></li>
<li><a href="#all_util_utiltypesisint32arrayvalue"><code>util.types.isInt32Array(value)</code></a></li>
<li><a href="#all_util_utiltypesiskeyobjectvalue"><code>util.types.isKeyObject(value)</code></a></li>
<li><a href="#all_util_utiltypesismapvalue"><code>util.types.isMap(value)</code></a></li>
<li><a href="#all_util_utiltypesismapiteratorvalue"><code>util.types.isMapIterator(value)</code></a></li>
<li><a href="#all_util_utiltypesismodulenamespaceobjectvalue"><code>util.types.isModuleNamespaceObject(value)</code></a></li>
<li><a href="#all_util_utiltypesisnativeerrorvalue"><code>util.types.isNativeError(value)</code></a></li>
<li><a href="#all_util_utiltypesisnumberobjectvalue"><code>util.types.isNumberObject(value)</code></a></li>
<li><a href="#all_util_utiltypesispromisevalue"><code>util.types.isPromise(value)</code></a></li>
<li><a href="#all_util_utiltypesisproxyvalue"><code>util.types.isProxy(value)</code></a></li>
<li><a href="#all_util_utiltypesisregexpvalue"><code>util.types.isRegExp(value)</code></a></li>
<li><a href="#all_util_utiltypesissetvalue"><code>util.types.isSet(value)</code></a></li>
<li><a href="#all_util_utiltypesissetiteratorvalue"><code>util.types.isSetIterator(value)</code></a></li>
<li><a href="#all_util_utiltypesissharedarraybuffervalue"><code>util.types.isSharedArrayBuffer(value)</code></a></li>
<li><a href="#all_util_utiltypesisstringobjectvalue"><code>util.types.isStringObject(value)</code></a></li>
<li><a href="#all_util_utiltypesissymbolobjectvalue"><code>util.types.isSymbolObject(value)</code></a></li>
<li><a href="#all_util_utiltypesistypedarrayvalue"><code>util.types.isTypedArray(value)</code></a></li>
<li><a href="#all_util_utiltypesisuint8arrayvalue"><code>util.types.isUint8Array(value)</code></a></li>
<li><a href="#all_util_utiltypesisuint8clampedarrayvalue"><code>util.types.isUint8ClampedArray(value)</code></a></li>
<li><a href="#all_util_utiltypesisuint16arrayvalue"><code>util.types.isUint16Array(value)</code></a></li>
<li><a href="#all_util_utiltypesisuint32arrayvalue"><code>util.types.isUint32Array(value)</code></a></li>
<li><a href="#all_util_utiltypesisweakmapvalue"><code>util.types.isWeakMap(value)</code></a></li>
<li><a href="#all_util_utiltypesisweaksetvalue"><code>util.types.isWeakSet(value)</code></a></li>
</ul>
</li>
<li><a href="#all_util_deprecated-apis">Deprecated APIs</a>
<ul>
<li><span class="stability_0"><a href="#all_util_util_extendtarget-source"><code>util._extend(target, source)</code></a></span></li>
<li><span class="stability_0"><a href="#all_util_utilisarrayobject"><code>util.isArray(object)</code></a></span></li>
<li><span class="stability_0"><a href="#all_util_utilisbooleanobject"><code>util.isBoolean(object)</code></a></span></li>
<li><span class="stability_0"><a href="#all_util_utilisbufferobject"><code>util.isBuffer(object)</code></a></span></li>
<li><span class="stability_0"><a href="#all_util_utilisdateobject"><code>util.isDate(object)</code></a></span></li>
<li><span class="stability_0"><a href="#all_util_utiliserrorobject"><code>util.isError(object)</code></a></span></li>
<li><span class="stability_0"><a href="#all_util_utilisfunctionobject"><code>util.isFunction(object)</code></a></span></li>
<li><span class="stability_0"><a href="#all_util_utilisnullobject"><code>util.isNull(object)</code></a></span></li>
<li><span class="stability_0"><a href="#all_util_utilisnullorundefinedobject"><code>util.isNullOrUndefined(object)</code></a></span></li>
<li><span class="stability_0"><a href="#all_util_utilisnumberobject"><code>util.isNumber(object)</code></a></span></li>
<li><span class="stability_0"><a href="#all_util_utilisobjectobject"><code>util.isObject(object)</code></a></span></li>
<li><span class="stability_0"><a href="#all_util_utilisprimitiveobject"><code>util.isPrimitive(object)</code></a></span></li>
<li><span class="stability_0"><a href="#all_util_utilisregexpobject"><code>util.isRegExp(object)</code></a></span></li>
<li><span class="stability_0"><a href="#all_util_utilisstringobject"><code>util.isString(object)</code></a></span></li>
<li><span class="stability_0"><a href="#all_util_utilissymbolobject"><code>util.isSymbol(object)</code></a></span></li>
<li><span class="stability_0"><a href="#all_util_utilisundefinedobject"><code>util.isUndefined(object)</code></a></span></li>
<li><span class="stability_0"><a href="#all_util_utillogstring"><code>util.log(string)</code></a></span></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_v8_v8">V8</a>
<ul>
<li><a href="#all_v8_v8cacheddataversiontag"><code>v8.cachedDataVersionTag()</code></a></li>
<li><a href="#all_v8_v8getheapcodestatistics"><code>v8.getHeapCodeStatistics()</code></a></li>
<li><a href="#all_v8_v8getheapsnapshotoptions"><code>v8.getHeapSnapshot([options])</code></a></li>
<li><a href="#all_v8_v8getheapspacestatistics"><code>v8.getHeapSpaceStatistics()</code></a></li>
<li><a href="#all_v8_v8getheapstatistics"><code>v8.getHeapStatistics()</code></a></li>
<li><span class="stability_1"><a href="#all_v8_v8queryobjectsctor-options"><code>v8.queryObjects(ctor[, options])</code></a></span></li>
<li><a href="#all_v8_v8setflagsfromstringflags"><code>v8.setFlagsFromString(flags)</code></a></li>
<li><a href="#all_v8_v8stopcoverage"><code>v8.stopCoverage()</code></a></li>
<li><a href="#all_v8_v8takecoverage"><code>v8.takeCoverage()</code></a></li>
<li><a href="#all_v8_v8writeheapsnapshotfilenameoptions"><code>v8.writeHeapSnapshot([filename[,options]])</code></a></li>
<li><span class="stability_1"><a href="#all_v8_v8setheapsnapshotnearheaplimitlimit"><code>v8.setHeapSnapshotNearHeapLimit(limit)</code></a></span></li>
<li><a href="#all_v8_serialization-api">Serialization API</a>
<ul>
<li><a href="#all_v8_v8serializevalue"><code>v8.serialize(value)</code></a></li>
<li><a href="#all_v8_v8deserializebuffer"><code>v8.deserialize(buffer)</code></a></li>
<li><a href="#all_v8_class-v8serializer">Class: <code>v8.Serializer</code></a>
<ul>
<li><a href="#all_v8_new-serializer"><code>new Serializer()</code></a></li>
<li><a href="#all_v8_serializerwriteheader"><code>serializer.writeHeader()</code></a></li>
<li><a href="#all_v8_serializerwritevaluevalue"><code>serializer.writeValue(value)</code></a></li>
<li><a href="#all_v8_serializerreleasebuffer"><code>serializer.releaseBuffer()</code></a></li>
<li><a href="#all_v8_serializertransferarraybufferid-arraybuffer"><code>serializer.transferArrayBuffer(id, arrayBuffer)</code></a></li>
<li><a href="#all_v8_serializerwriteuint32value"><code>serializer.writeUint32(value)</code></a></li>
<li><a href="#all_v8_serializerwriteuint64hi-lo"><code>serializer.writeUint64(hi, lo)</code></a></li>
<li><a href="#all_v8_serializerwritedoublevalue"><code>serializer.writeDouble(value)</code></a></li>
<li><a href="#all_v8_serializerwriterawbytesbuffer"><code>serializer.writeRawBytes(buffer)</code></a></li>
<li><a href="#all_v8_serializer_writehostobjectobject"><code>serializer._writeHostObject(object)</code></a></li>
<li><a href="#all_v8_serializer_getdatacloneerrormessage"><code>serializer._getDataCloneError(message)</code></a></li>
<li><a href="#all_v8_serializer_getsharedarraybufferidsharedarraybuffer"><code>serializer._getSharedArrayBufferId(sharedArrayBuffer)</code></a></li>
<li><a href="#all_v8_serializer_settreatarraybufferviewsashostobjectsflag"><code>serializer._setTreatArrayBufferViewsAsHostObjects(flag)</code></a></li>
</ul>
</li>
<li><a href="#all_v8_class-v8deserializer">Class: <code>v8.Deserializer</code></a>
<ul>
<li><a href="#all_v8_new-deserializerbuffer"><code>new Deserializer(buffer)</code></a></li>
<li><a href="#all_v8_deserializerreadheader"><code>deserializer.readHeader()</code></a></li>
<li><a href="#all_v8_deserializerreadvalue"><code>deserializer.readValue()</code></a></li>
<li><a href="#all_v8_deserializertransferarraybufferid-arraybuffer"><code>deserializer.transferArrayBuffer(id, arrayBuffer)</code></a></li>
<li><a href="#all_v8_deserializergetwireformatversion"><code>deserializer.getWireFormatVersion()</code></a></li>
<li><a href="#all_v8_deserializerreaduint32"><code>deserializer.readUint32()</code></a></li>
<li><a href="#all_v8_deserializerreaduint64"><code>deserializer.readUint64()</code></a></li>
<li><a href="#all_v8_deserializerreaddouble"><code>deserializer.readDouble()</code></a></li>
<li><a href="#all_v8_deserializerreadrawbyteslength"><code>deserializer.readRawBytes(length)</code></a></li>
<li><a href="#all_v8_deserializer_readhostobject"><code>deserializer._readHostObject()</code></a></li>
</ul>
</li>
<li><a href="#all_v8_class-v8defaultserializer">Class: <code>v8.DefaultSerializer</code></a></li>
<li><a href="#all_v8_class-v8defaultdeserializer">Class: <code>v8.DefaultDeserializer</code></a></li>
</ul>
</li>
<li><a href="#all_v8_promise-hooks">Promise hooks</a>
<ul>
<li><a href="#all_v8_promisehooksoninitinit"><code>promiseHooks.onInit(init)</code></a></li>
<li><a href="#all_v8_promisehooksonsettledsettled"><code>promiseHooks.onSettled(settled)</code></a></li>
<li><a href="#all_v8_promisehooksonbeforebefore"><code>promiseHooks.onBefore(before)</code></a></li>
<li><a href="#all_v8_promisehooksonafterafter"><code>promiseHooks.onAfter(after)</code></a></li>
<li><a href="#all_v8_promisehookscreatehookcallbacks"><code>promiseHooks.createHook(callbacks)</code></a></li>
<li><a href="#all_v8_hook-callbacks">Hook callbacks</a>
<ul>
<li><a href="#all_v8_initpromise-parent"><code>init(promise, parent)</code></a></li>
<li><a href="#all_v8_beforepromise"><code>before(promise)</code></a></li>
<li><a href="#all_v8_afterpromise"><code>after(promise)</code></a></li>
<li><a href="#all_v8_settledpromise"><code>settled(promise)</code></a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_v8_startup-snapshot-api">Startup Snapshot API</a></span>
<ul>
<li><a href="#all_v8_v8startupsnapshotaddserializecallbackcallback-data"><code>v8.startupSnapshot.addSerializeCallback(callback[, data])</code></a></li>
<li><a href="#all_v8_v8startupsnapshotadddeserializecallbackcallback-data"><code>v8.startupSnapshot.addDeserializeCallback(callback[, data])</code></a></li>
<li><a href="#all_v8_v8startupsnapshotsetdeserializemainfunctioncallback-data"><code>v8.startupSnapshot.setDeserializeMainFunction(callback[, data])</code></a></li>
<li><a href="#all_v8_v8startupsnapshotisbuildingsnapshot"><code>v8.startupSnapshot.isBuildingSnapshot()</code></a></li>
</ul>
</li>
<li><a href="#all_v8_class-v8gcprofiler">Class: <code>v8.GCProfiler</code></a>
<ul>
<li><a href="#all_v8_new-v8gcprofiler"><code>new v8.GCProfiler()</code></a></li>
<li><a href="#all_v8_profilerstart"><code>profiler.start()</code></a></li>
<li><a href="#all_v8_profilerstop"><code>profiler.stop()</code></a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_vm_vm-executing-javascript">VM (executing JavaScript)</a></span>
<ul>
<li><a href="#all_vm_class-vmscript">Class: <code>vm.Script</code></a>
<ul>
<li><a href="#all_vm_new-vmscriptcode-options"><code>new vm.Script(code[, options])</code></a></li>
<li><a href="#all_vm_scriptcacheddatarejected"><code>script.cachedDataRejected</code></a></li>
<li><a href="#all_vm_scriptcreatecacheddata"><code>script.createCachedData()</code></a></li>
<li><a href="#all_vm_scriptrunincontextcontextifiedobject-options"><code>script.runInContext(contextifiedObject[, options])</code></a></li>
<li><a href="#all_vm_scriptruninnewcontextcontextobject-options"><code>script.runInNewContext([contextObject[, options]])</code></a></li>
<li><a href="#all_vm_scriptruninthiscontextoptions"><code>script.runInThisContext([options])</code></a></li>
<li><a href="#all_vm_scriptsourcemapurl"><code>script.sourceMapURL</code></a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_vm_class-vmmodule">Class: <code>vm.Module</code></a></span>
<ul>
<li><a href="#all_vm_moduledependencyspecifiers"><code>module.dependencySpecifiers</code></a></li>
<li><a href="#all_vm_moduleerror"><code>module.error</code></a></li>
<li><a href="#all_vm_moduleevaluateoptions"><code>module.evaluate([options])</code></a></li>
<li><a href="#all_vm_moduleidentifier"><code>module.identifier</code></a></li>
<li><a href="#all_vm_modulelinklinker"><code>module.link(linker)</code></a></li>
<li><a href="#all_vm_modulenamespace"><code>module.namespace</code></a></li>
<li><a href="#all_vm_modulestatus"><code>module.status</code></a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_vm_class-vmsourcetextmodule">Class: <code>vm.SourceTextModule</code></a></span>
<ul>
<li><a href="#all_vm_new-vmsourcetextmodulecode-options"><code>new vm.SourceTextModule(code[, options])</code></a></li>
<li><a href="#all_vm_sourcetextmodulecreatecacheddata"><code>sourceTextModule.createCachedData()</code></a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_vm_class-vmsyntheticmodule">Class: <code>vm.SyntheticModule</code></a></span>
<ul>
<li><a href="#all_vm_new-vmsyntheticmoduleexportnames-evaluatecallback-options"><code>new vm.SyntheticModule(exportNames, evaluateCallback[, options])</code></a></li>
<li><a href="#all_vm_syntheticmodulesetexportname-value"><code>syntheticModule.setExport(name, value)</code></a></li>
</ul>
</li>
<li><a href="#all_vm_vmcompilefunctioncode-params-options"><code>vm.compileFunction(code[, params[, options]])</code></a></li>
<li><a href="#all_vm_vmconstants"><code>vm.constants</code></a>
<ul>
<li><span class="stability_1"><a href="#all_vm_vmconstantsuse_main_context_default_loader"><code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code></a></span></li>
</ul>
</li>
<li><a href="#all_vm_vmcreatecontextcontextobject-options"><code>vm.createContext([contextObject[, options]])</code></a></li>
<li><a href="#all_vm_vmiscontextobject"><code>vm.isContext(object)</code></a></li>
<li><span class="stability_1"><a href="#all_vm_vmmeasurememoryoptions"><code>vm.measureMemory([options])</code></a></span></li>
<li><a href="#all_vm_vmrunincontextcode-contextifiedobject-options"><code>vm.runInContext(code, contextifiedObject[, options])</code></a></li>
<li><a href="#all_vm_vmruninnewcontextcode-contextobject-options"><code>vm.runInNewContext(code[, contextObject[, options]])</code></a></li>
<li><a href="#all_vm_vmruninthiscontextcode-options"><code>vm.runInThisContext(code[, options])</code></a></li>
<li><a href="#all_vm_example-running-an-http-server-within-a-vm">Example: Running an HTTP server within a VM</a></li>
<li><a href="#all_vm_what-does-it-mean-to-contextify-an-object">What does it mean to "contextify" an object?</a>
<ul>
<li><a href="#all_vm_vmconstantsdont_contextify"><code>vm.constants.DONT_CONTEXTIFY</code></a></li>
</ul>
</li>
<li><a href="#all_vm_timeout-interactions-with-asynchronous-tasks-and-promises">Timeout interactions with asynchronous tasks and Promises</a></li>
<li><a href="#all_vm_support-of-dynamic-import-in-compilation-apis">Support of dynamic <code>import()</code> in compilation APIs</a>
<ul>
<li><a href="#all_vm_when-the-importmoduledynamically-option-is-not-specified-or-undefined">When the <code>importModuleDynamically</code> option is not specified or undefined</a></li>
<li><a href="#all_vm_when-importmoduledynamically-is-vmconstantsuse_main_context_default_loader">When <code>importModuleDynamically</code> is <code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code></a></li>
<li><a href="#all_vm_when-importmoduledynamically-is-a-function">When <code>importModuleDynamically</code> is a function</a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_wasi_webassembly-system-interface-wasi">WebAssembly System Interface (WASI)</a></span>
<ul>
<li><a href="#all_wasi_security">Security</a></li>
<li><a href="#all_wasi_class-wasi">Class: <code>WASI</code></a>
<ul>
<li><a href="#all_wasi_new-wasioptions"><code>new WASI([options])</code></a></li>
<li><a href="#all_wasi_wasigetimportobject"><code>wasi.getImportObject()</code></a></li>
<li><a href="#all_wasi_wasistartinstance"><code>wasi.start(instance)</code></a></li>
<li><a href="#all_wasi_wasiinitializeinstance"><code>wasi.initialize(instance)</code></a></li>
<li><a href="#all_wasi_wasiwasiimport"><code>wasi.wasiImport</code></a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_webcrypto_web-crypto-api">Web Crypto API</a></span>
<ul>
<li><a href="#all_webcrypto_examples">Examples</a>
<ul>
<li><a href="#all_webcrypto_generating-keys">Generating keys</a>
<ul>
<li><a href="#all_webcrypto_aes-keys">AES keys</a></li>
<li><a href="#all_webcrypto_ecdsa-key-pairs">ECDSA key pairs</a></li>
<li><span class="stability_1"><a href="#all_webcrypto_ed25519ed448x25519x448-key-pairs">Ed25519/Ed448/X25519/X448 key pairs</a></span></li>
<li><a href="#all_webcrypto_hmac-keys">HMAC keys</a></li>
<li><a href="#all_webcrypto_rsa-key-pairs">RSA key pairs</a></li>
</ul>
</li>
<li><a href="#all_webcrypto_encryption-and-decryption">Encryption and decryption</a></li>
<li><a href="#all_webcrypto_exporting-and-importing-keys">Exporting and importing keys</a></li>
<li><a href="#all_webcrypto_wrapping-and-unwrapping-keys">Wrapping and unwrapping keys</a></li>
<li><a href="#all_webcrypto_sign-and-verify">Sign and verify</a></li>
<li><a href="#all_webcrypto_deriving-bits-and-keys">Deriving bits and keys</a></li>
<li><a href="#all_webcrypto_digest">Digest</a></li>
</ul>
</li>
<li><a href="#all_webcrypto_algorithm-matrix">Algorithm matrix</a></li>
<li><a href="#all_webcrypto_class-crypto">Class: <code>Crypto</code></a>
<ul>
<li><a href="#all_webcrypto_cryptosubtle"><code>crypto.subtle</code></a></li>
<li><a href="#all_webcrypto_cryptogetrandomvaluestypedarray"><code>crypto.getRandomValues(typedArray)</code></a></li>
<li><a href="#all_webcrypto_cryptorandomuuid"><code>crypto.randomUUID()</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_class-cryptokey">Class: <code>CryptoKey</code></a>
<ul>
<li><a href="#all_webcrypto_cryptokeyalgorithm"><code>cryptoKey.algorithm</code></a></li>
<li><a href="#all_webcrypto_cryptokeyextractable"><code>cryptoKey.extractable</code></a></li>
<li><a href="#all_webcrypto_cryptokeytype"><code>cryptoKey.type</code></a></li>
<li><a href="#all_webcrypto_cryptokeyusages"><code>cryptoKey.usages</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_class-cryptokeypair">Class: <code>CryptoKeyPair</code></a>
<ul>
<li><a href="#all_webcrypto_cryptokeypairprivatekey"><code>cryptoKeyPair.privateKey</code></a></li>
<li><a href="#all_webcrypto_cryptokeypairpublickey"><code>cryptoKeyPair.publicKey</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_class-subtlecrypto">Class: <code>SubtleCrypto</code></a>
<ul>
<li><a href="#all_webcrypto_subtledecryptalgorithm-key-data"><code>subtle.decrypt(algorithm, key, data)</code></a></li>
<li><a href="#all_webcrypto_subtlederivebitsalgorithm-basekey-length"><code>subtle.deriveBits(algorithm, baseKey[, length])</code></a></li>
<li><a href="#all_webcrypto_subtlederivekeyalgorithm-basekey-derivedkeyalgorithm-extractable-keyusages"><code>subtle.deriveKey(algorithm, baseKey, derivedKeyAlgorithm, extractable, keyUsages)</code></a></li>
<li><a href="#all_webcrypto_subtledigestalgorithm-data"><code>subtle.digest(algorithm, data)</code></a></li>
<li><a href="#all_webcrypto_subtleencryptalgorithm-key-data"><code>subtle.encrypt(algorithm, key, data)</code></a></li>
<li><a href="#all_webcrypto_subtleexportkeyformat-key"><code>subtle.exportKey(format, key)</code></a></li>
<li><a href="#all_webcrypto_subtlegeneratekeyalgorithm-extractable-keyusages"><code>subtle.generateKey(algorithm, extractable, keyUsages)</code></a></li>
<li><a href="#all_webcrypto_subtleimportkeyformat-keydata-algorithm-extractable-keyusages"><code>subtle.importKey(format, keyData, algorithm, extractable, keyUsages)</code></a></li>
<li><a href="#all_webcrypto_subtlesignalgorithm-key-data"><code>subtle.sign(algorithm, key, data)</code></a></li>
<li><a href="#all_webcrypto_subtleunwrapkeyformat-wrappedkey-unwrappingkey-unwrapalgo-unwrappedkeyalgo-extractable-keyusages"><code>subtle.unwrapKey(format, wrappedKey, unwrappingKey, unwrapAlgo, unwrappedKeyAlgo, extractable, keyUsages)</code></a></li>
<li><a href="#all_webcrypto_subtleverifyalgorithm-key-signature-data"><code>subtle.verify(algorithm, key, signature, data)</code></a></li>
<li><a href="#all_webcrypto_subtlewrapkeyformat-key-wrappingkey-wrapalgo"><code>subtle.wrapKey(format, key, wrappingKey, wrapAlgo)</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_algorithm-parameters">Algorithm parameters</a>
<ul>
<li><a href="#all_webcrypto_class-algorithmidentifier">Class: <code>AlgorithmIdentifier</code></a>
<ul>
<li><a href="#all_webcrypto_algorithmidentifiername"><code>algorithmIdentifier.name</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_class-aescbcparams">Class: <code>AesCbcParams</code></a>
<ul>
<li><a href="#all_webcrypto_aescbcparamsiv"><code>aesCbcParams.iv</code></a></li>
<li><a href="#all_webcrypto_aescbcparamsname"><code>aesCbcParams.name</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_class-aesctrparams">Class: <code>AesCtrParams</code></a>
<ul>
<li><a href="#all_webcrypto_aesctrparamscounter"><code>aesCtrParams.counter</code></a></li>
<li><a href="#all_webcrypto_aesctrparamslength"><code>aesCtrParams.length</code></a></li>
<li><a href="#all_webcrypto_aesctrparamsname"><code>aesCtrParams.name</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_class-aesgcmparams">Class: <code>AesGcmParams</code></a>
<ul>
<li><a href="#all_webcrypto_aesgcmparamsadditionaldata"><code>aesGcmParams.additionalData</code></a></li>
<li><a href="#all_webcrypto_aesgcmparamsiv"><code>aesGcmParams.iv</code></a></li>
<li><a href="#all_webcrypto_aesgcmparamsname"><code>aesGcmParams.name</code></a></li>
<li><a href="#all_webcrypto_aesgcmparamstaglength"><code>aesGcmParams.tagLength</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_class-aeskeygenparams">Class: <code>AesKeyGenParams</code></a>
<ul>
<li><a href="#all_webcrypto_aeskeygenparamslength"><code>aesKeyGenParams.length</code></a></li>
<li><a href="#all_webcrypto_aeskeygenparamsname"><code>aesKeyGenParams.name</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_class-ecdhkeyderiveparams">Class: <code>EcdhKeyDeriveParams</code></a>
<ul>
<li><a href="#all_webcrypto_ecdhkeyderiveparamsname"><code>ecdhKeyDeriveParams.name</code></a></li>
<li><a href="#all_webcrypto_ecdhkeyderiveparamspublic"><code>ecdhKeyDeriveParams.public</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_class-ecdsaparams">Class: <code>EcdsaParams</code></a>
<ul>
<li><a href="#all_webcrypto_ecdsaparamshash"><code>ecdsaParams.hash</code></a></li>
<li><a href="#all_webcrypto_ecdsaparamsname"><code>ecdsaParams.name</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_class-eckeygenparams">Class: <code>EcKeyGenParams</code></a>
<ul>
<li><a href="#all_webcrypto_eckeygenparamsname"><code>ecKeyGenParams.name</code></a></li>
<li><a href="#all_webcrypto_eckeygenparamsnamedcurve"><code>ecKeyGenParams.namedCurve</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_class-eckeyimportparams">Class: <code>EcKeyImportParams</code></a>
<ul>
<li><a href="#all_webcrypto_eckeyimportparamsname"><code>ecKeyImportParams.name</code></a></li>
<li><a href="#all_webcrypto_eckeyimportparamsnamedcurve"><code>ecKeyImportParams.namedCurve</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_class-ed448params">Class: <code>Ed448Params</code></a>
<ul>
<li><a href="#all_webcrypto_ed448paramsname"><code>ed448Params.name</code></a></li>
<li><a href="#all_webcrypto_ed448paramscontext"><code>ed448Params.context</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_class-hkdfparams">Class: <code>HkdfParams</code></a>
<ul>
<li><a href="#all_webcrypto_hkdfparamshash"><code>hkdfParams.hash</code></a></li>
<li><a href="#all_webcrypto_hkdfparamsinfo"><code>hkdfParams.info</code></a></li>
<li><a href="#all_webcrypto_hkdfparamsname"><code>hkdfParams.name</code></a></li>
<li><a href="#all_webcrypto_hkdfparamssalt"><code>hkdfParams.salt</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_class-hmacimportparams">Class: <code>HmacImportParams</code></a>
<ul>
<li><a href="#all_webcrypto_hmacimportparamshash"><code>hmacImportParams.hash</code></a></li>
<li><a href="#all_webcrypto_hmacimportparamslength"><code>hmacImportParams.length</code></a></li>
<li><a href="#all_webcrypto_hmacimportparamsname"><code>hmacImportParams.name</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_class-hmackeygenparams">Class: <code>HmacKeyGenParams</code></a>
<ul>
<li><a href="#all_webcrypto_hmackeygenparamshash"><code>hmacKeyGenParams.hash</code></a></li>
<li><a href="#all_webcrypto_hmackeygenparamslength"><code>hmacKeyGenParams.length</code></a></li>
<li><a href="#all_webcrypto_hmackeygenparamsname"><code>hmacKeyGenParams.name</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_class-pbkdf2params">Class: <code>Pbkdf2Params</code></a>
<ul>
<li><a href="#all_webcrypto_pbkdb2paramshash"><code>pbkdb2Params.hash</code></a></li>
<li><a href="#all_webcrypto_pbkdf2paramsiterations"><code>pbkdf2Params.iterations</code></a></li>
<li><a href="#all_webcrypto_pbkdf2paramsname"><code>pbkdf2Params.name</code></a></li>
<li><a href="#all_webcrypto_pbkdf2paramssalt"><code>pbkdf2Params.salt</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_class-rsahashedimportparams">Class: <code>RsaHashedImportParams</code></a>
<ul>
<li><a href="#all_webcrypto_rsahashedimportparamshash"><code>rsaHashedImportParams.hash</code></a></li>
<li><a href="#all_webcrypto_rsahashedimportparamsname"><code>rsaHashedImportParams.name</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_class-rsahashedkeygenparams">Class: <code>RsaHashedKeyGenParams</code></a>
<ul>
<li><a href="#all_webcrypto_rsahashedkeygenparamshash"><code>rsaHashedKeyGenParams.hash</code></a></li>
<li><a href="#all_webcrypto_rsahashedkeygenparamsmoduluslength"><code>rsaHashedKeyGenParams.modulusLength</code></a></li>
<li><a href="#all_webcrypto_rsahashedkeygenparamsname"><code>rsaHashedKeyGenParams.name</code></a></li>
<li><a href="#all_webcrypto_rsahashedkeygenparamspublicexponent"><code>rsaHashedKeyGenParams.publicExponent</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_class-rsaoaepparams">Class: <code>RsaOaepParams</code></a>
<ul>
<li><a href="#all_webcrypto_rsaoaepparamslabel"><code>rsaOaepParams.label</code></a></li>
<li><a href="#all_webcrypto_rsaoaepparamsname"><code>rsaOaepParams.name</code></a></li>
</ul>
</li>
<li><a href="#all_webcrypto_class-rsapssparams">Class: <code>RsaPssParams</code></a>
<ul>
<li><a href="#all_webcrypto_rsapssparamsname"><code>rsaPssParams.name</code></a></li>
<li><a href="#all_webcrypto_rsapssparamssaltlength"><code>rsaPssParams.saltLength</code></a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_webstreams_web-streams-api">Web Streams API</a></span>
<ul>
<li><a href="#all_webstreams_overview">Overview</a>
<ul>
<li><a href="#all_webstreams_example-readablestream">Example <code>ReadableStream</code></a></li>
</ul>
</li>
<li><a href="#all_webstreams_api">API</a>
<ul>
<li><a href="#all_webstreams_class-readablestream">Class: <code>ReadableStream</code></a>
<ul>
<li><a href="#all_webstreams_new-readablestreamunderlyingsource--strategy"><code>new ReadableStream([underlyingSource [, strategy]])</code></a></li>
<li><a href="#all_webstreams_readablestreamlocked"><code>readableStream.locked</code></a></li>
<li><a href="#all_webstreams_readablestreamcancelreason"><code>readableStream.cancel([reason])</code></a></li>
<li><a href="#all_webstreams_readablestreamgetreaderoptions"><code>readableStream.getReader([options])</code></a></li>
<li><a href="#all_webstreams_readablestreampipethroughtransform-options"><code>readableStream.pipeThrough(transform[, options])</code></a></li>
<li><a href="#all_webstreams_readablestreampipetodestination-options"><code>readableStream.pipeTo(destination[, options])</code></a></li>
<li><a href="#all_webstreams_readablestreamtee"><code>readableStream.tee()</code></a></li>
<li><a href="#all_webstreams_readablestreamvaluesoptions"><code>readableStream.values([options])</code></a></li>
<li><a href="#all_webstreams_async-iteration">Async Iteration</a></li>
<li><a href="#all_webstreams_transferring-with-postmessage">Transferring with <code>postMessage()</code></a></li>
</ul>
</li>
<li><a href="#all_webstreams_readablestreamfromiterable"><code>ReadableStream.from(iterable)</code></a></li>
<li><a href="#all_webstreams_class-readablestreamdefaultreader">Class: <code>ReadableStreamDefaultReader</code></a>
<ul>
<li><a href="#all_webstreams_new-readablestreamdefaultreaderstream"><code>new ReadableStreamDefaultReader(stream)</code></a></li>
<li><a href="#all_webstreams_readablestreamdefaultreadercancelreason"><code>readableStreamDefaultReader.cancel([reason])</code></a></li>
<li><a href="#all_webstreams_readablestreamdefaultreaderclosed"><code>readableStreamDefaultReader.closed</code></a></li>
<li><a href="#all_webstreams_readablestreamdefaultreaderread"><code>readableStreamDefaultReader.read()</code></a></li>
<li><a href="#all_webstreams_readablestreamdefaultreaderreleaselock"><code>readableStreamDefaultReader.releaseLock()</code></a></li>
</ul>
</li>
<li><a href="#all_webstreams_class-readablestreambyobreader">Class: <code>ReadableStreamBYOBReader</code></a>
<ul>
<li><a href="#all_webstreams_new-readablestreambyobreaderstream"><code>new ReadableStreamBYOBReader(stream)</code></a></li>
<li><a href="#all_webstreams_readablestreambyobreadercancelreason"><code>readableStreamBYOBReader.cancel([reason])</code></a></li>
<li><a href="#all_webstreams_readablestreambyobreaderclosed"><code>readableStreamBYOBReader.closed</code></a></li>
<li><a href="#all_webstreams_readablestreambyobreaderreadview-options"><code>readableStreamBYOBReader.read(view[, options])</code></a></li>
<li><a href="#all_webstreams_readablestreambyobreaderreleaselock"><code>readableStreamBYOBReader.releaseLock()</code></a></li>
</ul>
</li>
<li><a href="#all_webstreams_class-readablestreamdefaultcontroller">Class: <code>ReadableStreamDefaultController</code></a>
<ul>
<li><a href="#all_webstreams_readablestreamdefaultcontrollerclose"><code>readableStreamDefaultController.close()</code></a></li>
<li><a href="#all_webstreams_readablestreamdefaultcontrollerdesiredsize"><code>readableStreamDefaultController.desiredSize</code></a></li>
<li><a href="#all_webstreams_readablestreamdefaultcontrollerenqueuechunk"><code>readableStreamDefaultController.enqueue([chunk])</code></a></li>
<li><a href="#all_webstreams_readablestreamdefaultcontrollererrorerror"><code>readableStreamDefaultController.error([error])</code></a></li>
</ul>
</li>
<li><a href="#all_webstreams_class-readablebytestreamcontroller">Class: <code>ReadableByteStreamController</code></a>
<ul>
<li><a href="#all_webstreams_readablebytestreamcontrollerbyobrequest"><code>readableByteStreamController.byobRequest</code></a></li>
<li><a href="#all_webstreams_readablebytestreamcontrollerclose"><code>readableByteStreamController.close()</code></a></li>
<li><a href="#all_webstreams_readablebytestreamcontrollerdesiredsize"><code>readableByteStreamController.desiredSize</code></a></li>
<li><a href="#all_webstreams_readablebytestreamcontrollerenqueuechunk"><code>readableByteStreamController.enqueue(chunk)</code></a></li>
<li><a href="#all_webstreams_readablebytestreamcontrollererrorerror"><code>readableByteStreamController.error([error])</code></a></li>
</ul>
</li>
<li><a href="#all_webstreams_class-readablestreambyobrequest">Class: <code>ReadableStreamBYOBRequest</code></a>
<ul>
<li><a href="#all_webstreams_readablestreambyobrequestrespondbyteswritten"><code>readableStreamBYOBRequest.respond(bytesWritten)</code></a></li>
<li><a href="#all_webstreams_readablestreambyobrequestrespondwithnewviewview"><code>readableStreamBYOBRequest.respondWithNewView(view)</code></a></li>
<li><a href="#all_webstreams_readablestreambyobrequestview"><code>readableStreamBYOBRequest.view</code></a></li>
</ul>
</li>
<li><a href="#all_webstreams_class-writablestream">Class: <code>WritableStream</code></a>
<ul>
<li><a href="#all_webstreams_new-writablestreamunderlyingsink-strategy"><code>new WritableStream([underlyingSink[, strategy]])</code></a></li>
<li><a href="#all_webstreams_writablestreamabortreason"><code>writableStream.abort([reason])</code></a></li>
<li><a href="#all_webstreams_writablestreamclose"><code>writableStream.close()</code></a></li>
<li><a href="#all_webstreams_writablestreamgetwriter"><code>writableStream.getWriter()</code></a></li>
<li><a href="#all_webstreams_writablestreamlocked"><code>writableStream.locked</code></a></li>
<li><a href="#all_webstreams_transferring-with-postmessage_1">Transferring with postMessage()</a></li>
</ul>
</li>
<li><a href="#all_webstreams_class-writablestreamdefaultwriter">Class: <code>WritableStreamDefaultWriter</code></a>
<ul>
<li><a href="#all_webstreams_new-writablestreamdefaultwriterstream"><code>new WritableStreamDefaultWriter(stream)</code></a></li>
<li><a href="#all_webstreams_writablestreamdefaultwriterabortreason"><code>writableStreamDefaultWriter.abort([reason])</code></a></li>
<li><a href="#all_webstreams_writablestreamdefaultwriterclose"><code>writableStreamDefaultWriter.close()</code></a></li>
<li><a href="#all_webstreams_writablestreamdefaultwriterclosed"><code>writableStreamDefaultWriter.closed</code></a></li>
<li><a href="#all_webstreams_writablestreamdefaultwriterdesiredsize"><code>writableStreamDefaultWriter.desiredSize</code></a></li>
<li><a href="#all_webstreams_writablestreamdefaultwriterready"><code>writableStreamDefaultWriter.ready</code></a></li>
<li><a href="#all_webstreams_writablestreamdefaultwriterreleaselock"><code>writableStreamDefaultWriter.releaseLock()</code></a></li>
<li><a href="#all_webstreams_writablestreamdefaultwriterwritechunk"><code>writableStreamDefaultWriter.write([chunk])</code></a></li>
</ul>
</li>
<li><a href="#all_webstreams_class-writablestreamdefaultcontroller">Class: <code>WritableStreamDefaultController</code></a>
<ul>
<li><a href="#all_webstreams_writablestreamdefaultcontrollererrorerror"><code>writableStreamDefaultController.error([error])</code></a></li>
<li><a href="#all_webstreams_writablestreamdefaultcontrollersignal"><code>writableStreamDefaultController.signal</code></a></li>
</ul>
</li>
<li><a href="#all_webstreams_class-transformstream">Class: <code>TransformStream</code></a>
<ul>
<li><a href="#all_webstreams_new-transformstreamtransformer-writablestrategy-readablestrategy"><code>new TransformStream([transformer[, writableStrategy[, readableStrategy]]])</code></a></li>
<li><a href="#all_webstreams_transformstreamreadable"><code>transformStream.readable</code></a></li>
<li><a href="#all_webstreams_transformstreamwritable"><code>transformStream.writable</code></a></li>
<li><a href="#all_webstreams_transferring-with-postmessage_2">Transferring with postMessage()</a></li>
</ul>
</li>
<li><a href="#all_webstreams_class-transformstreamdefaultcontroller">Class: <code>TransformStreamDefaultController</code></a>
<ul>
<li><a href="#all_webstreams_transformstreamdefaultcontrollerdesiredsize"><code>transformStreamDefaultController.desiredSize</code></a></li>
<li><a href="#all_webstreams_transformstreamdefaultcontrollerenqueuechunk"><code>transformStreamDefaultController.enqueue([chunk])</code></a></li>
<li><a href="#all_webstreams_transformstreamdefaultcontrollererrorreason"><code>transformStreamDefaultController.error([reason])</code></a></li>
<li><a href="#all_webstreams_transformstreamdefaultcontrollerterminate"><code>transformStreamDefaultController.terminate()</code></a></li>
</ul>
</li>
<li><a href="#all_webstreams_class-bytelengthqueuingstrategy">Class: <code>ByteLengthQueuingStrategy</code></a>
<ul>
<li><a href="#all_webstreams_new-bytelengthqueuingstrategyinit"><code>new ByteLengthQueuingStrategy(init)</code></a></li>
<li><a href="#all_webstreams_bytelengthqueuingstrategyhighwatermark"><code>byteLengthQueuingStrategy.highWaterMark</code></a></li>
<li><a href="#all_webstreams_bytelengthqueuingstrategysize"><code>byteLengthQueuingStrategy.size</code></a></li>
</ul>
</li>
<li><a href="#all_webstreams_class-countqueuingstrategy">Class: <code>CountQueuingStrategy</code></a>
<ul>
<li><a href="#all_webstreams_new-countqueuingstrategyinit"><code>new CountQueuingStrategy(init)</code></a></li>
<li><a href="#all_webstreams_countqueuingstrategyhighwatermark"><code>countQueuingStrategy.highWaterMark</code></a></li>
<li><a href="#all_webstreams_countqueuingstrategysize"><code>countQueuingStrategy.size</code></a></li>
</ul>
</li>
<li><a href="#all_webstreams_class-textencoderstream">Class: <code>TextEncoderStream</code></a>
<ul>
<li><a href="#all_webstreams_new-textencoderstream"><code>new TextEncoderStream()</code></a></li>
<li><a href="#all_webstreams_textencoderstreamencoding"><code>textEncoderStream.encoding</code></a></li>
<li><a href="#all_webstreams_textencoderstreamreadable"><code>textEncoderStream.readable</code></a></li>
<li><a href="#all_webstreams_textencoderstreamwritable"><code>textEncoderStream.writable</code></a></li>
</ul>
</li>
<li><a href="#all_webstreams_class-textdecoderstream">Class: <code>TextDecoderStream</code></a>
<ul>
<li><a href="#all_webstreams_new-textdecoderstreamencoding-options"><code>new TextDecoderStream([encoding[, options]])</code></a></li>
<li><a href="#all_webstreams_textdecoderstreamencoding"><code>textDecoderStream.encoding</code></a></li>
<li><a href="#all_webstreams_textdecoderstreamfatal"><code>textDecoderStream.fatal</code></a></li>
<li><a href="#all_webstreams_textdecoderstreamignorebom"><code>textDecoderStream.ignoreBOM</code></a></li>
<li><a href="#all_webstreams_textdecoderstreamreadable"><code>textDecoderStream.readable</code></a></li>
<li><a href="#all_webstreams_textdecoderstreamwritable"><code>textDecoderStream.writable</code></a></li>
</ul>
</li>
<li><a href="#all_webstreams_class-compressionstream">Class: <code>CompressionStream</code></a>
<ul>
<li><a href="#all_webstreams_new-compressionstreamformat"><code>new CompressionStream(format)</code></a></li>
<li><a href="#all_webstreams_compressionstreamreadable"><code>compressionStream.readable</code></a></li>
<li><a href="#all_webstreams_compressionstreamwritable"><code>compressionStream.writable</code></a></li>
</ul>
</li>
<li><a href="#all_webstreams_class-decompressionstream">Class: <code>DecompressionStream</code></a>
<ul>
<li><a href="#all_webstreams_new-decompressionstreamformat"><code>new DecompressionStream(format)</code></a></li>
<li><a href="#all_webstreams_decompressionstreamreadable"><code>decompressionStream.readable</code></a></li>
<li><a href="#all_webstreams_decompressionstreamwritable"><code>decompressionStream.writable</code></a></li>
</ul>
</li>
<li><a href="#all_webstreams_utility-consumers">Utility Consumers</a>
<ul>
<li><a href="#all_webstreams_streamconsumersarraybufferstream"><code>streamConsumers.arrayBuffer(stream)</code></a></li>
<li><a href="#all_webstreams_streamconsumersblobstream"><code>streamConsumers.blob(stream)</code></a></li>
<li><a href="#all_webstreams_streamconsumersbufferstream"><code>streamConsumers.buffer(stream)</code></a></li>
<li><a href="#all_webstreams_streamconsumersjsonstream"><code>streamConsumers.json(stream)</code></a></li>
<li><a href="#all_webstreams_streamconsumerstextstream"><code>streamConsumers.text(stream)</code></a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_worker_threads_worker-threads">Worker threads</a></span>
<ul>
<li><a href="#all_worker_threads_workergetenvironmentdatakey"><code>worker.getEnvironmentData(key)</code></a></li>
<li><a href="#all_worker_threads_workerismainthread"><code>worker.isMainThread</code></a></li>
<li><a href="#all_worker_threads_workermarkasuntransferableobject"><code>worker.markAsUntransferable(object)</code></a></li>
<li><a href="#all_worker_threads_workermovemessageporttocontextport-contextifiedsandbox"><code>worker.moveMessagePortToContext(port, contextifiedSandbox)</code></a></li>
<li><a href="#all_worker_threads_workerparentport"><code>worker.parentPort</code></a></li>
<li><a href="#all_worker_threads_workerreceivemessageonportport"><code>worker.receiveMessageOnPort(port)</code></a></li>
<li><a href="#all_worker_threads_workerresourcelimits"><code>worker.resourceLimits</code></a></li>
<li><a href="#all_worker_threads_workershare_env"><code>worker.SHARE_ENV</code></a></li>
<li><a href="#all_worker_threads_workersetenvironmentdatakey-value"><code>worker.setEnvironmentData(key[, value])</code></a></li>
<li><a href="#all_worker_threads_workerthreadid"><code>worker.threadId</code></a></li>
<li><a href="#all_worker_threads_workerworkerdata"><code>worker.workerData</code></a></li>
<li><a href="#all_worker_threads_class-broadcastchannel-extends-eventtarget">Class: <code>BroadcastChannel extends EventTarget</code></a>
<ul>
<li><a href="#all_worker_threads_new-broadcastchannelname"><code>new BroadcastChannel(name)</code></a></li>
<li><a href="#all_worker_threads_broadcastchannelclose"><code>broadcastChannel.close()</code></a></li>
<li><a href="#all_worker_threads_broadcastchannelonmessage"><code>broadcastChannel.onmessage</code></a></li>
<li><a href="#all_worker_threads_broadcastchannelonmessageerror"><code>broadcastChannel.onmessageerror</code></a></li>
<li><a href="#all_worker_threads_broadcastchannelpostmessagemessage"><code>broadcastChannel.postMessage(message)</code></a></li>
<li><a href="#all_worker_threads_broadcastchannelref"><code>broadcastChannel.ref()</code></a></li>
<li><a href="#all_worker_threads_broadcastchannelunref"><code>broadcastChannel.unref()</code></a></li>
</ul>
</li>
<li><a href="#all_worker_threads_class-messagechannel">Class: <code>MessageChannel</code></a></li>
<li><a href="#all_worker_threads_class-messageport">Class: <code>MessagePort</code></a>
<ul>
<li><a href="#all_worker_threads_event-close">Event: <code>'close'</code></a></li>
<li><a href="#all_worker_threads_event-message">Event: <code>'message'</code></a></li>
<li><a href="#all_worker_threads_event-messageerror">Event: <code>'messageerror'</code></a></li>
<li><a href="#all_worker_threads_portclose"><code>port.close()</code></a></li>
<li><a href="#all_worker_threads_portpostmessagevalue-transferlist"><code>port.postMessage(value[, transferList])</code></a>
<ul>
<li><a href="#all_worker_threads_considerations-when-transferring-typedarrays-and-buffers">Considerations when transferring TypedArrays and Buffers</a></li>
<li><a href="#all_worker_threads_considerations-when-cloning-objects-with-prototypes-classes-and-accessors">Considerations when cloning objects with prototypes, classes, and accessors</a></li>
</ul>
</li>
<li><span class="stability_1"><a href="#all_worker_threads_porthasref"><code>port.hasRef()</code></a></span></li>
<li><a href="#all_worker_threads_portref"><code>port.ref()</code></a></li>
<li><a href="#all_worker_threads_portstart"><code>port.start()</code></a></li>
<li><a href="#all_worker_threads_portunref"><code>port.unref()</code></a></li>
</ul>
</li>
<li><a href="#all_worker_threads_class-worker">Class: <code>Worker</code></a>
<ul>
<li><a href="#all_worker_threads_new-workerfilename-options"><code>new Worker(filename[, options])</code></a></li>
<li><a href="#all_worker_threads_event-error">Event: <code>'error'</code></a></li>
<li><a href="#all_worker_threads_event-exit">Event: <code>'exit'</code></a></li>
<li><a href="#all_worker_threads_event-message_1">Event: <code>'message'</code></a></li>
<li><a href="#all_worker_threads_event-messageerror_1">Event: <code>'messageerror'</code></a></li>
<li><a href="#all_worker_threads_event-online">Event: <code>'online'</code></a></li>
<li><a href="#all_worker_threads_workergetheapsnapshotoptions"><code>worker.getHeapSnapshot([options])</code></a></li>
<li><a href="#all_worker_threads_workerperformance"><code>worker.performance</code></a>
<ul>
<li><a href="#all_worker_threads_performanceeventlooputilizationutilization1-utilization2"><code>performance.eventLoopUtilization([utilization1[, utilization2]])</code></a></li>
</ul>
</li>
<li><a href="#all_worker_threads_workerpostmessagevalue-transferlist"><code>worker.postMessage(value[, transferList])</code></a></li>
<li><a href="#all_worker_threads_workerref"><code>worker.ref()</code></a></li>
<li><a href="#all_worker_threads_workerresourcelimits_1"><code>worker.resourceLimits</code></a></li>
<li><a href="#all_worker_threads_workerstderr"><code>worker.stderr</code></a></li>
<li><a href="#all_worker_threads_workerstdin"><code>worker.stdin</code></a></li>
<li><a href="#all_worker_threads_workerstdout"><code>worker.stdout</code></a></li>
<li><a href="#all_worker_threads_workerterminate"><code>worker.terminate()</code></a></li>
<li><a href="#all_worker_threads_workerthreadid_1"><code>worker.threadId</code></a></li>
<li><a href="#all_worker_threads_workerunref"><code>worker.unref()</code></a></li>
</ul>
</li>
<li><a href="#all_worker_threads_notes">Notes</a>
<ul>
<li><a href="#all_worker_threads_synchronous-blocking-of-stdio">Synchronous blocking of stdio</a></li>
<li><a href="#all_worker_threads_launching-worker-threads-from-preload-scripts">Launching worker threads from preload scripts</a></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#all_zlib_zlib">Zlib</a></span>
<ul>
<li><a href="#all_zlib_threadpool-usage-and-performance-considerations">Threadpool usage and performance considerations</a></li>
<li><a href="#all_zlib_compressing-http-requests-and-responses">Compressing HTTP requests and responses</a></li>
<li><a href="#all_zlib_memory-usage-tuning">Memory usage tuning</a>
<ul>
<li><a href="#all_zlib_for-zlib-based-streams">For zlib-based streams</a></li>
<li><a href="#all_zlib_for-brotli-based-streams">For Brotli-based streams</a></li>
</ul>
</li>
<li><a href="#all_zlib_flushing">Flushing</a></li>
<li><a href="#all_zlib_constants">Constants</a>
<ul>
<li><a href="#all_zlib_zlib-constants">zlib constants</a></li>
<li><a href="#all_zlib_brotli-constants">Brotli constants</a>
<ul>
<li><a href="#all_zlib_flush-operations">Flush operations</a></li>
<li><a href="#all_zlib_compressor-options">Compressor options</a></li>
<li><a href="#all_zlib_decompressor-options">Decompressor options</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_zlib_class-options">Class: <code>Options</code></a></li>
<li><a href="#all_zlib_class-brotlioptions">Class: <code>BrotliOptions</code></a></li>
<li><a href="#all_zlib_class-zlibbrotlicompress">Class: <code>zlib.BrotliCompress</code></a></li>
<li><a href="#all_zlib_class-zlibbrotlidecompress">Class: <code>zlib.BrotliDecompress</code></a></li>
<li><a href="#all_zlib_class-zlibdeflate">Class: <code>zlib.Deflate</code></a></li>
<li><a href="#all_zlib_class-zlibdeflateraw">Class: <code>zlib.DeflateRaw</code></a></li>
<li><a href="#all_zlib_class-zlibgunzip">Class: <code>zlib.Gunzip</code></a></li>
<li><a href="#all_zlib_class-zlibgzip">Class: <code>zlib.Gzip</code></a></li>
<li><a href="#all_zlib_class-zlibinflate">Class: <code>zlib.Inflate</code></a></li>
<li><a href="#all_zlib_class-zlibinflateraw">Class: <code>zlib.InflateRaw</code></a></li>
<li><a href="#all_zlib_class-zlibunzip">Class: <code>zlib.Unzip</code></a></li>
<li><a href="#all_zlib_class-zlibzlibbase">Class: <code>zlib.ZlibBase</code></a>
<ul>
<li><span class="stability_0"><a href="#all_zlib_zlibbytesread"><code>zlib.bytesRead</code></a></span></li>
<li><a href="#all_zlib_zlibbyteswritten"><code>zlib.bytesWritten</code></a></li>
<li><a href="#all_zlib_zlibcrc32data-value"><code>zlib.crc32(data[, value])</code></a></li>
<li><a href="#all_zlib_zlibclosecallback"><code>zlib.close([callback])</code></a></li>
<li><a href="#all_zlib_zlibflushkind-callback"><code>zlib.flush([kind, ]callback)</code></a></li>
<li><a href="#all_zlib_zlibparamslevel-strategy-callback"><code>zlib.params(level, strategy, callback)</code></a></li>
<li><a href="#all_zlib_zlibreset"><code>zlib.reset()</code></a></li>
</ul>
</li>
<li><a href="#all_zlib_zlibconstants"><code>zlib.constants</code></a></li>
<li><a href="#all_zlib_zlibcreatebrotlicompressoptions"><code>zlib.createBrotliCompress([options])</code></a></li>
<li><a href="#all_zlib_zlibcreatebrotlidecompressoptions"><code>zlib.createBrotliDecompress([options])</code></a></li>
<li><a href="#all_zlib_zlibcreatedeflateoptions"><code>zlib.createDeflate([options])</code></a></li>
<li><a href="#all_zlib_zlibcreatedeflaterawoptions"><code>zlib.createDeflateRaw([options])</code></a></li>
<li><a href="#all_zlib_zlibcreategunzipoptions"><code>zlib.createGunzip([options])</code></a></li>
<li><a href="#all_zlib_zlibcreategzipoptions"><code>zlib.createGzip([options])</code></a></li>
<li><a href="#all_zlib_zlibcreateinflateoptions"><code>zlib.createInflate([options])</code></a></li>
<li><a href="#all_zlib_zlibcreateinflaterawoptions"><code>zlib.createInflateRaw([options])</code></a></li>
<li><a href="#all_zlib_zlibcreateunzipoptions"><code>zlib.createUnzip([options])</code></a></li>
<li><a href="#all_zlib_convenience-methods">Convenience methods</a>
<ul>
<li><a href="#all_zlib_zlibbrotlicompressbuffer-options-callback"><code>zlib.brotliCompress(buffer[, options], callback)</code></a></li>
<li><a href="#all_zlib_zlibbrotlicompresssyncbuffer-options"><code>zlib.brotliCompressSync(buffer[, options])</code></a></li>
<li><a href="#all_zlib_zlibbrotlidecompressbuffer-options-callback"><code>zlib.brotliDecompress(buffer[, options], callback)</code></a></li>
<li><a href="#all_zlib_zlibbrotlidecompresssyncbuffer-options"><code>zlib.brotliDecompressSync(buffer[, options])</code></a></li>
<li><a href="#all_zlib_zlibdeflatebuffer-options-callback"><code>zlib.deflate(buffer[, options], callback)</code></a></li>
<li><a href="#all_zlib_zlibdeflatesyncbuffer-options"><code>zlib.deflateSync(buffer[, options])</code></a></li>
<li><a href="#all_zlib_zlibdeflaterawbuffer-options-callback"><code>zlib.deflateRaw(buffer[, options], callback)</code></a></li>
<li><a href="#all_zlib_zlibdeflaterawsyncbuffer-options"><code>zlib.deflateRawSync(buffer[, options])</code></a></li>
<li><a href="#all_zlib_zlibgunzipbuffer-options-callback"><code>zlib.gunzip(buffer[, options], callback)</code></a></li>
<li><a href="#all_zlib_zlibgunzipsyncbuffer-options"><code>zlib.gunzipSync(buffer[, options])</code></a></li>
<li><a href="#all_zlib_zlibgzipbuffer-options-callback"><code>zlib.gzip(buffer[, options], callback)</code></a></li>
<li><a href="#all_zlib_zlibgzipsyncbuffer-options"><code>zlib.gzipSync(buffer[, options])</code></a></li>
<li><a href="#all_zlib_zlibinflatebuffer-options-callback"><code>zlib.inflate(buffer[, options], callback)</code></a></li>
<li><a href="#all_zlib_zlibinflatesyncbuffer-options"><code>zlib.inflateSync(buffer[, options])</code></a></li>
<li><a href="#all_zlib_zlibinflaterawbuffer-options-callback"><code>zlib.inflateRaw(buffer[, options], callback)</code></a></li>
<li><a href="#all_zlib_zlibinflaterawsyncbuffer-options"><code>zlib.inflateRawSync(buffer[, options])</code></a></li>
<li><a href="#all_zlib_zlibunzipbuffer-options-callback"><code>zlib.unzip(buffer[, options], callback)</code></a></li>
<li><a href="#all_zlib_zlibunzipsyncbuffer-options"><code>zlib.unzipSync(buffer[, options])</code></a></li>
</ul>
</li>
</ul>
</li>
</ul>
</details>


      <div role="main" id="apicontent">
        <section><h2>About this documentation<span><a class="mark" href="#all_documentation_about-this-documentation" id="all_documentation_about-this-documentation">#</a></span><a aria-hidden="true" class="legacy" id="documentation_about_this_documentation"></a></h2>


<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>
<section><h3>Contributing<span><a class="mark" href="#all_documentation_contributing" id="all_documentation_contributing">#</a></span><a aria-hidden="true" class="legacy" id="documentation_contributing"></a></h3>
<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/HEAD/CONTRIBUTING.md">the contributing guide</a> for directions on how to submit pull requests.</p>
</section><section><h3>Stability index<span><a class="mark" href="#all_documentation_stability-index" id="all_documentation_stability-index">#</a></span><a aria-hidden="true" class="legacy" id="documentation_stability_index"></a></h3>

<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 indexes are as follows:</p>
<p></p><div class="api_stability api_stability_0">Stability: 0 - Deprecated. The feature may emit warnings. Backward
compatibility is not guaranteed.</div><p></p>
<!-- separator -->
<p></p><div class="api_stability api_stability_1">Stability: 1 - Experimental. 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.<p>Experimental features are subdivided into stages:</p><ul>
<li>1.0 - Early development. Experimental features at this stage are unfinished
and subject to substantial change.</li>
<li>1.1 - Active development. Experimental features at this stage are nearing
minimum viability.</li>
<li>1.2 - Release candidate. Experimental features at this stage are hopefully
ready to become stable. No further breaking changes are anticipated but may
still occur in response to user feedback. We encourage user testing and
feedback so that we can know that this feature is ready to be marked as
stable.</li>
</ul></div><p></p>
<!-- separator -->
<p></p><div class="api_stability api_stability_2">Stability: 2 - Stable. Compatibility with the npm ecosystem is a high
priority.</div><p></p>
<!-- separator -->
<p></p><div class="api_stability api_stability_3">Stability: 3 - Legacy. Although this feature is unlikely to be removed and is
still covered by semantic versioning guarantees, it is no longer actively
maintained, and other alternatives are available.</div><p></p>
<p>Features are marked as legacy rather than being deprecated if their use does no
harm, and they are widely relied upon within the npm ecosystem. Bugs found in
legacy features are unlikely to be fixed.</p>
<p>Use caution when making use of Experimental features, particularly when
authoring libraries. Users may not be aware that experimental features are being
used. Bugs or behavior changes may surprise 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="#all_process_event-warning">warning</a>.</p>
</section><section><h3>Stability overview<span><a class="mark" href="#all_documentation_stability-overview" id="all_documentation_stability-overview">#</a></span><a aria-hidden="true" class="legacy" id="documentation_stability_overview"></a></h3>
<!-- STABILITY_OVERVIEW_SLOT_BEGIN -->
<!-- STABILITY_OVERVIEW_SLOT_END -->
</section><section><h3>JSON output<span><a class="mark" href="#all_documentation_json-output" id="all_documentation_json-output">#</a></span><a aria-hidden="true" class="legacy" id="documentation_json_output"></a></h3>
<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>
</section><section><h3>System calls and man pages<span><a class="mark" href="#all_documentation_system-calls-and-man-pages" id="all_documentation_system-calls-and-man-pages">#</a></span><a aria-hidden="true" class="legacy" id="documentation_system_calls_and_man_pages"></a></h3>
<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></section>
        </section>
<section><h2>Usage and example<span><a class="mark" href="#all_synopsis_usage-and-example" id="all_synopsis_usage-and-example">#</a></span><a aria-hidden="true" class="legacy" id="synopsis_usage_and_example"></a></h2>
<section><h3>Usage<span><a class="mark" href="#all_synopsis_usage" id="all_synopsis_usage">#</a></span><a aria-hidden="true" class="legacy" id="synopsis_usage"></a></h3>


<p><code>node [options] [V8 options] [script.js | -e "script" | - ] [arguments]</code></p>
<p>Please see the <a href="#all_cli_options">Command-line options</a> document for more information.</p>
</section><section><h3>Example<span><a class="mark" href="#all_synopsis_example" id="all_synopsis_example">#</a></span><a aria-hidden="true" class="legacy" id="synopsis_example"></a></h3>
<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/">Installing Node.js via package manager</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-bash"><span class="hljs-built_in">mkdir</span> ~/projects
<span class="hljs-built_in">cd</span> ~/projects</code> <button class="copy-button">copy</button></pre>
<p>Windows CMD:</p>
<pre><code class="language-powershell">mkdir %USERPROFILE%\projects
<span class="hljs-built_in">cd</span> %USERPROFILE%\projects</code> <button class="copy-button">copy</button></pre>
<p>Windows PowerShell:</p>
<pre><code class="language-powershell">mkdir <span class="hljs-variable">$env:USERPROFILE</span>\projects
<span class="hljs-built_in">cd</span> <span class="hljs-variable">$env:USERPROFILE</span>\projects</code> <button class="copy-button">copy</button></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"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);

<span class="hljs-keyword">const</span> hostname = <span class="hljs-string">'127.0.0.1'</span>;
<span class="hljs-keyword">const</span> port = <span class="hljs-number">3000</span>;

<span class="hljs-keyword">const</span> server = http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
  res.<span class="hljs-property">statusCode</span> = <span class="hljs-number">200</span>;
  res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Content-Type'</span>, <span class="hljs-string">'text/plain'</span>);
  res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'Hello, World!\n'</span>);
});

server.<span class="hljs-title function_">listen</span>(port, hostname, <span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Server running at http://<span class="hljs-subst">${hostname}</span>:<span class="hljs-subst">${port}</span>/`</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>Save the file. Then, in the terminal window, to run the <code>hello-world.js</code> file,
enter:</p>
<pre><code class="language-bash">node hello-world.js</code> <button class="copy-button">copy</button></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> <button class="copy-button">copy</button></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></section>
        </section>
<section><h2>Assert<span><a class="mark" href="#all_assert_assert" id="all_assert_assert">#</a></span><a aria-hidden="true" class="legacy" id="assert_assert"></a></h2>

<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/assert.js">lib/assert.js</a></p>
<p>The <code>node:assert</code> module provides a set of assertion functions for verifying
invariants.</p>
<section><h3>Strict assertion mode<span><a class="mark" href="#all_assert_strict-assertion-mode" id="all_assert_strict-assertion-mode">#</a></span><a aria-hidden="true" class="legacy" id="assert_strict_assertion_mode"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>Exposed as <code>require('node:assert/strict')</code>.</p></td></tr>
<tr><td>v13.9.0, 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 meaning 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="#all_assert_assertdeepequalactual-expected-message"><code>assert.deepEqual()</code></a> will behave like
<a href="#all_assert_assertdeepstrictequalactual-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 class="with-47-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { strict <span class="hljs-keyword">as</span> assert } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>).<span class="hljs-property">strict</span>;</code><button class="copy-button">copy</button></pre>

<pre class="with-45-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);</code><button class="copy-button">copy</button></pre>
<p>Example error diff:</p>

<pre class="with-47-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { strict <span class="hljs-keyword">as</span> assert } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;

assert.<span class="hljs-title function_">deepEqual</span>([[[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]], <span class="hljs-number">4</span>, <span class="hljs-number">5</span>], [[[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-string">'3'</span>]], <span class="hljs-number">4</span>, <span class="hljs-number">5</span>]);
<span class="hljs-comment">// AssertionError: Expected inputs to be strictly deep-equal:</span>
<span class="hljs-comment">// + actual - expected ... Lines skipped</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">//   [</span>
<span class="hljs-comment">//     [</span>
<span class="hljs-comment">// ...</span>
<span class="hljs-comment">//       2,</span>
<span class="hljs-comment">// +     3</span>
<span class="hljs-comment">// -     '3'</span>
<span class="hljs-comment">//     ],</span>
<span class="hljs-comment">// ...</span>
<span class="hljs-comment">//     5</span>
<span class="hljs-comment">//   ]</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);

assert.<span class="hljs-title function_">deepEqual</span>([[[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]], <span class="hljs-number">4</span>, <span class="hljs-number">5</span>], [[[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-string">'3'</span>]], <span class="hljs-number">4</span>, <span class="hljs-number">5</span>]);
<span class="hljs-comment">// AssertionError: Expected inputs to be strictly deep-equal:</span>
<span class="hljs-comment">// + actual - expected ... Lines skipped</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">//   [</span>
<span class="hljs-comment">//     [</span>
<span class="hljs-comment">// ...</span>
<span class="hljs-comment">//       2,</span>
<span class="hljs-comment">// +     3</span>
<span class="hljs-comment">// -     '3'</span>
<span class="hljs-comment">//     ],</span>
<span class="hljs-comment">// ...</span>
<span class="hljs-comment">//     5</span>
<span class="hljs-comment">//   ]</span></code><button class="copy-button">copy</button></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="#all_tty_writestreamgetcolordepthenv"><code>getColorDepth()</code></a> documentation.</p>
</section><section><h3>Legacy assertion mode<span><a class="mark" href="#all_assert_legacy-assertion-mode" id="all_assert_legacy-assertion-mode">#</a></span><a aria-hidden="true" class="legacy" id="assert_legacy_assertion_mode"></a></h3>
<p>Legacy assertion mode uses the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality"><code>==</code> operator</a> in:</p>
<ul>
<li><a href="#all_assert_assertdeepequalactual-expected-message"><code>assert.deepEqual()</code></a></li>
<li><a href="#all_assert_assertequalactual-expected-message"><code>assert.equal()</code></a></li>
<li><a href="#all_assert_assertnotdeepequalactual-expected-message"><code>assert.notDeepEqual()</code></a></li>
<li><a href="#all_assert_assertnotequalactual-expected-message"><code>assert.notEqual()</code></a></li>
</ul>
<p>To use legacy assertion mode:</p>

<pre class="with-38-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);</code><button class="copy-button">copy</button></pre>
<p>Legacy assertion mode may have surprising results, especially when using
<a href="#all_assert_assertdeepequalactual-expected-message"><code>assert.deepEqual()</code></a>:</p>
<pre><code class="language-js cjs"><span class="hljs-comment">// WARNING: This does not throw an AssertionError in legacy assertion mode!</span>
assert.<span class="hljs-title function_">deepEqual</span>(<span class="hljs-regexp">/a/gi</span>, <span class="hljs-keyword">new</span> <span class="hljs-title class_">Date</span>());</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Class: assert.AssertionError<a class="srclink" href="https://github.com/nodejs/node/blob/7eebd17fa2c1e48e4534f3a69560388fab2f2c07/lib/assert.js#L143">[src]</a><span><a class="mark" href="#all_assert_class-assertassertionerror" id="all_assert_class-assertassertionerror">#</a></span><a aria-hidden="true" class="legacy" id="assert_class_assert_assertionerror"></a></h3>
<ul>
<li>Extends: <a href="#all_errors_class-error" class="type">&#x3C;errors.Error></a></li>
</ul>
<p>Indicates the failure of an assertion. All errors thrown by the <code>node:assert</code>
module will be instances of the <code>AssertionError</code> class.</p>
<h4><code>new assert.AssertionError(options)</code><span><a class="mark" href="#all_assert_new-assertassertionerroroptions" id="all_assert_new-assertassertionerroroptions">#</a></span><a aria-hidden="true" class="legacy" id="assert_new_assert_assertionerror_options"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.21</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>
<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="#all_assert_assertstrictequalactual-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="#all_assert_assertstrictequalactual-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 class="with-38-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;

<span class="hljs-comment">// Generate an AssertionError to compare the error message later:</span>
<span class="hljs-keyword">const</span> { message } = <span class="hljs-keyword">new</span> assert.<span class="hljs-title class_">AssertionError</span>({
  <span class="hljs-attr">actual</span>: <span class="hljs-number">1</span>,
  <span class="hljs-attr">expected</span>: <span class="hljs-number">2</span>,
  <span class="hljs-attr">operator</span>: <span class="hljs-string">'strictEqual'</span>,
});

<span class="hljs-comment">// Verify error output:</span>
<span class="hljs-keyword">try</span> {
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-title function_">assert</span>(err <span class="hljs-keyword">instanceof</span> assert.<span class="hljs-property">AssertionError</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(err.<span class="hljs-property">message</span>, message);
  assert.<span class="hljs-title function_">strictEqual</span>(err.<span class="hljs-property">name</span>, <span class="hljs-string">'AssertionError'</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(err.<span class="hljs-property">actual</span>, <span class="hljs-number">1</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(err.<span class="hljs-property">expected</span>, <span class="hljs-number">2</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(err.<span class="hljs-property">code</span>, <span class="hljs-string">'ERR_ASSERTION'</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(err.<span class="hljs-property">operator</span>, <span class="hljs-string">'strictEqual'</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(err.<span class="hljs-property">generatedMessage</span>, <span class="hljs-literal">true</span>);
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);

<span class="hljs-comment">// Generate an AssertionError to compare the error message later:</span>
<span class="hljs-keyword">const</span> { message } = <span class="hljs-keyword">new</span> assert.<span class="hljs-title class_">AssertionError</span>({
  <span class="hljs-attr">actual</span>: <span class="hljs-number">1</span>,
  <span class="hljs-attr">expected</span>: <span class="hljs-number">2</span>,
  <span class="hljs-attr">operator</span>: <span class="hljs-string">'strictEqual'</span>,
});

<span class="hljs-comment">// Verify error output:</span>
<span class="hljs-keyword">try</span> {
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-title function_">assert</span>(err <span class="hljs-keyword">instanceof</span> assert.<span class="hljs-property">AssertionError</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(err.<span class="hljs-property">message</span>, message);
  assert.<span class="hljs-title function_">strictEqual</span>(err.<span class="hljs-property">name</span>, <span class="hljs-string">'AssertionError'</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(err.<span class="hljs-property">actual</span>, <span class="hljs-number">1</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(err.<span class="hljs-property">expected</span>, <span class="hljs-number">2</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(err.<span class="hljs-property">code</span>, <span class="hljs-string">'ERR_ASSERTION'</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(err.<span class="hljs-property">operator</span>, <span class="hljs-string">'strictEqual'</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(err.<span class="hljs-property">generatedMessage</span>, <span class="hljs-literal">true</span>);
}</code><button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>assert.CallTracker</code><span><a class="mark" href="#all_assert_class-assertcalltracker" id="all_assert_class-assertcalltracker">#</a></span><a aria-hidden="true" class="legacy" id="assert_class_assert_calltracker"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.1.0</td>
<td><p>the <code>assert.CallTracker</code> class has been deprecated and will be removed in a future version.</p></td></tr>
<tr><td>v14.2.0, v12.19.0</td>
<td><p><span>Added in: v14.2.0, v12.19.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated</div><p></p>
<p>This feature is deprecated and will be removed in a future version.
Please consider using alternatives such as the
<a href="#all_test_mocking"><code>mock</code></a> helper function.</p>
<h4><code>new assert.CallTracker()</code><span><a class="mark" href="#all_assert_new-assertcalltracker" id="all_assert_new-assertcalltracker">#</a></span><a aria-hidden="true" class="legacy" id="assert_new_assert_calltracker"></a></h4>
<div class="api_metadata">
<span>Added in: v14.2.0, v12.19.0</span>
</div>
<p>Creates a new <a href="#all_assert_class-assertcalltracker"><code>CallTracker</code></a> object which can be used to track if functions
were called a specific number of times. The <code>tracker.verify()</code> must be called
for the verification to take place. The usual pattern would be to call it in a
<a href="#all_process_event-exit"><code>process.on('exit')</code></a> handler.</p>

<pre class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-keyword">const</span> tracker = <span class="hljs-keyword">new</span> assert.<span class="hljs-title class_">CallTracker</span>();

<span class="hljs-keyword">function</span> <span class="hljs-title function_">func</span>(<span class="hljs-params"></span>) {}

<span class="hljs-comment">// callsfunc() must be called exactly 1 time before tracker.verify().</span>
<span class="hljs-keyword">const</span> callsfunc = tracker.<span class="hljs-title function_">calls</span>(func, <span class="hljs-number">1</span>);

<span class="hljs-title function_">callsfunc</span>();

<span class="hljs-comment">// Calls tracker.verify() and verifies if all tracker.calls() functions have</span>
<span class="hljs-comment">// been called exact times.</span>
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">() =></span> {
  tracker.<span class="hljs-title function_">verify</span>();
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-keyword">const</span> tracker = <span class="hljs-keyword">new</span> assert.<span class="hljs-title class_">CallTracker</span>();

<span class="hljs-keyword">function</span> <span class="hljs-title function_">func</span>(<span class="hljs-params"></span>) {}

<span class="hljs-comment">// callsfunc() must be called exactly 1 time before tracker.verify().</span>
<span class="hljs-keyword">const</span> callsfunc = tracker.<span class="hljs-title function_">calls</span>(func, <span class="hljs-number">1</span>);

<span class="hljs-title function_">callsfunc</span>();

<span class="hljs-comment">// Calls tracker.verify() and verifies if all tracker.calls() functions have</span>
<span class="hljs-comment">// been called exact times.</span>
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">() =></span> {
  tracker.<span class="hljs-title function_">verify</span>();
});</code><button class="copy-button">copy</button></pre>
<h4><code>tracker.calls([fn][, exact])</code><span><a class="mark" href="#all_assert_trackercallsfn-exact" id="all_assert_trackercallsfn-exact">#</a></span><a aria-hidden="true" class="legacy" id="assert_tracker_calls_fn_exact"></a></h4>
<div class="api_metadata">
<span>Added in: v14.2.0, v12.19.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> <strong>Default:</strong> A no-op function.</li>
<li><code>exact</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>1</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> A function that wraps <code>fn</code>.</li>
</ul>
<p>The wrapper function is expected to be called exactly <code>exact</code> times. If the
function has not been called exactly <code>exact</code> times when
<a href="#all_assert_trackerverify"><code>tracker.verify()</code></a> is called, then <a href="#all_assert_trackerverify"><code>tracker.verify()</code></a> will throw an
error.</p>

<pre class="with-38-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;

<span class="hljs-comment">// Creates call tracker.</span>
<span class="hljs-keyword">const</span> tracker = <span class="hljs-keyword">new</span> assert.<span class="hljs-title class_">CallTracker</span>();

<span class="hljs-keyword">function</span> <span class="hljs-title function_">func</span>(<span class="hljs-params"></span>) {}

<span class="hljs-comment">// Returns a function that wraps func() that must be called exact times</span>
<span class="hljs-comment">// before tracker.verify().</span>
<span class="hljs-keyword">const</span> callsfunc = tracker.<span class="hljs-title function_">calls</span>(func);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);

<span class="hljs-comment">// Creates call tracker.</span>
<span class="hljs-keyword">const</span> tracker = <span class="hljs-keyword">new</span> assert.<span class="hljs-title class_">CallTracker</span>();

<span class="hljs-keyword">function</span> <span class="hljs-title function_">func</span>(<span class="hljs-params"></span>) {}

<span class="hljs-comment">// Returns a function that wraps func() that must be called exact times</span>
<span class="hljs-comment">// before tracker.verify().</span>
<span class="hljs-keyword">const</span> callsfunc = tracker.<span class="hljs-title function_">calls</span>(func);</code><button class="copy-button">copy</button></pre>
<h4><code>tracker.getCalls(fn)</code><span><a class="mark" href="#all_assert_trackergetcallsfn" id="all_assert_trackergetcallsfn">#</a></span><a aria-hidden="true" class="legacy" id="assert_tracker_getcalls_fn"></a></h4>
<div class="api_metadata">
<span>Added in: v18.8.0, v16.18.0</span>
</div>
<ul>
<li>
<p><code>fn</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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type">&#x3C;Array></a> An array with all the calls to a tracked function.</p>
</li>
<li>
<p>Object <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>thisArg</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
<li><code>arguments</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type">&#x3C;Array></a> the arguments passed to the tracked function</li>
</ul>
</li>
</ul>

<pre class="with-38-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;

<span class="hljs-keyword">const</span> tracker = <span class="hljs-keyword">new</span> assert.<span class="hljs-title class_">CallTracker</span>();

<span class="hljs-keyword">function</span> <span class="hljs-title function_">func</span>(<span class="hljs-params"></span>) {}
<span class="hljs-keyword">const</span> callsfunc = tracker.<span class="hljs-title function_">calls</span>(func);
<span class="hljs-title function_">callsfunc</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>);

assert.<span class="hljs-title function_">deepStrictEqual</span>(tracker.<span class="hljs-title function_">getCalls</span>(callsfunc),
                       [{ <span class="hljs-attr">thisArg</span>: <span class="hljs-literal">undefined</span>, <span class="hljs-attr">arguments</span>: [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>] }]);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);

<span class="hljs-comment">// Creates call tracker.</span>
<span class="hljs-keyword">const</span> tracker = <span class="hljs-keyword">new</span> assert.<span class="hljs-title class_">CallTracker</span>();

<span class="hljs-keyword">function</span> <span class="hljs-title function_">func</span>(<span class="hljs-params"></span>) {}
<span class="hljs-keyword">const</span> callsfunc = tracker.<span class="hljs-title function_">calls</span>(func);
<span class="hljs-title function_">callsfunc</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>);

assert.<span class="hljs-title function_">deepStrictEqual</span>(tracker.<span class="hljs-title function_">getCalls</span>(callsfunc),
                       [{ <span class="hljs-attr">thisArg</span>: <span class="hljs-literal">undefined</span>, <span class="hljs-attr">arguments</span>: [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>] }]);</code><button class="copy-button">copy</button></pre>
<h4><code>tracker.report()</code><span><a class="mark" href="#all_assert_trackerreport" id="all_assert_trackerreport">#</a></span><a aria-hidden="true" class="legacy" id="assert_tracker_report"></a></h4>
<div class="api_metadata">
<span>Added in: v14.2.0, v12.19.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> An array of objects containing information about the wrapper
functions returned by <a href="#all_assert_trackercallsfn-exact"><code>tracker.calls()</code></a>.</li>
<li>Object <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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>
<li><code>actual</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The actual number of times the function was called.</li>
<li><code>expected</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The number of times the function was expected to be
called.</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 name of the function that is wrapped.</li>
<li><code>stack</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> A stack trace of the function.</li>
</ul>
</li>
</ul>
<p>The arrays contains information about the expected and actual number of calls of
the functions that have not been called the expected number of times.</p>

<pre class="with-38-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;

<span class="hljs-comment">// Creates call tracker.</span>
<span class="hljs-keyword">const</span> tracker = <span class="hljs-keyword">new</span> assert.<span class="hljs-title class_">CallTracker</span>();

<span class="hljs-keyword">function</span> <span class="hljs-title function_">func</span>(<span class="hljs-params"></span>) {}

<span class="hljs-comment">// Returns a function that wraps func() that must be called exact times</span>
<span class="hljs-comment">// before tracker.verify().</span>
<span class="hljs-keyword">const</span> callsfunc = tracker.<span class="hljs-title function_">calls</span>(func, <span class="hljs-number">2</span>);

<span class="hljs-comment">// Returns an array containing information on callsfunc()</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(tracker.<span class="hljs-title function_">report</span>());
<span class="hljs-comment">// [</span>
<span class="hljs-comment">//  {</span>
<span class="hljs-comment">//    message: 'Expected the func function to be executed 2 time(s) but was</span>
<span class="hljs-comment">//    executed 0 time(s).',</span>
<span class="hljs-comment">//    actual: 0,</span>
<span class="hljs-comment">//    expected: 2,</span>
<span class="hljs-comment">//    operator: 'func',</span>
<span class="hljs-comment">//    stack: stack trace</span>
<span class="hljs-comment">//  }</span>
<span class="hljs-comment">// ]</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);

<span class="hljs-comment">// Creates call tracker.</span>
<span class="hljs-keyword">const</span> tracker = <span class="hljs-keyword">new</span> assert.<span class="hljs-title class_">CallTracker</span>();

<span class="hljs-keyword">function</span> <span class="hljs-title function_">func</span>(<span class="hljs-params"></span>) {}

<span class="hljs-comment">// Returns a function that wraps func() that must be called exact times</span>
<span class="hljs-comment">// before tracker.verify().</span>
<span class="hljs-keyword">const</span> callsfunc = tracker.<span class="hljs-title function_">calls</span>(func, <span class="hljs-number">2</span>);

<span class="hljs-comment">// Returns an array containing information on callsfunc()</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(tracker.<span class="hljs-title function_">report</span>());
<span class="hljs-comment">// [</span>
<span class="hljs-comment">//  {</span>
<span class="hljs-comment">//    message: 'Expected the func function to be executed 2 time(s) but was</span>
<span class="hljs-comment">//    executed 0 time(s).',</span>
<span class="hljs-comment">//    actual: 0,</span>
<span class="hljs-comment">//    expected: 2,</span>
<span class="hljs-comment">//    operator: 'func',</span>
<span class="hljs-comment">//    stack: stack trace</span>
<span class="hljs-comment">//  }</span>
<span class="hljs-comment">// ]</span></code><button class="copy-button">copy</button></pre>
<h4><code>tracker.reset([fn])</code><span><a class="mark" href="#all_assert_trackerresetfn" id="all_assert_trackerresetfn">#</a></span><a aria-hidden="true" class="legacy" id="assert_tracker_reset_fn"></a></h4>
<div class="api_metadata">
<span>Added in: v18.8.0, v16.18.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 tracked function to reset.</li>
</ul>
<p>Reset calls of the call tracker.
If a tracked function is passed as an argument, the calls will be reset for it.
If no arguments are passed, all tracked functions will be reset.</p>

<pre class="with-38-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;

<span class="hljs-keyword">const</span> tracker = <span class="hljs-keyword">new</span> assert.<span class="hljs-title class_">CallTracker</span>();

<span class="hljs-keyword">function</span> <span class="hljs-title function_">func</span>(<span class="hljs-params"></span>) {}
<span class="hljs-keyword">const</span> callsfunc = tracker.<span class="hljs-title function_">calls</span>(func);

<span class="hljs-title function_">callsfunc</span>();
<span class="hljs-comment">// Tracker was called once</span>
assert.<span class="hljs-title function_">strictEqual</span>(tracker.<span class="hljs-title function_">getCalls</span>(callsfunc).<span class="hljs-property">length</span>, <span class="hljs-number">1</span>);

tracker.<span class="hljs-title function_">reset</span>(callsfunc);
assert.<span class="hljs-title function_">strictEqual</span>(tracker.<span class="hljs-title function_">getCalls</span>(callsfunc).<span class="hljs-property">length</span>, <span class="hljs-number">0</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);

<span class="hljs-keyword">const</span> tracker = <span class="hljs-keyword">new</span> assert.<span class="hljs-title class_">CallTracker</span>();

<span class="hljs-keyword">function</span> <span class="hljs-title function_">func</span>(<span class="hljs-params"></span>) {}
<span class="hljs-keyword">const</span> callsfunc = tracker.<span class="hljs-title function_">calls</span>(func);

<span class="hljs-title function_">callsfunc</span>();
<span class="hljs-comment">// Tracker was called once</span>
assert.<span class="hljs-title function_">strictEqual</span>(tracker.<span class="hljs-title function_">getCalls</span>(callsfunc).<span class="hljs-property">length</span>, <span class="hljs-number">1</span>);

tracker.<span class="hljs-title function_">reset</span>(callsfunc);
assert.<span class="hljs-title function_">strictEqual</span>(tracker.<span class="hljs-title function_">getCalls</span>(callsfunc).<span class="hljs-property">length</span>, <span class="hljs-number">0</span>);</code><button class="copy-button">copy</button></pre>
<h4><code>tracker.verify()</code><span><a class="mark" href="#all_assert_trackerverify" id="all_assert_trackerverify">#</a></span><a aria-hidden="true" class="legacy" id="assert_tracker_verify"></a></h4>
<div class="api_metadata">
<span>Added in: v14.2.0, v12.19.0</span>
</div>
<p>Iterates through the list of functions passed to
<a href="#all_assert_trackercallsfn-exact"><code>tracker.calls()</code></a> and will throw an error for functions that
have not been called the expected number of times.</p>

<pre class="with-38-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;

<span class="hljs-comment">// Creates call tracker.</span>
<span class="hljs-keyword">const</span> tracker = <span class="hljs-keyword">new</span> assert.<span class="hljs-title class_">CallTracker</span>();

<span class="hljs-keyword">function</span> <span class="hljs-title function_">func</span>(<span class="hljs-params"></span>) {}

<span class="hljs-comment">// Returns a function that wraps func() that must be called exact times</span>
<span class="hljs-comment">// before tracker.verify().</span>
<span class="hljs-keyword">const</span> callsfunc = tracker.<span class="hljs-title function_">calls</span>(func, <span class="hljs-number">2</span>);

<span class="hljs-title function_">callsfunc</span>();

<span class="hljs-comment">// Will throw an error since callsfunc() was only called once.</span>
tracker.<span class="hljs-title function_">verify</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);

<span class="hljs-comment">// Creates call tracker.</span>
<span class="hljs-keyword">const</span> tracker = <span class="hljs-keyword">new</span> assert.<span class="hljs-title class_">CallTracker</span>();

<span class="hljs-keyword">function</span> <span class="hljs-title function_">func</span>(<span class="hljs-params"></span>) {}

<span class="hljs-comment">// Returns a function that wraps func() that must be called exact times</span>
<span class="hljs-comment">// before tracker.verify().</span>
<span class="hljs-keyword">const</span> callsfunc = tracker.<span class="hljs-title function_">calls</span>(func, <span class="hljs-number">2</span>);

<span class="hljs-title function_">callsfunc</span>();

<span class="hljs-comment">// Will throw an error since callsfunc() was only called once.</span>
tracker.<span class="hljs-title function_">verify</span>();</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>assert(value[, message])</code><span><a class="mark" href="#all_assert_assertvalue-message" id="all_assert_assertvalue-message">#</a></span><a aria-hidden="true" class="legacy" id="assert_assert_value_message"></a></h3>
<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="#all_assert_assertokvalue-message"><code>assert.ok()</code></a>.</p>
</section><section><h3><code>assert.deepEqual(actual, expected[, message])</code><span><a class="mark" href="#all_assert_assertdeepequalactual-expected-message" id="all_assert_assertdeepequalactual-expected-message">#</a></span><a aria-hidden="true" class="legacy" id="assert_assert_deepequal_actual_expected_message"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.15.0</td>
<td><p>Error cause and errors properties are now compared as well.</p></td></tr>
<tr><td>v18.0.0</td>
<td><p>Regular expressions lastIndex property is now compared as well.</p></td></tr>
<tr><td>v16.0.0, v14.18.0</td>
<td><p>In Legacy assertion mode, changed status from Deprecated to Legacy.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>NaN is now treated as being identical if both sides are NaN.</p></td></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="#all_assert_assertdeepstrictequalactual-expected-message"><code>assert.deepStrictEqual()</code></a>.</p>
<p><strong>Legacy assertion mode</strong></p>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy: Use <a href="#all_assert_assertdeepstrictequalactual-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="#all_assert_assertdeepstrictequalactual-expected-message"><code>assert.deepStrictEqual()</code></a> instead. <a href="#all_assert_assertdeepequalactual-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>
<h4>Comparison details<span><a class="mark" href="#all_assert_comparison-details" id="all_assert_comparison-details">#</a></span><a aria-hidden="true" class="legacy" id="assert_comparison_details"></a></h4>
<ul>
<li>Primitive values are compared with the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality"><code>==</code> operator</a>,
with the exception of <code>NaN</code>. It is treated as being identical in case
both sides are <code>NaN</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="#all_errors_class-error"><code>Error</code></a> names, messages, causes, and errors 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>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions"><code>RegExp</code></a> lastIndex, flags, and source are always compared, even if these
are not enumerable properties.</li>
</ul>
<p>The following example does not throw an <a href="#all_assert_class-assertassertionerror"><code>AssertionError</code></a> because the
primitives are compared using the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality"><code>==</code> operator</a>.</p>

<pre class="with-50-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-comment">// WARNING: This does not throw an AssertionError!</span>

assert.<span class="hljs-title function_">deepEqual</span>(<span class="hljs-string">'+00000000'</span>, <span class="hljs-literal">false</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-comment">// WARNING: This does not throw an AssertionError!</span>

assert.<span class="hljs-title function_">deepEqual</span>(<span class="hljs-string">'+00000000'</span>, <span class="hljs-literal">false</span>);</code><button class="copy-button">copy</button></pre>
<p>"Deep" equality means that the enumerable "own" properties of child objects
are evaluated also:</p>

<pre class="with-38-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;

<span class="hljs-keyword">const</span> obj1 = {
  <span class="hljs-attr">a</span>: {
    <span class="hljs-attr">b</span>: <span class="hljs-number">1</span>,
  },
};
<span class="hljs-keyword">const</span> obj2 = {
  <span class="hljs-attr">a</span>: {
    <span class="hljs-attr">b</span>: <span class="hljs-number">2</span>,
  },
};
<span class="hljs-keyword">const</span> obj3 = {
  <span class="hljs-attr">a</span>: {
    <span class="hljs-attr">b</span>: <span class="hljs-number">1</span>,
  },
};
<span class="hljs-keyword">const</span> obj4 = { <span class="hljs-attr">__proto__</span>: obj1 };

assert.<span class="hljs-title function_">deepEqual</span>(obj1, obj1);
<span class="hljs-comment">// OK</span>

<span class="hljs-comment">// Values of b are different:</span>
assert.<span class="hljs-title function_">deepEqual</span>(obj1, obj2);
<span class="hljs-comment">// AssertionError: { a: { b: 1 } } deepEqual { a: { b: 2 } }</span>

assert.<span class="hljs-title function_">deepEqual</span>(obj1, obj3);
<span class="hljs-comment">// OK</span>

<span class="hljs-comment">// Prototypes are ignored:</span>
assert.<span class="hljs-title function_">deepEqual</span>(obj1, obj4);
<span class="hljs-comment">// AssertionError: { a: { b: 1 } } deepEqual {}</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);

<span class="hljs-keyword">const</span> obj1 = {
  <span class="hljs-attr">a</span>: {
    <span class="hljs-attr">b</span>: <span class="hljs-number">1</span>,
  },
};
<span class="hljs-keyword">const</span> obj2 = {
  <span class="hljs-attr">a</span>: {
    <span class="hljs-attr">b</span>: <span class="hljs-number">2</span>,
  },
};
<span class="hljs-keyword">const</span> obj3 = {
  <span class="hljs-attr">a</span>: {
    <span class="hljs-attr">b</span>: <span class="hljs-number">1</span>,
  },
};
<span class="hljs-keyword">const</span> obj4 = { <span class="hljs-attr">__proto__</span>: obj1 };

assert.<span class="hljs-title function_">deepEqual</span>(obj1, obj1);
<span class="hljs-comment">// OK</span>

<span class="hljs-comment">// Values of b are different:</span>
assert.<span class="hljs-title function_">deepEqual</span>(obj1, obj2);
<span class="hljs-comment">// AssertionError: { a: { b: 1 } } deepEqual { a: { b: 2 } }</span>

assert.<span class="hljs-title function_">deepEqual</span>(obj1, obj3);
<span class="hljs-comment">// OK</span>

<span class="hljs-comment">// Prototypes are ignored:</span>
assert.<span class="hljs-title function_">deepEqual</span>(obj1, obj4);
<span class="hljs-comment">// AssertionError: { a: { b: 1 } } deepEqual {}</span></code><button class="copy-button">copy</button></pre>
<p>If the values are not equal, an <a href="#all_assert_class-assertassertionerror"><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="#all_errors_class-error"><code>Error</code></a> then it will be thrown instead of the
<a href="#all_assert_class-assertassertionerror"><code>AssertionError</code></a>.</p>
</section><section><h3><code>assert.deepStrictEqual(actual, expected[, message])</code><span><a class="mark" href="#all_assert_assertdeepstrictequalactual-expected-message" id="all_assert_assertdeepstrictequalactual-expected-message">#</a></span><a aria-hidden="true" class="legacy" id="assert_assert_deepstrictequal_actual_expected_message"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.15.0</td>
<td><p>Error cause and errors properties are now compared as well.</p></td></tr>
<tr><td>v18.0.0</td>
<td><p>Regular expressions lastIndex property is now compared as well.</p></td></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.1.0</td>
<td><p>Objects with circular references can be used as inputs now.</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>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>
<h4>Comparison details<span><a class="mark" href="#all_assert_comparison-details_1" id="all_assert_comparison-details_1">#</a></span><a aria-hidden="true" class="legacy" id="assert_comparison_details_1"></a></h4>
<ul>
<li>Primitive values are compared using <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://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality"><code>===</code> operator</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="#all_errors_class-error"><code>Error</code></a> names, messages, causes, and errors are always compared,
even if these are not enumerable properties.
<code>errors</code> is also compared.</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>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions"><code>RegExp</code></a> lastIndex, flags, and source are always compared, even if these
are not enumerable properties.</li>
</ul>

<pre class="with-45-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;

<span class="hljs-comment">// This fails because 1 !== '1'.</span>
assert.<span class="hljs-title function_">deepStrictEqual</span>({ <span class="hljs-attr">a</span>: <span class="hljs-number">1</span> }, { <span class="hljs-attr">a</span>: <span class="hljs-string">'1'</span> });
<span class="hljs-comment">// AssertionError: Expected inputs to be strictly deep-equal:</span>
<span class="hljs-comment">// + actual - expected</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">//   {</span>
<span class="hljs-comment">// +   a: 1</span>
<span class="hljs-comment">// -   a: '1'</span>
<span class="hljs-comment">//   }</span>

<span class="hljs-comment">// The following objects don't have own properties</span>
<span class="hljs-keyword">const</span> date = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Date</span>();
<span class="hljs-keyword">const</span> object = {};
<span class="hljs-keyword">const</span> fakeDate = {};
<span class="hljs-title class_">Object</span>.<span class="hljs-title function_">setPrototypeOf</span>(fakeDate, <span class="hljs-title class_">Date</span>.<span class="hljs-property"><span class="hljs-keyword">prototype</span></span>);

<span class="hljs-comment">// Different [[Prototype]]:</span>
assert.<span class="hljs-title function_">deepStrictEqual</span>(object, fakeDate);
<span class="hljs-comment">// AssertionError: Expected inputs to be strictly deep-equal:</span>
<span class="hljs-comment">// + actual - expected</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// + {}</span>
<span class="hljs-comment">// - Date {}</span>

<span class="hljs-comment">// Different type tags:</span>
assert.<span class="hljs-title function_">deepStrictEqual</span>(date, fakeDate);
<span class="hljs-comment">// AssertionError: Expected inputs to be strictly deep-equal:</span>
<span class="hljs-comment">// + actual - expected</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// + 2018-04-26T00:49:08.604Z</span>
<span class="hljs-comment">// - Date {}</span>

assert.<span class="hljs-title function_">deepStrictEqual</span>(<span class="hljs-title class_">NaN</span>, <span class="hljs-title class_">NaN</span>);
<span class="hljs-comment">// OK because Object.is(NaN, NaN) is true.</span>

<span class="hljs-comment">// Different unwrapped numbers:</span>
assert.<span class="hljs-title function_">deepStrictEqual</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Number</span>(<span class="hljs-number">1</span>), <span class="hljs-keyword">new</span> <span class="hljs-title class_">Number</span>(<span class="hljs-number">2</span>));
<span class="hljs-comment">// AssertionError: Expected inputs to be strictly deep-equal:</span>
<span class="hljs-comment">// + actual - expected</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// + [Number: 1]</span>
<span class="hljs-comment">// - [Number: 2]</span>

assert.<span class="hljs-title function_">deepStrictEqual</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">String</span>(<span class="hljs-string">'foo'</span>), <span class="hljs-title class_">Object</span>(<span class="hljs-string">'foo'</span>));
<span class="hljs-comment">// OK because the object and the string are identical when unwrapped.</span>

assert.<span class="hljs-title function_">deepStrictEqual</span>(-<span class="hljs-number">0</span>, -<span class="hljs-number">0</span>);
<span class="hljs-comment">// OK</span>

<span class="hljs-comment">// Different zeros:</span>
assert.<span class="hljs-title function_">deepStrictEqual</span>(<span class="hljs-number">0</span>, -<span class="hljs-number">0</span>);
<span class="hljs-comment">// AssertionError: Expected inputs to be strictly deep-equal:</span>
<span class="hljs-comment">// + actual - expected</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// + 0</span>
<span class="hljs-comment">// - -0</span>

<span class="hljs-keyword">const</span> symbol1 = <span class="hljs-title class_">Symbol</span>();
<span class="hljs-keyword">const</span> symbol2 = <span class="hljs-title class_">Symbol</span>();
assert.<span class="hljs-title function_">deepStrictEqual</span>({ [symbol1]: <span class="hljs-number">1</span> }, { [symbol1]: <span class="hljs-number">1</span> });
<span class="hljs-comment">// OK, because it is the same symbol on both objects.</span>

assert.<span class="hljs-title function_">deepStrictEqual</span>({ [symbol1]: <span class="hljs-number">1</span> }, { [symbol2]: <span class="hljs-number">1</span> });
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: Inputs identical but not reference equal:</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// {</span>
<span class="hljs-comment">//   [Symbol()]: 1</span>
<span class="hljs-comment">// }</span>

<span class="hljs-keyword">const</span> weakMap1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WeakMap</span>();
<span class="hljs-keyword">const</span> weakMap2 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WeakMap</span>([[{}, {}]]);
<span class="hljs-keyword">const</span> weakMap3 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WeakMap</span>();
weakMap3.<span class="hljs-property">unequal</span> = <span class="hljs-literal">true</span>;

assert.<span class="hljs-title function_">deepStrictEqual</span>(weakMap1, weakMap2);
<span class="hljs-comment">// OK, because it is impossible to compare the entries</span>

<span class="hljs-comment">// Fails because weakMap3 has a property that weakMap1 does not contain:</span>
assert.<span class="hljs-title function_">deepStrictEqual</span>(weakMap1, weakMap3);
<span class="hljs-comment">// AssertionError: Expected inputs to be strictly deep-equal:</span>
<span class="hljs-comment">// + actual - expected</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">//   WeakMap {</span>
<span class="hljs-comment">// +   [items unknown]</span>
<span class="hljs-comment">// -   [items unknown],</span>
<span class="hljs-comment">// -   unequal: true</span>
<span class="hljs-comment">//   }</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);

<span class="hljs-comment">// This fails because 1 !== '1'.</span>
assert.<span class="hljs-title function_">deepStrictEqual</span>({ <span class="hljs-attr">a</span>: <span class="hljs-number">1</span> }, { <span class="hljs-attr">a</span>: <span class="hljs-string">'1'</span> });
<span class="hljs-comment">// AssertionError: Expected inputs to be strictly deep-equal:</span>
<span class="hljs-comment">// + actual - expected</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">//   {</span>
<span class="hljs-comment">// +   a: 1</span>
<span class="hljs-comment">// -   a: '1'</span>
<span class="hljs-comment">//   }</span>

<span class="hljs-comment">// The following objects don't have own properties</span>
<span class="hljs-keyword">const</span> date = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Date</span>();
<span class="hljs-keyword">const</span> object = {};
<span class="hljs-keyword">const</span> fakeDate = {};
<span class="hljs-title class_">Object</span>.<span class="hljs-title function_">setPrototypeOf</span>(fakeDate, <span class="hljs-title class_">Date</span>.<span class="hljs-property"><span class="hljs-keyword">prototype</span></span>);

<span class="hljs-comment">// Different [[Prototype]]:</span>
assert.<span class="hljs-title function_">deepStrictEqual</span>(object, fakeDate);
<span class="hljs-comment">// AssertionError: Expected inputs to be strictly deep-equal:</span>
<span class="hljs-comment">// + actual - expected</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// + {}</span>
<span class="hljs-comment">// - Date {}</span>

<span class="hljs-comment">// Different type tags:</span>
assert.<span class="hljs-title function_">deepStrictEqual</span>(date, fakeDate);
<span class="hljs-comment">// AssertionError: Expected inputs to be strictly deep-equal:</span>
<span class="hljs-comment">// + actual - expected</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// + 2018-04-26T00:49:08.604Z</span>
<span class="hljs-comment">// - Date {}</span>

assert.<span class="hljs-title function_">deepStrictEqual</span>(<span class="hljs-title class_">NaN</span>, <span class="hljs-title class_">NaN</span>);
<span class="hljs-comment">// OK because Object.is(NaN, NaN) is true.</span>

<span class="hljs-comment">// Different unwrapped numbers:</span>
assert.<span class="hljs-title function_">deepStrictEqual</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Number</span>(<span class="hljs-number">1</span>), <span class="hljs-keyword">new</span> <span class="hljs-title class_">Number</span>(<span class="hljs-number">2</span>));
<span class="hljs-comment">// AssertionError: Expected inputs to be strictly deep-equal:</span>
<span class="hljs-comment">// + actual - expected</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// + [Number: 1]</span>
<span class="hljs-comment">// - [Number: 2]</span>

assert.<span class="hljs-title function_">deepStrictEqual</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">String</span>(<span class="hljs-string">'foo'</span>), <span class="hljs-title class_">Object</span>(<span class="hljs-string">'foo'</span>));
<span class="hljs-comment">// OK because the object and the string are identical when unwrapped.</span>

assert.<span class="hljs-title function_">deepStrictEqual</span>(-<span class="hljs-number">0</span>, -<span class="hljs-number">0</span>);
<span class="hljs-comment">// OK</span>

<span class="hljs-comment">// Different zeros:</span>
assert.<span class="hljs-title function_">deepStrictEqual</span>(<span class="hljs-number">0</span>, -<span class="hljs-number">0</span>);
<span class="hljs-comment">// AssertionError: Expected inputs to be strictly deep-equal:</span>
<span class="hljs-comment">// + actual - expected</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// + 0</span>
<span class="hljs-comment">// - -0</span>

<span class="hljs-keyword">const</span> symbol1 = <span class="hljs-title class_">Symbol</span>();
<span class="hljs-keyword">const</span> symbol2 = <span class="hljs-title class_">Symbol</span>();
assert.<span class="hljs-title function_">deepStrictEqual</span>({ [symbol1]: <span class="hljs-number">1</span> }, { [symbol1]: <span class="hljs-number">1</span> });
<span class="hljs-comment">// OK, because it is the same symbol on both objects.</span>

assert.<span class="hljs-title function_">deepStrictEqual</span>({ [symbol1]: <span class="hljs-number">1</span> }, { [symbol2]: <span class="hljs-number">1</span> });
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: Inputs identical but not reference equal:</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// {</span>
<span class="hljs-comment">//   [Symbol()]: 1</span>
<span class="hljs-comment">// }</span>

<span class="hljs-keyword">const</span> weakMap1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WeakMap</span>();
<span class="hljs-keyword">const</span> weakMap2 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WeakMap</span>([[{}, {}]]);
<span class="hljs-keyword">const</span> weakMap3 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WeakMap</span>();
weakMap3.<span class="hljs-property">unequal</span> = <span class="hljs-literal">true</span>;

assert.<span class="hljs-title function_">deepStrictEqual</span>(weakMap1, weakMap2);
<span class="hljs-comment">// OK, because it is impossible to compare the entries</span>

<span class="hljs-comment">// Fails because weakMap3 has a property that weakMap1 does not contain:</span>
assert.<span class="hljs-title function_">deepStrictEqual</span>(weakMap1, weakMap3);
<span class="hljs-comment">// AssertionError: Expected inputs to be strictly deep-equal:</span>
<span class="hljs-comment">// + actual - expected</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">//   WeakMap {</span>
<span class="hljs-comment">// +   [items unknown]</span>
<span class="hljs-comment">// -   [items unknown],</span>
<span class="hljs-comment">// -   unequal: true</span>
<span class="hljs-comment">//   }</span></code><button class="copy-button">copy</button></pre>
<p>If the values are not equal, an <a href="#all_assert_class-assertassertionerror"><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="#all_errors_class-error"><code>Error</code></a> then it will be thrown instead of the
<code>AssertionError</code>.</p>
</section><section><h3><code>assert.doesNotMatch(string, regexp[, message])</code><span><a class="mark" href="#all_assert_assertdoesnotmatchstring-regexp-message" id="all_assert_assertdoesnotmatchstring-regexp-message">#</a></span><a aria-hidden="true" class="legacy" id="assert_assert_doesnotmatch_string_regexp_message"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0</td>
<td><p>This API is no longer experimental.</p></td></tr>
<tr><td>v13.6.0, v12.16.0</td>
<td><p><span>Added in: v13.6.0, v12.16.0</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></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>Expects the <code>string</code> input not to match the regular expression.</p>

<pre class="with-45-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;

assert.<span class="hljs-title function_">doesNotMatch</span>(<span class="hljs-string">'I will fail'</span>, <span class="hljs-regexp">/fail/</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: The input was expected to not match the ...</span>

assert.<span class="hljs-title function_">doesNotMatch</span>(<span class="hljs-number">123</span>, <span class="hljs-regexp">/pass/</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.</span>

assert.<span class="hljs-title function_">doesNotMatch</span>(<span class="hljs-string">'I will pass'</span>, <span class="hljs-regexp">/different/</span>);
<span class="hljs-comment">// OK</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);

assert.<span class="hljs-title function_">doesNotMatch</span>(<span class="hljs-string">'I will fail'</span>, <span class="hljs-regexp">/fail/</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: The input was expected to not match the ...</span>

assert.<span class="hljs-title function_">doesNotMatch</span>(<span class="hljs-number">123</span>, <span class="hljs-regexp">/pass/</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.</span>

assert.<span class="hljs-title function_">doesNotMatch</span>(<span class="hljs-string">'I will pass'</span>, <span class="hljs-regexp">/different/</span>);
<span class="hljs-comment">// OK</span></code><button class="copy-button">copy</button></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="#all_assert_class-assertassertionerror"><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="#all_errors_class-error"><code>Error</code></a> then it will be thrown instead of the
<a href="#all_assert_class-assertassertionerror"><code>AssertionError</code></a>.</p>
</section><section><h3><code>assert.doesNotReject(asyncFn[, error][, message])</code><span><a class="mark" href="#all_assert_assertdoesnotrejectasyncfn-error-message" id="all_assert_assertdoesnotrejectasyncfn-error-message">#</a></span><a aria-hidden="true" class="legacy" id="assert_assert_doesnotreject_asyncfn_error_message"></a></h3>
<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="#all_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="#all_assert_assertthrowsfn-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="#all_assert_assertdoesnotthrowfn-error-message"><code>assert.doesNotThrow()</code></a>.</p>

<pre class="with-45-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;

<span class="hljs-keyword">await</span> assert.<span class="hljs-title function_">doesNotReject</span>(
  <span class="hljs-keyword">async</span> () => {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'Wrong value'</span>);
  },
  <span class="hljs-title class_">SyntaxError</span>,
);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);

(<span class="hljs-keyword">async</span> () => {
  <span class="hljs-keyword">await</span> assert.<span class="hljs-title function_">doesNotReject</span>(
    <span class="hljs-keyword">async</span> () => {
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'Wrong value'</span>);
    },
    <span class="hljs-title class_">SyntaxError</span>,
  );
})();</code><button class="copy-button">copy</button></pre>

<pre class="with-45-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;

assert.<span class="hljs-title function_">doesNotReject</span>(<span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">reject</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'Wrong value'</span>)))
  .<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> {
    <span class="hljs-comment">// ...</span>
  });</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);

assert.<span class="hljs-title function_">doesNotReject</span>(<span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">reject</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'Wrong value'</span>)))
  .<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> {
    <span class="hljs-comment">// ...</span>
  });</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>assert.doesNotThrow(fn[, error][, message])</code><span><a class="mark" href="#all_assert_assertdoesnotthrowfn-error-message" id="all_assert_assertdoesnotthrowfn-error-message">#</a></span><a aria-hidden="true" class="legacy" id="assert_assert_doesnotthrow_fn_error_message"></a></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, 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="#all_assert_class-assertassertionerror"><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="#all_assert_assertthrowsfn-error-message"><code>assert.throws()</code></a> for more details.</p>
<p>The following, for instance, will throw the <a href="#all_errors_class-typeerror"><code>TypeError</code></a> because there is no
matching error type in the assertion:</p>

<pre class="with-45-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;

assert.<span class="hljs-title function_">doesNotThrow</span>(
  <span class="hljs-function">() =></span> {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'Wrong value'</span>);
  },
  <span class="hljs-title class_">SyntaxError</span>,
);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);

assert.<span class="hljs-title function_">doesNotThrow</span>(
  <span class="hljs-function">() =></span> {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'Wrong value'</span>);
  },
  <span class="hljs-title class_">SyntaxError</span>,
);</code><button class="copy-button">copy</button></pre>
<p>However, the following will result in an <a href="#all_assert_class-assertassertionerror"><code>AssertionError</code></a> with the message
'Got unwanted exception...':</p>

<pre class="with-45-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;

assert.<span class="hljs-title function_">doesNotThrow</span>(
  <span class="hljs-function">() =></span> {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'Wrong value'</span>);
  },
  <span class="hljs-title class_">TypeError</span>,
);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);

assert.<span class="hljs-title function_">doesNotThrow</span>(
  <span class="hljs-function">() =></span> {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'Wrong value'</span>);
  },
  <span class="hljs-title class_">TypeError</span>,
);</code><button class="copy-button">copy</button></pre>
<p>If an <a href="#all_assert_class-assertassertionerror"><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="#all_assert_class-assertassertionerror"><code>AssertionError</code></a>
message:</p>

<pre class="with-45-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;

assert.<span class="hljs-title function_">doesNotThrow</span>(
  <span class="hljs-function">() =></span> {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'Wrong value'</span>);
  },
  <span class="hljs-regexp">/Wrong value/</span>,
  <span class="hljs-string">'Whoops'</span>,
);
<span class="hljs-comment">// Throws: AssertionError: Got unwanted exception: Whoops</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);

assert.<span class="hljs-title function_">doesNotThrow</span>(
  <span class="hljs-function">() =></span> {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'Wrong value'</span>);
  },
  <span class="hljs-regexp">/Wrong value/</span>,
  <span class="hljs-string">'Whoops'</span>,
);
<span class="hljs-comment">// Throws: AssertionError: Got unwanted exception: Whoops</span></code><button class="copy-button">copy</button></pre>
</section><section><h3><code>assert.equal(actual, expected[, message])</code><span><a class="mark" href="#all_assert_assertequalactual-expected-message" id="all_assert_assertequalactual-expected-message">#</a></span><a aria-hidden="true" class="legacy" id="assert_assert_equal_actual_expected_message"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0, v14.18.0</td>
<td><p>In Legacy assertion mode, changed status from Deprecated to Legacy.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>NaN is now treated as being identical if both sides are NaN.</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="#all_assert_assertstrictequalactual-expected-message"><code>assert.strictEqual()</code></a>.</p>
<p><strong>Legacy assertion mode</strong></p>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy: Use <a href="#all_assert_assertstrictequalactual-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://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality"><code>==</code> operator</a>. <code>NaN</code> is specially handled
and treated as being identical if both sides are <code>NaN</code>.</p>

<pre class="with-38-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;

assert.<span class="hljs-title function_">equal</span>(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>);
<span class="hljs-comment">// OK, 1 == 1</span>
assert.<span class="hljs-title function_">equal</span>(<span class="hljs-number">1</span>, <span class="hljs-string">'1'</span>);
<span class="hljs-comment">// OK, 1 == '1'</span>
assert.<span class="hljs-title function_">equal</span>(<span class="hljs-title class_">NaN</span>, <span class="hljs-title class_">NaN</span>);
<span class="hljs-comment">// OK</span>

assert.<span class="hljs-title function_">equal</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);
<span class="hljs-comment">// AssertionError: 1 == 2</span>
assert.<span class="hljs-title function_">equal</span>({ <span class="hljs-attr">a</span>: { <span class="hljs-attr">b</span>: <span class="hljs-number">1</span> } }, { <span class="hljs-attr">a</span>: { <span class="hljs-attr">b</span>: <span class="hljs-number">1</span> } });
<span class="hljs-comment">// AssertionError: { a: { b: 1 } } == { a: { b: 1 } }</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);

assert.<span class="hljs-title function_">equal</span>(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>);
<span class="hljs-comment">// OK, 1 == 1</span>
assert.<span class="hljs-title function_">equal</span>(<span class="hljs-number">1</span>, <span class="hljs-string">'1'</span>);
<span class="hljs-comment">// OK, 1 == '1'</span>
assert.<span class="hljs-title function_">equal</span>(<span class="hljs-title class_">NaN</span>, <span class="hljs-title class_">NaN</span>);
<span class="hljs-comment">// OK</span>

assert.<span class="hljs-title function_">equal</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);
<span class="hljs-comment">// AssertionError: 1 == 2</span>
assert.<span class="hljs-title function_">equal</span>({ <span class="hljs-attr">a</span>: { <span class="hljs-attr">b</span>: <span class="hljs-number">1</span> } }, { <span class="hljs-attr">a</span>: { <span class="hljs-attr">b</span>: <span class="hljs-number">1</span> } });
<span class="hljs-comment">// AssertionError: { a: { b: 1 } } == { a: { b: 1 } }</span></code><button class="copy-button">copy</button></pre>
<p>If the values are not equal, an <a href="#all_assert_class-assertassertionerror"><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="#all_errors_class-error"><code>Error</code></a> then it will be thrown instead of the
<code>AssertionError</code>.</p>
</section><section><h3><code>assert.fail([message])</code><span><a class="mark" href="#all_assert_assertfailmessage" id="all_assert_assertfailmessage">#</a></span><a aria-hidden="true" class="legacy" id="assert_assert_fail_message"></a></h3>
<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="#all_assert_class-assertassertionerror"><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="#all_errors_class-error"><code>Error</code></a> then
it will be thrown instead of the <a href="#all_assert_class-assertassertionerror"><code>AssertionError</code></a>.</p>

<pre class="with-45-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;

assert.<span class="hljs-title function_">fail</span>();
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: Failed</span>

assert.<span class="hljs-title function_">fail</span>(<span class="hljs-string">'boom'</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: boom</span>

assert.<span class="hljs-title function_">fail</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'need array'</span>));
<span class="hljs-comment">// TypeError: need array</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);

assert.<span class="hljs-title function_">fail</span>();
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: Failed</span>

assert.<span class="hljs-title function_">fail</span>(<span class="hljs-string">'boom'</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: boom</span>

assert.<span class="hljs-title function_">fail</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'need array'</span>));
<span class="hljs-comment">// TypeError: need array</span></code><button class="copy-button">copy</button></pre>
<p>Using <code>assert.fail()</code> with more than two arguments is possible but deprecated.
See below for further details.</p>
</section><section><h3><code>assert.fail(actual, expected[, message[, operator[, stackStartFn]]])</code><span><a class="mark" href="#all_assert_assertfailactual-expected-message-operator-stackstartfn" id="all_assert_assertfailactual-expected-message-operator-stackstartfn">#</a></span><a aria-hidden="true" class="legacy" id="assert_assert_fail_actual_expected_message_operator_stackstartfn"></a></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 <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="#all_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="#all_errors_errorcapturestacktracetargetobject-constructoropt"><code>Error.captureStackTrace</code></a>). If no arguments are
given, the default message <code>Failed</code> will be used.</p>

<pre class="with-45-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;

assert.<span class="hljs-title function_">fail</span>(<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: 'a' != 'b'</span>

assert.<span class="hljs-title function_">fail</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-literal">undefined</span>, <span class="hljs-string">'>'</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: 1 > 2</span>

assert.<span class="hljs-title function_">fail</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-string">'fail'</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: fail</span>

assert.<span class="hljs-title function_">fail</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-string">'whoops'</span>, <span class="hljs-string">'>'</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: whoops</span>

assert.<span class="hljs-title function_">fail</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'need array'</span>));
<span class="hljs-comment">// TypeError: need array</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);

assert.<span class="hljs-title function_">fail</span>(<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: 'a' != 'b'</span>

assert.<span class="hljs-title function_">fail</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-literal">undefined</span>, <span class="hljs-string">'>'</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: 1 > 2</span>

assert.<span class="hljs-title function_">fail</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-string">'fail'</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: fail</span>

assert.<span class="hljs-title function_">fail</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-string">'whoops'</span>, <span class="hljs-string">'>'</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: whoops</span>

assert.<span class="hljs-title function_">fail</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'need array'</span>));
<span class="hljs-comment">// TypeError: need array</span></code><button class="copy-button">copy</button></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 class="with-45-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;

<span class="hljs-keyword">function</span> <span class="hljs-title function_">suppressFrame</span>(<span class="hljs-params"></span>) {
  assert.<span class="hljs-title function_">fail</span>(<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>, <span class="hljs-literal">undefined</span>, <span class="hljs-string">'!=='</span>, suppressFrame);
}
<span class="hljs-title function_">suppressFrame</span>();
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: 'a' !== 'b'</span>
<span class="hljs-comment">//     at repl:1:1</span>
<span class="hljs-comment">//     at ContextifyScript.Script.runInThisContext (vm.js:44:33)</span>
<span class="hljs-comment">//     ...</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);

<span class="hljs-keyword">function</span> <span class="hljs-title function_">suppressFrame</span>(<span class="hljs-params"></span>) {
  assert.<span class="hljs-title function_">fail</span>(<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>, <span class="hljs-literal">undefined</span>, <span class="hljs-string">'!=='</span>, suppressFrame);
}
<span class="hljs-title function_">suppressFrame</span>();
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: 'a' !== 'b'</span>
<span class="hljs-comment">//     at repl:1:1</span>
<span class="hljs-comment">//     at ContextifyScript.Script.runInThisContext (vm.js:44:33)</span>
<span class="hljs-comment">//     ...</span></code><button class="copy-button">copy</button></pre>
</section><section><h3><code>assert.ifError(value)</code><span><a class="mark" href="#all_assert_assertiferrorvalue" id="all_assert_assertiferrorvalue">#</a></span><a aria-hidden="true" class="legacy" id="assert_assert_iferror_value"></a></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>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 class="with-45-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;

assert.<span class="hljs-title function_">ifError</span>(<span class="hljs-literal">null</span>);
<span class="hljs-comment">// OK</span>
assert.<span class="hljs-title function_">ifError</span>(<span class="hljs-number">0</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0</span>
assert.<span class="hljs-title function_">ifError</span>(<span class="hljs-string">'error'</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error'</span>
assert.<span class="hljs-title function_">ifError</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>());
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error</span>

<span class="hljs-comment">// Create some random error frames.</span>
<span class="hljs-keyword">let</span> err;
(<span class="hljs-keyword">function</span> <span class="hljs-title function_">errorFrame</span>(<span class="hljs-params"></span>) {
  err = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'test error'</span>);
})();

(<span class="hljs-keyword">function</span> <span class="hljs-title function_">ifErrorFrame</span>(<span class="hljs-params"></span>) {
  assert.<span class="hljs-title function_">ifError</span>(err);
})();
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error</span>
<span class="hljs-comment">//     at ifErrorFrame</span>
<span class="hljs-comment">//     at errorFrame</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);

assert.<span class="hljs-title function_">ifError</span>(<span class="hljs-literal">null</span>);
<span class="hljs-comment">// OK</span>
assert.<span class="hljs-title function_">ifError</span>(<span class="hljs-number">0</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0</span>
assert.<span class="hljs-title function_">ifError</span>(<span class="hljs-string">'error'</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error'</span>
assert.<span class="hljs-title function_">ifError</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>());
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error</span>

<span class="hljs-comment">// Create some random error frames.</span>
<span class="hljs-keyword">let</span> err;
(<span class="hljs-keyword">function</span> <span class="hljs-title function_">errorFrame</span>(<span class="hljs-params"></span>) {
  err = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'test error'</span>);
})();

(<span class="hljs-keyword">function</span> <span class="hljs-title function_">ifErrorFrame</span>(<span class="hljs-params"></span>) {
  assert.<span class="hljs-title function_">ifError</span>(err);
})();
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error</span>
<span class="hljs-comment">//     at ifErrorFrame</span>
<span class="hljs-comment">//     at errorFrame</span></code><button class="copy-button">copy</button></pre>
</section><section><h3><code>assert.match(string, regexp[, message])</code><span><a class="mark" href="#all_assert_assertmatchstring-regexp-message" id="all_assert_assertmatchstring-regexp-message">#</a></span><a aria-hidden="true" class="legacy" id="assert_assert_match_string_regexp_message"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0</td>
<td><p>This API is no longer experimental.</p></td></tr>
<tr><td>v13.6.0, v12.16.0</td>
<td><p><span>Added in: v13.6.0, v12.16.0</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></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>Expects the <code>string</code> input to match the regular expression.</p>

<pre class="with-45-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;

assert.<span class="hljs-title function_">match</span>(<span class="hljs-string">'I will fail'</span>, <span class="hljs-regexp">/pass/</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: The input did not match the regular ...</span>

assert.<span class="hljs-title function_">match</span>(<span class="hljs-number">123</span>, <span class="hljs-regexp">/pass/</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.</span>

assert.<span class="hljs-title function_">match</span>(<span class="hljs-string">'I will pass'</span>, <span class="hljs-regexp">/pass/</span>);
<span class="hljs-comment">// OK</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);

assert.<span class="hljs-title function_">match</span>(<span class="hljs-string">'I will fail'</span>, <span class="hljs-regexp">/pass/</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: The input did not match the regular ...</span>

assert.<span class="hljs-title function_">match</span>(<span class="hljs-number">123</span>, <span class="hljs-regexp">/pass/</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.</span>

assert.<span class="hljs-title function_">match</span>(<span class="hljs-string">'I will pass'</span>, <span class="hljs-regexp">/pass/</span>);
<span class="hljs-comment">// OK</span></code><button class="copy-button">copy</button></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="#all_assert_class-assertassertionerror"><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="#all_errors_class-error"><code>Error</code></a> then it will be thrown instead of the
<a href="#all_assert_class-assertassertionerror"><code>AssertionError</code></a>.</p>
</section><section><h3><code>assert.notDeepEqual(actual, expected[, message])</code><span><a class="mark" href="#all_assert_assertnotdeepequalactual-expected-message" id="all_assert_assertnotdeepequalactual-expected-message">#</a></span><a aria-hidden="true" class="legacy" id="assert_assert_notdeepequal_actual_expected_message"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0, v14.18.0</td>
<td><p>In Legacy assertion mode, changed status from Deprecated to Legacy.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>NaN is now treated as being identical if both sides are NaN.</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="#all_assert_assertnotdeepstrictequalactual-expected-message"><code>assert.notDeepStrictEqual()</code></a>.</p>
<p><strong>Legacy assertion mode</strong></p>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy: Use <a href="#all_assert_assertnotdeepstrictequalactual-expected-message"><code>assert.notDeepStrictEqual()</code></a> instead.</div><p></p>
<p>Tests for any deep inequality. Opposite of <a href="#all_assert_assertdeepequalactual-expected-message"><code>assert.deepEqual()</code></a>.</p>

<pre class="with-38-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;

<span class="hljs-keyword">const</span> obj1 = {
  <span class="hljs-attr">a</span>: {
    <span class="hljs-attr">b</span>: <span class="hljs-number">1</span>,
  },
};
<span class="hljs-keyword">const</span> obj2 = {
  <span class="hljs-attr">a</span>: {
    <span class="hljs-attr">b</span>: <span class="hljs-number">2</span>,
  },
};
<span class="hljs-keyword">const</span> obj3 = {
  <span class="hljs-attr">a</span>: {
    <span class="hljs-attr">b</span>: <span class="hljs-number">1</span>,
  },
};
<span class="hljs-keyword">const</span> obj4 = { <span class="hljs-attr">__proto__</span>: obj1 };

assert.<span class="hljs-title function_">notDeepEqual</span>(obj1, obj1);
<span class="hljs-comment">// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }</span>

assert.<span class="hljs-title function_">notDeepEqual</span>(obj1, obj2);
<span class="hljs-comment">// OK</span>

assert.<span class="hljs-title function_">notDeepEqual</span>(obj1, obj3);
<span class="hljs-comment">// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }</span>

assert.<span class="hljs-title function_">notDeepEqual</span>(obj1, obj4);
<span class="hljs-comment">// OK</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);

<span class="hljs-keyword">const</span> obj1 = {
  <span class="hljs-attr">a</span>: {
    <span class="hljs-attr">b</span>: <span class="hljs-number">1</span>,
  },
};
<span class="hljs-keyword">const</span> obj2 = {
  <span class="hljs-attr">a</span>: {
    <span class="hljs-attr">b</span>: <span class="hljs-number">2</span>,
  },
};
<span class="hljs-keyword">const</span> obj3 = {
  <span class="hljs-attr">a</span>: {
    <span class="hljs-attr">b</span>: <span class="hljs-number">1</span>,
  },
};
<span class="hljs-keyword">const</span> obj4 = { <span class="hljs-attr">__proto__</span>: obj1 };

assert.<span class="hljs-title function_">notDeepEqual</span>(obj1, obj1);
<span class="hljs-comment">// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }</span>

assert.<span class="hljs-title function_">notDeepEqual</span>(obj1, obj2);
<span class="hljs-comment">// OK</span>

assert.<span class="hljs-title function_">notDeepEqual</span>(obj1, obj3);
<span class="hljs-comment">// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }</span>

assert.<span class="hljs-title function_">notDeepEqual</span>(obj1, obj4);
<span class="hljs-comment">// OK</span></code><button class="copy-button">copy</button></pre>
<p>If the values are deeply equal, an <a href="#all_assert_class-assertassertionerror"><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="#all_errors_class-error"><code>Error</code></a> then it will be thrown
instead of the <code>AssertionError</code>.</p>
</section><section><h3><code>assert.notDeepStrictEqual(actual, expected[, message])</code><span><a class="mark" href="#all_assert_assertnotdeepstrictequalactual-expected-message" id="all_assert_assertnotdeepstrictequalactual-expected-message">#</a></span><a aria-hidden="true" class="legacy" id="assert_assert_notdeepstrictequal_actual_expected_message"></a></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>-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.1.0</td>
<td><p>Objects with circular references can be used as inputs now.</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>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="#all_assert_assertdeepstrictequalactual-expected-message"><code>assert.deepStrictEqual()</code></a>.</p>

<pre class="with-45-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;

assert.<span class="hljs-title function_">notDeepStrictEqual</span>({ <span class="hljs-attr">a</span>: <span class="hljs-number">1</span> }, { <span class="hljs-attr">a</span>: <span class="hljs-string">'1'</span> });
<span class="hljs-comment">// OK</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);

assert.<span class="hljs-title function_">notDeepStrictEqual</span>({ <span class="hljs-attr">a</span>: <span class="hljs-number">1</span> }, { <span class="hljs-attr">a</span>: <span class="hljs-string">'1'</span> });
<span class="hljs-comment">// OK</span></code><button class="copy-button">copy</button></pre>
<p>If the values are deeply and strictly equal, an <a href="#all_assert_class-assertassertionerror"><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="#all_errors_class-error"><code>Error</code></a> then it will be thrown
instead of the <a href="#all_assert_class-assertassertionerror"><code>AssertionError</code></a>.</p>
</section><section><h3><code>assert.notEqual(actual, expected[, message])</code><span><a class="mark" href="#all_assert_assertnotequalactual-expected-message" id="all_assert_assertnotequalactual-expected-message">#</a></span><a aria-hidden="true" class="legacy" id="assert_assert_notequal_actual_expected_message"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0, v14.18.0</td>
<td><p>In Legacy assertion mode, changed status from Deprecated to Legacy.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>NaN is now treated as being identical if both sides are NaN.</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="#all_assert_assertnotstrictequalactual-expected-message"><code>assert.notStrictEqual()</code></a>.</p>
<p><strong>Legacy assertion mode</strong></p>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy: Use <a href="#all_assert_assertnotstrictequalactual-expected-message"><code>assert.notStrictEqual()</code></a> instead.</div><p></p>
<p>Tests shallow, coercive inequality with the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Inequality"><code>!=</code> operator</a>. <code>NaN</code> is
specially handled and treated as being identical if both sides are <code>NaN</code>.</p>

<pre class="with-38-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;

assert.<span class="hljs-title function_">notEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);
<span class="hljs-comment">// OK</span>

assert.<span class="hljs-title function_">notEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>);
<span class="hljs-comment">// AssertionError: 1 != 1</span>

assert.<span class="hljs-title function_">notEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-string">'1'</span>);
<span class="hljs-comment">// AssertionError: 1 != '1'</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);

assert.<span class="hljs-title function_">notEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);
<span class="hljs-comment">// OK</span>

assert.<span class="hljs-title function_">notEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>);
<span class="hljs-comment">// AssertionError: 1 != 1</span>

assert.<span class="hljs-title function_">notEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-string">'1'</span>);
<span class="hljs-comment">// AssertionError: 1 != '1'</span></code><button class="copy-button">copy</button></pre>
<p>If the values are equal, an <a href="#all_assert_class-assertassertionerror"><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="#all_errors_class-error"><code>Error</code></a> then it will be thrown instead of the
<code>AssertionError</code>.</p>
</section><section><h3><code>assert.notStrictEqual(actual, expected[, message])</code><span><a class="mark" href="#all_assert_assertnotstrictequalactual-expected-message" id="all_assert_assertnotstrictequalactual-expected-message">#</a></span><a aria-hidden="true" class="legacy" id="assert_assert_notstrictequal_actual_expected_message"></a></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>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 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is"><code>Object.is()</code></a>.</p>

<pre class="with-45-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;

assert.<span class="hljs-title function_">notStrictEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);
<span class="hljs-comment">// OK</span>

assert.<span class="hljs-title function_">notStrictEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to:</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// 1</span>

assert.<span class="hljs-title function_">notStrictEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-string">'1'</span>);
<span class="hljs-comment">// OK</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);

assert.<span class="hljs-title function_">notStrictEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);
<span class="hljs-comment">// OK</span>

assert.<span class="hljs-title function_">notStrictEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to:</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// 1</span>

assert.<span class="hljs-title function_">notStrictEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-string">'1'</span>);
<span class="hljs-comment">// OK</span></code><button class="copy-button">copy</button></pre>
<p>If the values are strictly equal, an <a href="#all_assert_class-assertassertionerror"><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="#all_errors_class-error"><code>Error</code></a> then it will be thrown
instead of the <code>AssertionError</code>.</p>
</section><section><h3><code>assert.ok(value[, message])</code><span><a class="mark" href="#all_assert_assertokvalue-message" id="all_assert_assertokvalue-message">#</a></span><a aria-hidden="true" class="legacy" id="assert_assert_ok_value_message"></a></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>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="#all_assert_class-assertassertionerror"><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="#all_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 class="with-45-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;

assert.<span class="hljs-title function_">ok</span>(<span class="hljs-literal">true</span>);
<span class="hljs-comment">// OK</span>
assert.<span class="hljs-title function_">ok</span>(<span class="hljs-number">1</span>);
<span class="hljs-comment">// OK</span>

assert.<span class="hljs-title function_">ok</span>();
<span class="hljs-comment">// AssertionError: No value argument passed to `assert.ok()`</span>

assert.<span class="hljs-title function_">ok</span>(<span class="hljs-literal">false</span>, <span class="hljs-string">'it\'s false'</span>);
<span class="hljs-comment">// AssertionError: it's false</span>

<span class="hljs-comment">// In the repl:</span>
assert.<span class="hljs-title function_">ok</span>(<span class="hljs-keyword">typeof</span> <span class="hljs-number">123</span> === <span class="hljs-string">'string'</span>);
<span class="hljs-comment">// AssertionError: false == true</span>

<span class="hljs-comment">// In a file (e.g. test.js):</span>
assert.<span class="hljs-title function_">ok</span>(<span class="hljs-keyword">typeof</span> <span class="hljs-number">123</span> === <span class="hljs-string">'string'</span>);
<span class="hljs-comment">// AssertionError: The expression evaluated to a falsy value:</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">//   assert.ok(typeof 123 === 'string')</span>

assert.<span class="hljs-title function_">ok</span>(<span class="hljs-literal">false</span>);
<span class="hljs-comment">// AssertionError: The expression evaluated to a falsy value:</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">//   assert.ok(false)</span>

assert.<span class="hljs-title function_">ok</span>(<span class="hljs-number">0</span>);
<span class="hljs-comment">// AssertionError: The expression evaluated to a falsy value:</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">//   assert.ok(0)</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);

assert.<span class="hljs-title function_">ok</span>(<span class="hljs-literal">true</span>);
<span class="hljs-comment">// OK</span>
assert.<span class="hljs-title function_">ok</span>(<span class="hljs-number">1</span>);
<span class="hljs-comment">// OK</span>

assert.<span class="hljs-title function_">ok</span>();
<span class="hljs-comment">// AssertionError: No value argument passed to `assert.ok()`</span>

assert.<span class="hljs-title function_">ok</span>(<span class="hljs-literal">false</span>, <span class="hljs-string">'it\'s false'</span>);
<span class="hljs-comment">// AssertionError: it's false</span>

<span class="hljs-comment">// In the repl:</span>
assert.<span class="hljs-title function_">ok</span>(<span class="hljs-keyword">typeof</span> <span class="hljs-number">123</span> === <span class="hljs-string">'string'</span>);
<span class="hljs-comment">// AssertionError: false == true</span>

<span class="hljs-comment">// In a file (e.g. test.js):</span>
assert.<span class="hljs-title function_">ok</span>(<span class="hljs-keyword">typeof</span> <span class="hljs-number">123</span> === <span class="hljs-string">'string'</span>);
<span class="hljs-comment">// AssertionError: The expression evaluated to a falsy value:</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">//   assert.ok(typeof 123 === 'string')</span>

assert.<span class="hljs-title function_">ok</span>(<span class="hljs-literal">false</span>);
<span class="hljs-comment">// AssertionError: The expression evaluated to a falsy value:</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">//   assert.ok(false)</span>

assert.<span class="hljs-title function_">ok</span>(<span class="hljs-number">0</span>);
<span class="hljs-comment">// AssertionError: The expression evaluated to a falsy value:</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">//   assert.ok(0)</span></code><button class="copy-button">copy</button></pre>

<pre class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;

<span class="hljs-comment">// Using `assert()` works the same:</span>
<span class="hljs-title function_">assert</span>(<span class="hljs-number">0</span>);
<span class="hljs-comment">// AssertionError: The expression evaluated to a falsy value:</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">//   assert(0)</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);

<span class="hljs-comment">// Using `assert()` works the same:</span>
<span class="hljs-title function_">assert</span>(<span class="hljs-number">0</span>);
<span class="hljs-comment">// AssertionError: The expression evaluated to a falsy value:</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">//   assert(0)</span></code><button class="copy-button">copy</button></pre>
</section><section><h3><code>assert.rejects(asyncFn[, error][, message])</code><span><a class="mark" href="#all_assert_assertrejectsasyncfn-error-message" id="all_assert_assertrejectsasyncfn-error-message">#</a></span><a aria-hidden="true" class="legacy" id="assert_assert_rejects_asyncfn_error_message"></a></h3>
<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="#all_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="#all_assert_assertthrowsfn-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="#all_assert_class-assertassertionerror"><code>AssertionError</code></a>
if the <code>asyncFn</code> fails to reject.</p>

<pre class="with-45-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;

<span class="hljs-keyword">await</span> assert.<span class="hljs-title function_">rejects</span>(
  <span class="hljs-keyword">async</span> () => {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'Wrong value'</span>);
  },
  {
    <span class="hljs-attr">name</span>: <span class="hljs-string">'TypeError'</span>,
    <span class="hljs-attr">message</span>: <span class="hljs-string">'Wrong value'</span>,
  },
);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);

(<span class="hljs-keyword">async</span> () => {
  <span class="hljs-keyword">await</span> assert.<span class="hljs-title function_">rejects</span>(
    <span class="hljs-keyword">async</span> () => {
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'Wrong value'</span>);
    },
    {
      <span class="hljs-attr">name</span>: <span class="hljs-string">'TypeError'</span>,
      <span class="hljs-attr">message</span>: <span class="hljs-string">'Wrong value'</span>,
    },
  );
})();</code><button class="copy-button">copy</button></pre>

<pre class="with-45-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;

<span class="hljs-keyword">await</span> assert.<span class="hljs-title function_">rejects</span>(
  <span class="hljs-keyword">async</span> () => {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'Wrong value'</span>);
  },
  <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
    assert.<span class="hljs-title function_">strictEqual</span>(err.<span class="hljs-property">name</span>, <span class="hljs-string">'TypeError'</span>);
    assert.<span class="hljs-title function_">strictEqual</span>(err.<span class="hljs-property">message</span>, <span class="hljs-string">'Wrong value'</span>);
    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
  },
);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);

(<span class="hljs-keyword">async</span> () => {
  <span class="hljs-keyword">await</span> assert.<span class="hljs-title function_">rejects</span>(
    <span class="hljs-keyword">async</span> () => {
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'Wrong value'</span>);
    },
    <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
      assert.<span class="hljs-title function_">strictEqual</span>(err.<span class="hljs-property">name</span>, <span class="hljs-string">'TypeError'</span>);
      assert.<span class="hljs-title function_">strictEqual</span>(err.<span class="hljs-property">message</span>, <span class="hljs-string">'Wrong value'</span>);
      <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
    },
  );
})();</code><button class="copy-button">copy</button></pre>

<pre class="with-45-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;

assert.<span class="hljs-title function_">rejects</span>(
  <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">reject</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Wrong value'</span>)),
  <span class="hljs-title class_">Error</span>,
).<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> {
  <span class="hljs-comment">// ...</span>
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);

assert.<span class="hljs-title function_">rejects</span>(
  <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">reject</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Wrong value'</span>)),
  <span class="hljs-title class_">Error</span>,
).<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> {
  <span class="hljs-comment">// ...</span>
});</code><button class="copy-button">copy</button></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="#all_assert_assertthrowsfn-error-message"><code>assert.throws()</code></a> carefully if using a string as the second
argument gets considered.</p>
</section><section><h3><code>assert.strictEqual(actual, expected[, message])</code><span><a class="mark" href="#all_assert_assertstrictequalactual-expected-message" id="all_assert_assertstrictequalactual-expected-message">#</a></span><a aria-hidden="true" class="legacy" id="assert_assert_strictequal_actual_expected_message"></a></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>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 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is"><code>Object.is()</code></a>.</p>

<pre class="with-45-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;

assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// 1 !== 2</span>

assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>);
<span class="hljs-comment">// OK</span>

assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-string">'Hello foobar'</span>, <span class="hljs-string">'Hello World!'</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:</span>
<span class="hljs-comment">// + actual - expected</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// + 'Hello foobar'</span>
<span class="hljs-comment">// - 'Hello World!'</span>
<span class="hljs-comment">//          ^</span>

<span class="hljs-keyword">const</span> apples = <span class="hljs-number">1</span>;
<span class="hljs-keyword">const</span> oranges = <span class="hljs-number">2</span>;
assert.<span class="hljs-title function_">strictEqual</span>(apples, oranges, <span class="hljs-string">`apples <span class="hljs-subst">${apples}</span> !== oranges <span class="hljs-subst">${oranges}</span>`</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2</span>

assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-string">'1'</span>, <span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'Inputs are not identical'</span>));
<span class="hljs-comment">// TypeError: Inputs are not identical</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);

assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// 1 !== 2</span>

assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>);
<span class="hljs-comment">// OK</span>

assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-string">'Hello foobar'</span>, <span class="hljs-string">'Hello World!'</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:</span>
<span class="hljs-comment">// + actual - expected</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// + 'Hello foobar'</span>
<span class="hljs-comment">// - 'Hello World!'</span>
<span class="hljs-comment">//          ^</span>

<span class="hljs-keyword">const</span> apples = <span class="hljs-number">1</span>;
<span class="hljs-keyword">const</span> oranges = <span class="hljs-number">2</span>;
assert.<span class="hljs-title function_">strictEqual</span>(apples, oranges, <span class="hljs-string">`apples <span class="hljs-subst">${apples}</span> !== oranges <span class="hljs-subst">${oranges}</span>`</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2</span>

assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-string">'1'</span>, <span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'Inputs are not identical'</span>));
<span class="hljs-comment">// TypeError: Inputs are not identical</span></code><button class="copy-button">copy</button></pre>
<p>If the values are not strictly equal, an <a href="#all_assert_class-assertassertionerror"><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="#all_errors_class-error"><code>Error</code></a> then it will be thrown
instead of the <a href="#all_assert_class-assertassertionerror"><code>AssertionError</code></a>.</p>
</section><section><h3><code>assert.throws(fn[, error][, message])</code><span><a class="mark" href="#all_assert_assertthrowsfn-error-message" id="all_assert_assertthrowsfn-error-message">#</a></span><a aria-hidden="true" class="legacy" id="assert_assert_throws_fn_error_message"></a></h3>
<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 class="with-45-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;

<span class="hljs-keyword">const</span> err = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'Wrong value'</span>);
err.<span class="hljs-property">code</span> = <span class="hljs-number">404</span>;
err.<span class="hljs-property">foo</span> = <span class="hljs-string">'bar'</span>;
err.<span class="hljs-property">info</span> = {
  <span class="hljs-attr">nested</span>: <span class="hljs-literal">true</span>,
  <span class="hljs-attr">baz</span>: <span class="hljs-string">'text'</span>,
};
err.<span class="hljs-property">reg</span> = <span class="hljs-regexp">/abc/i</span>;

assert.<span class="hljs-title function_">throws</span>(
  <span class="hljs-function">() =></span> {
    <span class="hljs-keyword">throw</span> err;
  },
  {
    <span class="hljs-attr">name</span>: <span class="hljs-string">'TypeError'</span>,
    <span class="hljs-attr">message</span>: <span class="hljs-string">'Wrong value'</span>,
    <span class="hljs-attr">info</span>: {
      <span class="hljs-attr">nested</span>: <span class="hljs-literal">true</span>,
      <span class="hljs-attr">baz</span>: <span class="hljs-string">'text'</span>,
    },
    <span class="hljs-comment">// Only properties on the validation object will be tested for.</span>
    <span class="hljs-comment">// Using nested objects requires all properties to be present. Otherwise</span>
    <span class="hljs-comment">// the validation is going to fail.</span>
  },
);

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

<span class="hljs-comment">// Fails due to the different `message` and `name` properties:</span>
assert.<span class="hljs-title function_">throws</span>(
  <span class="hljs-function">() =></span> {
    <span class="hljs-keyword">const</span> otherErr = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Not found'</span>);
    <span class="hljs-comment">// Copy all enumerable properties from `err` to `otherErr`.</span>
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> [key, value] <span class="hljs-keyword">of</span> <span class="hljs-title class_">Object</span>.<span class="hljs-title function_">entries</span>(err)) {
      otherErr[key] = value;
    }
    <span class="hljs-keyword">throw</span> otherErr;
  },
  <span class="hljs-comment">// The error's `message` and `name` properties will also be checked when using</span>
  <span class="hljs-comment">// an error as validation object.</span>
  err,
);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);

<span class="hljs-keyword">const</span> err = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>(<span class="hljs-string">'Wrong value'</span>);
err.<span class="hljs-property">code</span> = <span class="hljs-number">404</span>;
err.<span class="hljs-property">foo</span> = <span class="hljs-string">'bar'</span>;
err.<span class="hljs-property">info</span> = {
  <span class="hljs-attr">nested</span>: <span class="hljs-literal">true</span>,
  <span class="hljs-attr">baz</span>: <span class="hljs-string">'text'</span>,
};
err.<span class="hljs-property">reg</span> = <span class="hljs-regexp">/abc/i</span>;

assert.<span class="hljs-title function_">throws</span>(
  <span class="hljs-function">() =></span> {
    <span class="hljs-keyword">throw</span> err;
  },
  {
    <span class="hljs-attr">name</span>: <span class="hljs-string">'TypeError'</span>,
    <span class="hljs-attr">message</span>: <span class="hljs-string">'Wrong value'</span>,
    <span class="hljs-attr">info</span>: {
      <span class="hljs-attr">nested</span>: <span class="hljs-literal">true</span>,
      <span class="hljs-attr">baz</span>: <span class="hljs-string">'text'</span>,
    },
    <span class="hljs-comment">// Only properties on the validation object will be tested for.</span>
    <span class="hljs-comment">// Using nested objects requires all properties to be present. Otherwise</span>
    <span class="hljs-comment">// the validation is going to fail.</span>
  },
);

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

<span class="hljs-comment">// Fails due to the different `message` and `name` properties:</span>
assert.<span class="hljs-title function_">throws</span>(
  <span class="hljs-function">() =></span> {
    <span class="hljs-keyword">const</span> otherErr = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Not found'</span>);
    <span class="hljs-comment">// Copy all enumerable properties from `err` to `otherErr`.</span>
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> [key, value] <span class="hljs-keyword">of</span> <span class="hljs-title class_">Object</span>.<span class="hljs-title function_">entries</span>(err)) {
      otherErr[key] = value;
    }
    <span class="hljs-keyword">throw</span> otherErr;
  },
  <span class="hljs-comment">// The error's `message` and `name` properties will also be checked when using</span>
  <span class="hljs-comment">// an error as validation object.</span>
  err,
);</code><button class="copy-button">copy</button></pre>
<p>Validate instanceof using constructor:</p>

<pre class="with-45-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;

assert.<span class="hljs-title function_">throws</span>(
  <span class="hljs-function">() =></span> {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Wrong value'</span>);
  },
  <span class="hljs-title class_">Error</span>,
);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);

assert.<span class="hljs-title function_">throws</span>(
  <span class="hljs-function">() =></span> {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Wrong value'</span>);
  },
  <span class="hljs-title class_">Error</span>,
);</code><button class="copy-button">copy</button></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 class="with-45-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;

assert.<span class="hljs-title function_">throws</span>(
  <span class="hljs-function">() =></span> {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Wrong value'</span>);
  },
  <span class="hljs-regexp">/^Error: Wrong value$/</span>,
);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);

assert.<span class="hljs-title function_">throws</span>(
  <span class="hljs-function">() =></span> {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Wrong value'</span>);
  },
  <span class="hljs-regexp">/^Error: Wrong value$/</span>,
);</code><button class="copy-button">copy</button></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="#all_assert_class-assertassertionerror"><code>AssertionError</code></a>.</p>

<pre class="with-45-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;

assert.<span class="hljs-title function_">throws</span>(
  <span class="hljs-function">() =></span> {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Wrong value'</span>);
  },
  <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
    <span class="hljs-title function_">assert</span>(err <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">Error</span>);
    <span class="hljs-title function_">assert</span>(<span class="hljs-regexp">/value/</span>.<span class="hljs-title function_">test</span>(err));
    <span class="hljs-comment">// Avoid returning anything from validation functions besides `true`.</span>
    <span class="hljs-comment">// Otherwise, it's not clear what part of the validation failed. Instead,</span>
    <span class="hljs-comment">// throw an error about the specific validation that failed (as done in this</span>
    <span class="hljs-comment">// example) and add as much helpful debugging information to that error as</span>
    <span class="hljs-comment">// possible.</span>
    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
  },
  <span class="hljs-string">'unexpected error'</span>,
);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);

assert.<span class="hljs-title function_">throws</span>(
  <span class="hljs-function">() =></span> {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Wrong value'</span>);
  },
  <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
    <span class="hljs-title function_">assert</span>(err <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">Error</span>);
    <span class="hljs-title function_">assert</span>(<span class="hljs-regexp">/value/</span>.<span class="hljs-title function_">test</span>(err));
    <span class="hljs-comment">// Avoid returning anything from validation functions besides `true`.</span>
    <span class="hljs-comment">// Otherwise, it's not clear what part of the validation failed. Instead,</span>
    <span class="hljs-comment">// throw an error about the specific validation that failed (as done in this</span>
    <span class="hljs-comment">// example) and add as much helpful debugging information to that error as</span>
    <span class="hljs-comment">// possible.</span>
    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
  },
  <span class="hljs-string">'unexpected error'</span>,
);</code><button class="copy-button">copy</button></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>

<pre class="with-45-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert/strict'</span>;

<span class="hljs-keyword">function</span> <span class="hljs-title function_">throwingFirst</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'First'</span>);
}

<span class="hljs-keyword">function</span> <span class="hljs-title function_">throwingSecond</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Second'</span>);
}

<span class="hljs-keyword">function</span> <span class="hljs-title function_">notThrowing</span>(<span class="hljs-params"></span>) {}

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

<span class="hljs-comment">// The string is only used (as message) in case the function does not throw:</span>
assert.<span class="hljs-title function_">throws</span>(notThrowing, <span class="hljs-string">'Second'</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: Missing expected exception: Second</span>

<span class="hljs-comment">// If it was intended to match for the error message do this instead:</span>
<span class="hljs-comment">// It does not throw because the error messages match.</span>
assert.<span class="hljs-title function_">throws</span>(throwingSecond, <span class="hljs-regexp">/Second$/</span>);

<span class="hljs-comment">// If the error message does not match, an AssertionError is thrown.</span>
assert.<span class="hljs-title function_">throws</span>(throwingFirst, <span class="hljs-regexp">/Second$/</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert/strict'</span>);

<span class="hljs-keyword">function</span> <span class="hljs-title function_">throwingFirst</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'First'</span>);
}

<span class="hljs-keyword">function</span> <span class="hljs-title function_">throwingSecond</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Second'</span>);
}

<span class="hljs-keyword">function</span> <span class="hljs-title function_">notThrowing</span>(<span class="hljs-params"></span>) {}

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

<span class="hljs-comment">// The string is only used (as message) in case the function does not throw:</span>
assert.<span class="hljs-title function_">throws</span>(notThrowing, <span class="hljs-string">'Second'</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]: Missing expected exception: Second</span>

<span class="hljs-comment">// If it was intended to match for the error message do this instead:</span>
<span class="hljs-comment">// It does not throw because the error messages match.</span>
assert.<span class="hljs-title function_">throws</span>(throwingSecond, <span class="hljs-regexp">/Second$/</span>);

<span class="hljs-comment">// If the error message does not match, an AssertionError is thrown.</span>
assert.<span class="hljs-title function_">throws</span>(throwingFirst, <span class="hljs-regexp">/Second$/</span>);
<span class="hljs-comment">// AssertionError [ERR_ASSERTION]</span></code><button class="copy-button">copy</button></pre>
<p>Due to the confusing error-prone notation, avoid a string as the second
argument.</p></section>
        </section>
<section><h2>Asynchronous context tracking<span><a class="mark" href="#all_async_context_asynchronous-context-tracking" id="all_async_context_asynchronous-context-tracking">#</a></span><a aria-hidden="true" class="legacy" id="async_context_asynchronous_context_tracking"></a></h2>

<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/async_hooks.js">lib/async_hooks.js</a></p>
<section><h3>Introduction<span><a class="mark" href="#all_async_context_introduction" id="all_async_context_introduction">#</a></span><a aria-hidden="true" class="legacy" id="async_context_introduction"></a></h3>
<p>These classes are used to associate state and propagate it throughout
callbacks and promise chains.
They allow 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 <code>AsyncLocalStorage</code> and <code>AsyncResource</code> classes are part of the
<code>node:async_hooks</code> module:</p>

<pre class="with-73-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">AsyncLocalStorage</span>, <span class="hljs-title class_">AsyncResource</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">AsyncLocalStorage</span>, <span class="hljs-title class_">AsyncResource</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);</code><button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>AsyncLocalStorage</code><span><a class="mark" href="#all_async_context_class-asynclocalstorage" id="all_async_context_class-asynclocalstorage">#</a></span><a aria-hidden="true" class="legacy" id="async_context_class_asynclocalstorage"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.4.0</td>
<td><p>AsyncLocalStorage is now Stable. Previously, it had been Experimental.</p></td></tr>
<tr><td>v13.10.0, v12.17.0</td>
<td><p><span>Added in: v13.10.0, v12.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>This class creates stores that stay coherent through asynchronous operations.</p>
<p>While you can create your own implementation on top of the <code>node:async_hooks</code>
module, <code>AsyncLocalStorage</code> should be preferred as it is a performant and memory
safe implementation that involves significant optimizations that are non-obvious
to implement.</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 class="with-58-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> http <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">AsyncLocalStorage</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;

<span class="hljs-keyword">const</span> asyncLocalStorage = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AsyncLocalStorage</span>();

<span class="hljs-keyword">function</span> <span class="hljs-title function_">logWithId</span>(<span class="hljs-params">msg</span>) {
  <span class="hljs-keyword">const</span> id = asyncLocalStorage.<span class="hljs-title function_">getStore</span>();
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${id !== <span class="hljs-literal">undefined</span> ? id : <span class="hljs-string">'-'</span>}</span>:`</span>, msg);
}

<span class="hljs-keyword">let</span> idSeq = <span class="hljs-number">0</span>;
http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
  asyncLocalStorage.<span class="hljs-title function_">run</span>(idSeq++, <span class="hljs-function">() =></span> {
    <span class="hljs-title function_">logWithId</span>(<span class="hljs-string">'start'</span>);
    <span class="hljs-comment">// Imagine any chain of async operations here</span>
    <span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></span> {
      <span class="hljs-title function_">logWithId</span>(<span class="hljs-string">'finish'</span>);
      res.<span class="hljs-title function_">end</span>();
    });
  });
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8080</span>);

http.<span class="hljs-title function_">get</span>(<span class="hljs-string">'http://localhost:8080'</span>);
http.<span class="hljs-title function_">get</span>(<span class="hljs-string">'http://localhost:8080'</span>);
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   0: start</span>
<span class="hljs-comment">//   1: start</span>
<span class="hljs-comment">//   0: finish</span>
<span class="hljs-comment">//   1: finish</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">AsyncLocalStorage</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);

<span class="hljs-keyword">const</span> asyncLocalStorage = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AsyncLocalStorage</span>();

<span class="hljs-keyword">function</span> <span class="hljs-title function_">logWithId</span>(<span class="hljs-params">msg</span>) {
  <span class="hljs-keyword">const</span> id = asyncLocalStorage.<span class="hljs-title function_">getStore</span>();
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${id !== <span class="hljs-literal">undefined</span> ? id : <span class="hljs-string">'-'</span>}</span>:`</span>, msg);
}

<span class="hljs-keyword">let</span> idSeq = <span class="hljs-number">0</span>;
http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
  asyncLocalStorage.<span class="hljs-title function_">run</span>(idSeq++, <span class="hljs-function">() =></span> {
    <span class="hljs-title function_">logWithId</span>(<span class="hljs-string">'start'</span>);
    <span class="hljs-comment">// Imagine any chain of async operations here</span>
    <span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></span> {
      <span class="hljs-title function_">logWithId</span>(<span class="hljs-string">'finish'</span>);
      res.<span class="hljs-title function_">end</span>();
    });
  });
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8080</span>);

http.<span class="hljs-title function_">get</span>(<span class="hljs-string">'http://localhost:8080'</span>);
http.<span class="hljs-title function_">get</span>(<span class="hljs-string">'http://localhost:8080'</span>);
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   0: start</span>
<span class="hljs-comment">//   1: start</span>
<span class="hljs-comment">//   0: finish</span>
<span class="hljs-comment">//   1: finish</span></code><button class="copy-button">copy</button></pre>
<p>Each instance of <code>AsyncLocalStorage</code> maintains an independent storage context.
Multiple instances can safely exist simultaneously without risk of interfering
with each other's data.</p>
<h4><code>new AsyncLocalStorage()</code><span><a class="mark" href="#all_async_context_new-asynclocalstorage" id="all_async_context_new-asynclocalstorage">#</a></span><a aria-hidden="true" class="legacy" id="async_context_new_asynclocalstorage"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.7.0</td>
<td><p>Removed experimental onPropagate option.</p></td></tr>
<tr><td>v19.2.0, v18.13.0</td>
<td><p>Add option onPropagate.</p></td></tr>
<tr><td>v13.10.0, v12.17.0</td>
<td><p><span>Added in: v13.10.0, v12.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Creates a new instance of <code>AsyncLocalStorage</code>. Store is only provided within a
<code>run()</code> call or after an <code>enterWith()</code> call.</p>
<h4>Static method: <code>AsyncLocalStorage.bind(fn)</code><span><a class="mark" href="#all_async_context_static-method-asynclocalstoragebindfn" id="all_async_context_static-method-asynclocalstoragebindfn">#</a></span><a aria-hidden="true" class="legacy" id="async_context_static_method_asynclocalstorage_bind_fn"></a></h4>
<div class="api_metadata">
<span>Added in: v19.8.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<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 bind to the current execution context.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> A new function that calls <code>fn</code> within the captured
execution context.</li>
</ul>
<p>Binds the given function to the current execution context.</p>
<h4>Static method: <code>AsyncLocalStorage.snapshot()</code><span><a class="mark" href="#all_async_context_static-method-asynclocalstoragesnapshot" id="all_async_context_static-method-asynclocalstoragesnapshot">#</a></span><a aria-hidden="true" class="legacy" id="async_context_static_method_asynclocalstorage_snapshot"></a></h4>
<div class="api_metadata">
<span>Added in: v19.8.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> A new function with the signature
<code>(fn: (...args) : R, ...args) : R</code>.</li>
</ul>
<p>Captures the current execution context and returns a function that accepts a
function as an argument. Whenever the returned function is called, it
calls the function passed to it within the captured context.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> asyncLocalStorage = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AsyncLocalStorage</span>();
<span class="hljs-keyword">const</span> runInAsyncScope = asyncLocalStorage.<span class="hljs-title function_">run</span>(<span class="hljs-number">123</span>, <span class="hljs-function">() =></span> <span class="hljs-title class_">AsyncLocalStorage</span>.<span class="hljs-title function_">snapshot</span>());
<span class="hljs-keyword">const</span> result = asyncLocalStorage.<span class="hljs-title function_">run</span>(<span class="hljs-number">321</span>, <span class="hljs-function">() =></span> <span class="hljs-title function_">runInAsyncScope</span>(<span class="hljs-function">() =></span> asyncLocalStorage.<span class="hljs-title function_">getStore</span>()));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result);  <span class="hljs-comment">// returns 123</span></code> <button class="copy-button">copy</button></pre>
<p>AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple
async context tracking purposes, for example:</p>
<pre><code class="language-js"><span class="hljs-keyword">class</span> <span class="hljs-title class_">Foo</span> {
  #runInAsyncScope = <span class="hljs-title class_">AsyncLocalStorage</span>.<span class="hljs-title function_">snapshot</span>();

  <span class="hljs-title function_">get</span>(<span class="hljs-params"></span>) { <span class="hljs-keyword">return</span> <span class="hljs-variable language_">this</span>.#<span class="hljs-title function_">runInAsyncScope</span>(<span class="hljs-function">() =></span> asyncLocalStorage.<span class="hljs-title function_">getStore</span>()); }
}

<span class="hljs-keyword">const</span> foo = asyncLocalStorage.<span class="hljs-title function_">run</span>(<span class="hljs-number">123</span>, <span class="hljs-function">() =></span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Foo</span>());
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(asyncLocalStorage.<span class="hljs-title function_">run</span>(<span class="hljs-number">321</span>, <span class="hljs-function">() =></span> foo.<span class="hljs-title function_">get</span>())); <span class="hljs-comment">// returns 123</span></code> <button class="copy-button">copy</button></pre>
<h4><code>asyncLocalStorage.disable()</code><span><a class="mark" href="#all_async_context_asynclocalstoragedisable" id="all_async_context_asynclocalstoragedisable">#</a></span><a aria-hidden="true" class="legacy" id="async_context_asynclocalstorage_disable"></a></h4>
<div class="api_metadata">
<span>Added in: v13.10.0, v12.17.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>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> or <code>asyncLocalStorage.enterWith()</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>Use this method when the <code>asyncLocalStorage</code> is not in use anymore
in the current process.</p>
<h4><code>asyncLocalStorage.getStore()</code><span><a class="mark" href="#all_async_context_asynclocalstoragegetstore" id="all_async_context_asynclocalstoragegetstore">#</a></span><a aria-hidden="true" class="legacy" id="async_context_asynclocalstorage_getstore"></a></h4>
<div class="api_metadata">
<span>Added in: v13.10.0, 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>Returns the current store.
If called outside of an asynchronous context initialized by
calling <code>asyncLocalStorage.run()</code> or <code>asyncLocalStorage.enterWith()</code>, it
returns <code>undefined</code>.</p>
<h4><code>asyncLocalStorage.enterWith(store)</code><span><a class="mark" href="#all_async_context_asynclocalstorageenterwithstore" id="all_async_context_asynclocalstorageenterwithstore">#</a></span><a aria-hidden="true" class="legacy" id="async_context_asynclocalstorage_enterwith_store"></a></h4>
<div class="api_metadata">
<span>Added in: v13.11.0, v12.17.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<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>Transitions into the context for the remainder of the current
synchronous execution and then persists the store through any following
asynchronous calls.</p>
<p>Example:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> store = { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span> };
<span class="hljs-comment">// Replaces previous store with the given store object</span>
asyncLocalStorage.<span class="hljs-title function_">enterWith</span>(store);
asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns the store object</span>
<span class="hljs-title function_">someAsyncOperation</span>(<span class="hljs-function">() =></span> {
  asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns the same object</span>
});</code> <button class="copy-button">copy</button></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>. That is why
<code>run()</code> should be preferred over <code>enterWith()</code> unless there are strong reasons
to use the latter method.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> store = { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span> };

emitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'my-event'</span>, <span class="hljs-function">() =></span> {
  asyncLocalStorage.<span class="hljs-title function_">enterWith</span>(store);
});
emitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'my-event'</span>, <span class="hljs-function">() =></span> {
  asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns the same object</span>
});

asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns undefined</span>
emitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'my-event'</span>);
asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns the same object</span></code> <button class="copy-button">copy</button></pre>
<h4><code>asyncLocalStorage.run(store, callback[, ...args])</code><span><a class="mark" href="#all_async_context_asynclocalstoragerunstore-callback-args" id="all_async_context_asynclocalstoragerunstore-callback-args">#</a></span><a aria-hidden="true" class="legacy" id="async_context_asynclocalstorage_run_store_callback_args"></a></h4>
<div class="api_metadata">
<span>Added in: v13.10.0, 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>Runs a function synchronously within a context and returns its
return value. The store is not accessible outside of the callback function.
The store is accessible to any asynchronous operations created within the
callback.</p>
<p>The optional <code>args</code> are passed to the callback function.</p>
<p>If the callback function throws an error, the error is thrown by <code>run()</code> too.
The stacktrace is not impacted by this call and the context is exited.</p>
<p>Example:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> store = { <span class="hljs-attr">id</span>: <span class="hljs-number">2</span> };
<span class="hljs-keyword">try</span> {
  asyncLocalStorage.<span class="hljs-title function_">run</span>(store, <span class="hljs-function">() =></span> {
    asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns the store object</span>
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
      asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns the store object</span>
    }, <span class="hljs-number">200</span>);
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>();
  });
} <span class="hljs-keyword">catch</span> (e) {
  asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns undefined</span>
  <span class="hljs-comment">// The error will be caught here</span>
}</code> <button class="copy-button">copy</button></pre>
<h4><code>asyncLocalStorage.exit(callback[, ...args])</code><span><a class="mark" href="#all_async_context_asynclocalstorageexitcallback-args" id="all_async_context_asynclocalstorageexitcallback-args">#</a></span><a aria-hidden="true" class="legacy" id="async_context_asynclocalstorage_exit_callback_args"></a></h4>
<div class="api_metadata">
<span>Added in: v13.10.0, v12.17.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<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>Runs a function synchronously outside of a context and returns its
return value. The store is not accessible within the callback function or
the asynchronous operations created within the callback. Any <code>getStore()</code>
call done within the callback function will always return <code>undefined</code>.</p>
<p>The optional <code>args</code> are passed to the callback function.</p>
<p>If the callback function throws an error, the error is thrown by <code>exit()</code> too.
The stacktrace is not impacted by this call and the context is re-entered.</p>
<p>Example:</p>
<pre><code class="language-js"><span class="hljs-comment">// Within a call to run</span>
<span class="hljs-keyword">try</span> {
  asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns the store object or value</span>
  asyncLocalStorage.<span class="hljs-title function_">exit</span>(<span class="hljs-function">() =></span> {
    asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns undefined</span>
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>();
  });
} <span class="hljs-keyword">catch</span> (e) {
  asyncLocalStorage.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Returns the same object or value</span>
  <span class="hljs-comment">// The error will be caught here</span>
}</code> <button class="copy-button">copy</button></pre>
<h4>Usage with <code>async/await</code><span><a class="mark" href="#all_async_context_usage-with-asyncawait" id="all_async_context_usage-with-asyncawait">#</a></span><a aria-hidden="true" class="legacy" id="async_context_usage_with_async_await"></a></h4>
<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"><span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">fn</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">await</span> asyncLocalStorage.<span class="hljs-title function_">run</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Map</span>(), <span class="hljs-function">() =></span> {
    asyncLocalStorage.<span class="hljs-title function_">getStore</span>().<span class="hljs-title function_">set</span>(<span class="hljs-string">'key'</span>, value);
    <span class="hljs-keyword">return</span> <span class="hljs-title function_">foo</span>(); <span class="hljs-comment">// The return value of foo will be awaited</span>
  });
}</code> <button class="copy-button">copy</button></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>
<h4>Troubleshooting: Context loss<span><a class="mark" href="#all_async_context_troubleshooting-context-loss" id="all_async_context_troubleshooting-context-loss">#</a></span><a aria-hidden="true" class="legacy" id="async_context_troubleshooting_context_loss"></a></h4>
<p>In most cases, <code>AsyncLocalStorage</code> works without issues. In rare situations, the
current store is lost in one of the asynchronous operations.</p>
<p>If your code is callback-based, it is enough to promisify it with
<a href="#all_util_utilpromisifyoriginal"><code>util.promisify()</code></a> so it starts working with native promises.</p>
<p>If you need to use a callback-based API or your code assumes
a custom thenable implementation, use the <a href="#all_async_context_class-asyncresource"><code>AsyncResource</code></a> class
to associate the asynchronous operation with the correct execution context.
Find the function call responsible for the context loss by logging the content
of <code>asyncLocalStorage.getStore()</code> after the calls you suspect are responsible
for the loss. When the code logs <code>undefined</code>, the last callback called is
probably responsible for the context loss.</p>
</section><section><h3>Class: <code>AsyncResource</code><span><a class="mark" href="#all_async_context_class-asyncresource" id="all_async_context_class-asyncresource">#</a></span><a aria-hidden="true" class="legacy" id="async_context_class_asyncresource"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.4.0</td>
<td><p>AsyncResource is now Stable. Previously, it had been Experimental.</p></td></tr>
</tbody></table>
</details>
</div>
<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 class="with-72-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">AsyncResource</span>, executionAsyncId } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;

<span class="hljs-comment">// AsyncResource() is meant to be extended. Instantiating a</span>
<span class="hljs-comment">// new AsyncResource() also triggers init. If triggerAsyncId is omitted then</span>
<span class="hljs-comment">// async_hook.executionAsyncId() is used.</span>
<span class="hljs-keyword">const</span> asyncResource = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AsyncResource</span>(
  type, { <span class="hljs-attr">triggerAsyncId</span>: <span class="hljs-title function_">executionAsyncId</span>(), <span class="hljs-attr">requireManualDestroy</span>: <span class="hljs-literal">false</span> },
);

<span class="hljs-comment">// Run a function in the execution context of the resource. This will</span>
<span class="hljs-comment">// * establish the context of the resource</span>
<span class="hljs-comment">// * trigger the AsyncHooks before callbacks</span>
<span class="hljs-comment">// * call the provided function `fn` with the supplied arguments</span>
<span class="hljs-comment">// * trigger the AsyncHooks after callbacks</span>
<span class="hljs-comment">// * restore the original execution context</span>
asyncResource.<span class="hljs-title function_">runInAsyncScope</span>(fn, thisArg, ...args);

<span class="hljs-comment">// Call AsyncHooks destroy callbacks.</span>
asyncResource.<span class="hljs-title function_">emitDestroy</span>();

<span class="hljs-comment">// Return the unique ID assigned to the AsyncResource instance.</span>
asyncResource.<span class="hljs-title function_">asyncId</span>();

<span class="hljs-comment">// Return the trigger ID for the AsyncResource instance.</span>
asyncResource.<span class="hljs-title function_">triggerAsyncId</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">AsyncResource</span>, executionAsyncId } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);

<span class="hljs-comment">// AsyncResource() is meant to be extended. Instantiating a</span>
<span class="hljs-comment">// new AsyncResource() also triggers init. If triggerAsyncId is omitted then</span>
<span class="hljs-comment">// async_hook.executionAsyncId() is used.</span>
<span class="hljs-keyword">const</span> asyncResource = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AsyncResource</span>(
  type, { <span class="hljs-attr">triggerAsyncId</span>: <span class="hljs-title function_">executionAsyncId</span>(), <span class="hljs-attr">requireManualDestroy</span>: <span class="hljs-literal">false</span> },
);

<span class="hljs-comment">// Run a function in the execution context of the resource. This will</span>
<span class="hljs-comment">// * establish the context of the resource</span>
<span class="hljs-comment">// * trigger the AsyncHooks before callbacks</span>
<span class="hljs-comment">// * call the provided function `fn` with the supplied arguments</span>
<span class="hljs-comment">// * trigger the AsyncHooks after callbacks</span>
<span class="hljs-comment">// * restore the original execution context</span>
asyncResource.<span class="hljs-title function_">runInAsyncScope</span>(fn, thisArg, ...args);

<span class="hljs-comment">// Call AsyncHooks destroy callbacks.</span>
asyncResource.<span class="hljs-title function_">emitDestroy</span>();

<span class="hljs-comment">// Return the unique ID assigned to the AsyncResource instance.</span>
asyncResource.<span class="hljs-title function_">asyncId</span>();

<span class="hljs-comment">// Return the trigger ID for the AsyncResource instance.</span>
asyncResource.<span class="hljs-title function_">triggerAsyncId</span>();</code><button class="copy-button">copy</button></pre>
<h4><code>new AsyncResource(type[, options])</code><span><a class="mark" href="#all_async_context_new-asyncresourcetype-options" id="all_async_context_new-asyncresourcetype-options">#</a></span><a aria-hidden="true" class="legacy" id="async_context_new_asyncresource_type_options"></a></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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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"><span class="hljs-keyword">class</span> <span class="hljs-title class_">DBQuery</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">AsyncResource</span> {
  <span class="hljs-title function_">constructor</span>(<span class="hljs-params">db</span>) {
    <span class="hljs-variable language_">super</span>(<span class="hljs-string">'DBQuery'</span>);
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">db</span> = db;
  }

  <span class="hljs-title function_">getInfo</span>(<span class="hljs-params">query, callback</span>) {
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">db</span>.<span class="hljs-title function_">get</span>(query, <span class="hljs-function">(<span class="hljs-params">err, data</span>) =></span> {
      <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">runInAsyncScope</span>(callback, <span class="hljs-literal">null</span>, err, data);
    });
  }

  <span class="hljs-title function_">close</span>(<span class="hljs-params"></span>) {
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">db</span> = <span class="hljs-literal">null</span>;
    <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emitDestroy</span>();
  }
}</code> <button class="copy-button">copy</button></pre>
<h4>Static method: <code>AsyncResource.bind(fn[, type[, thisArg]])</code><span><a class="mark" href="#all_async_context_static-method-asyncresourcebindfn-type-thisarg" id="all_async_context_static-method-asyncresourcebindfn-type-thisarg">#</a></span><a aria-hidden="true" class="legacy" id="async_context_static_method_asyncresource_bind_fn_type_thisarg"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>The <code>asyncResource</code> property added to the bound function has been deprecated and will be removed in a future version.</p></td></tr>
<tr><td>v17.8.0, v16.15.0</td>
<td><p>Changed the default when <code>thisArg</code> is undefined to use <code>this</code> from the caller.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p>Added optional thisArg.</p></td></tr>
<tr><td>v14.8.0, v12.19.0</td>
<td><p><span>Added in: v14.8.0, v12.19.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 to bind to the current execution context.</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> An optional name to associate with the underlying
<code>AsyncResource</code>.</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></li>
</ul>
<p>Binds the given function to the current execution context.</p>
<h4><code>asyncResource.bind(fn[, thisArg])</code><span><a class="mark" href="#all_async_context_asyncresourcebindfn-thisarg" id="all_async_context_asyncresourcebindfn-thisarg">#</a></span><a aria-hidden="true" class="legacy" id="async_context_asyncresource_bind_fn_thisarg"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>The <code>asyncResource</code> property added to the bound function has been deprecated and will be removed in a future version.</p></td></tr>
<tr><td>v17.8.0, v16.15.0</td>
<td><p>Changed the default when <code>thisArg</code> is undefined to use <code>this</code> from the caller.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p>Added optional thisArg.</p></td></tr>
<tr><td>v14.8.0, v12.19.0</td>
<td><p><span>Added in: v14.8.0, v12.19.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 to bind to the current <code>AsyncResource</code>.</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></li>
</ul>
<p>Binds the given function to execute to this <code>AsyncResource</code>'s scope.</p>
<h4><code>asyncResource.runInAsyncScope(fn[, thisArg, ...args])</code><span><a class="mark" href="#all_async_context_asyncresourceruninasyncscopefn-thisarg-args" id="all_async_context_asyncresourceruninasyncscopefn-thisarg-args">#</a></span><a aria-hidden="true" class="legacy" id="async_context_asyncresource_runinasyncscope_fn_thisarg_args"></a></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="#all_async_context_asyncresourceemitdestroy" id="all_async_context_asyncresourceemitdestroy">#</a></span><a aria-hidden="true" class="legacy" id="async_context_asyncresource_emitdestroy"></a></h4>
<ul>
<li>Returns: <a href="#all_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="#all_async_context_asyncresourceasyncid" id="all_async_context_asyncresourceasyncid">#</a></span><a aria-hidden="true" class="legacy" id="async_context_asyncresource_asyncid"></a></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="#all_async_context_asyncresourcetriggerasyncid" id="all_async_context_asyncresourcetriggerasyncid">#</a></span><a aria-hidden="true" class="legacy" id="async_context_asyncresource_triggerasyncid"></a></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>
<h4>Using <code>AsyncResource</code> for a <code>Worker</code> thread pool<span><a class="mark" href="#all_async_context_using-asyncresource-for-a-worker-thread-pool" id="all_async_context_using-asyncresource-for-a-worker-thread-pool">#</a></span><a aria-hidden="true" class="legacy" id="async_context_using_asyncresource_for_a_worker_thread_pool"></a></h4>
<p>The following example shows how to use the <code>AsyncResource</code> class to properly
provide async tracking for a <a href="#all_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 class="with-54-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { parentPort } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:worker_threads'</span>;
parentPort.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">task</span>) =></span> {
  parentPort.<span class="hljs-title function_">postMessage</span>(task.<span class="hljs-property">a</span> + task.<span class="hljs-property">b</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { parentPort } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
parentPort.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">task</span>) =></span> {
  parentPort.<span class="hljs-title function_">postMessage</span>(task.<span class="hljs-property">a</span> + task.<span class="hljs-property">b</span>);
});</code><button class="copy-button">copy</button></pre>
<p>a Worker pool around it could use the following structure:</p>

<pre class="with-54-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">AsyncResource</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">import</span> path <span class="hljs-keyword">from</span> <span class="hljs-string">'node:path'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Worker</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:worker_threads'</span>;

<span class="hljs-keyword">const</span> kTaskInfo = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'kTaskInfo'</span>);
<span class="hljs-keyword">const</span> kWorkerFreedEvent = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'kWorkerFreedEvent'</span>);

<span class="hljs-keyword">class</span> <span class="hljs-title class_">WorkerPoolTaskInfo</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">AsyncResource</span> {
  <span class="hljs-title function_">constructor</span>(<span class="hljs-params">callback</span>) {
    <span class="hljs-variable language_">super</span>(<span class="hljs-string">'WorkerPoolTaskInfo'</span>);
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">callback</span> = callback;
  }

  <span class="hljs-title function_">done</span>(<span class="hljs-params">err, result</span>) {
    <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">runInAsyncScope</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">callback</span>, <span class="hljs-literal">null</span>, err, result);
    <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emitDestroy</span>();  <span class="hljs-comment">// `TaskInfo`s are used only once.</span>
  }
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">WorkerPool</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {
  <span class="hljs-title function_">constructor</span>(<span class="hljs-params">numThreads</span>) {
    <span class="hljs-variable language_">super</span>();
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">numThreads</span> = numThreads;
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">workers</span> = [];
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">freeWorkers</span> = [];
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">tasks</span> = [];

    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; numThreads; i++)
      <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">addNewWorker</span>();

    <span class="hljs-comment">// Any time the kWorkerFreedEvent is emitted, dispatch</span>
    <span class="hljs-comment">// the next task pending in the queue, if any.</span>
    <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">on</span>(kWorkerFreedEvent, <span class="hljs-function">() =></span> {
      <span class="hljs-keyword">if</span> (<span class="hljs-variable language_">this</span>.<span class="hljs-property">tasks</span>.<span class="hljs-property">length</span> > <span class="hljs-number">0</span>) {
        <span class="hljs-keyword">const</span> { task, callback } = <span class="hljs-variable language_">this</span>.<span class="hljs-property">tasks</span>.<span class="hljs-title function_">shift</span>();
        <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">runTask</span>(task, callback);
      }
    });
  }

  <span class="hljs-title function_">addNewWorker</span>(<span class="hljs-params"></span>) {
    <span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'task_processor.js'</span>, <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>));
    worker.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">result</span>) =></span> {
      <span class="hljs-comment">// In case of success: Call the callback that was passed to `runTask`,</span>
      <span class="hljs-comment">// remove the `TaskInfo` associated with the Worker, and mark it as free</span>
      <span class="hljs-comment">// again.</span>
      worker[kTaskInfo].<span class="hljs-title function_">done</span>(<span class="hljs-literal">null</span>, result);
      worker[kTaskInfo] = <span class="hljs-literal">null</span>;
      <span class="hljs-variable language_">this</span>.<span class="hljs-property">freeWorkers</span>.<span class="hljs-title function_">push</span>(worker);
      <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emit</span>(kWorkerFreedEvent);
    });
    worker.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
      <span class="hljs-comment">// In case of an uncaught exception: Call the callback that was passed to</span>
      <span class="hljs-comment">// `runTask` with the error.</span>
      <span class="hljs-keyword">if</span> (worker[kTaskInfo])
        worker[kTaskInfo].<span class="hljs-title function_">done</span>(err, <span class="hljs-literal">null</span>);
      <span class="hljs-keyword">else</span>
        <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'error'</span>, err);
      <span class="hljs-comment">// Remove the worker from the list and start a new Worker to replace the</span>
      <span class="hljs-comment">// current one.</span>
      <span class="hljs-variable language_">this</span>.<span class="hljs-property">workers</span>.<span class="hljs-title function_">splice</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">workers</span>.<span class="hljs-title function_">indexOf</span>(worker), <span class="hljs-number">1</span>);
      <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">addNewWorker</span>();
    });
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">workers</span>.<span class="hljs-title function_">push</span>(worker);
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">freeWorkers</span>.<span class="hljs-title function_">push</span>(worker);
    <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emit</span>(kWorkerFreedEvent);
  }

  <span class="hljs-title function_">runTask</span>(<span class="hljs-params">task, callback</span>) {
    <span class="hljs-keyword">if</span> (<span class="hljs-variable language_">this</span>.<span class="hljs-property">freeWorkers</span>.<span class="hljs-property">length</span> === <span class="hljs-number">0</span>) {
      <span class="hljs-comment">// No free threads, wait until a worker thread becomes free.</span>
      <span class="hljs-variable language_">this</span>.<span class="hljs-property">tasks</span>.<span class="hljs-title function_">push</span>({ task, callback });
      <span class="hljs-keyword">return</span>;
    }

    <span class="hljs-keyword">const</span> worker = <span class="hljs-variable language_">this</span>.<span class="hljs-property">freeWorkers</span>.<span class="hljs-title function_">pop</span>();
    worker[kTaskInfo] = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WorkerPoolTaskInfo</span>(callback);
    worker.<span class="hljs-title function_">postMessage</span>(task);
  }

  <span class="hljs-title function_">close</span>(<span class="hljs-params"></span>) {
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> worker <span class="hljs-keyword">of</span> <span class="hljs-variable language_">this</span>.<span class="hljs-property">workers</span>) worker.<span class="hljs-title function_">terminate</span>();
  }
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">AsyncResource</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">EventEmitter</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:path'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Worker</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);

<span class="hljs-keyword">const</span> kTaskInfo = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'kTaskInfo'</span>);
<span class="hljs-keyword">const</span> kWorkerFreedEvent = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'kWorkerFreedEvent'</span>);

<span class="hljs-keyword">class</span> <span class="hljs-title class_">WorkerPoolTaskInfo</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">AsyncResource</span> {
  <span class="hljs-title function_">constructor</span>(<span class="hljs-params">callback</span>) {
    <span class="hljs-variable language_">super</span>(<span class="hljs-string">'WorkerPoolTaskInfo'</span>);
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">callback</span> = callback;
  }

  <span class="hljs-title function_">done</span>(<span class="hljs-params">err, result</span>) {
    <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">runInAsyncScope</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">callback</span>, <span class="hljs-literal">null</span>, err, result);
    <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emitDestroy</span>();  <span class="hljs-comment">// `TaskInfo`s are used only once.</span>
  }
}

<span class="hljs-keyword">class</span> <span class="hljs-title class_">WorkerPool</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {
  <span class="hljs-title function_">constructor</span>(<span class="hljs-params">numThreads</span>) {
    <span class="hljs-variable language_">super</span>();
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">numThreads</span> = numThreads;
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">workers</span> = [];
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">freeWorkers</span> = [];
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">tasks</span> = [];

    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; numThreads; i++)
      <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">addNewWorker</span>();

    <span class="hljs-comment">// Any time the kWorkerFreedEvent is emitted, dispatch</span>
    <span class="hljs-comment">// the next task pending in the queue, if any.</span>
    <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">on</span>(kWorkerFreedEvent, <span class="hljs-function">() =></span> {
      <span class="hljs-keyword">if</span> (<span class="hljs-variable language_">this</span>.<span class="hljs-property">tasks</span>.<span class="hljs-property">length</span> > <span class="hljs-number">0</span>) {
        <span class="hljs-keyword">const</span> { task, callback } = <span class="hljs-variable language_">this</span>.<span class="hljs-property">tasks</span>.<span class="hljs-title function_">shift</span>();
        <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">runTask</span>(task, callback);
      }
    });
  }

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

  <span class="hljs-title function_">runTask</span>(<span class="hljs-params">task, callback</span>) {
    <span class="hljs-keyword">if</span> (<span class="hljs-variable language_">this</span>.<span class="hljs-property">freeWorkers</span>.<span class="hljs-property">length</span> === <span class="hljs-number">0</span>) {
      <span class="hljs-comment">// No free threads, wait until a worker thread becomes free.</span>
      <span class="hljs-variable language_">this</span>.<span class="hljs-property">tasks</span>.<span class="hljs-title function_">push</span>({ task, callback });
      <span class="hljs-keyword">return</span>;
    }

    <span class="hljs-keyword">const</span> worker = <span class="hljs-variable language_">this</span>.<span class="hljs-property">freeWorkers</span>.<span class="hljs-title function_">pop</span>();
    worker[kTaskInfo] = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WorkerPoolTaskInfo</span>(callback);
    worker.<span class="hljs-title function_">postMessage</span>(task);
  }

  <span class="hljs-title function_">close</span>(<span class="hljs-params"></span>) {
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> worker <span class="hljs-keyword">of</span> <span class="hljs-variable language_">this</span>.<span class="hljs-property">workers</span>) worker.<span class="hljs-title function_">terminate</span>();
  }
}

<span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = <span class="hljs-title class_">WorkerPool</span>;</code><button class="copy-button">copy</button></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 class="with-47-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> <span class="hljs-title class_">WorkerPool</span> <span class="hljs-keyword">from</span> <span class="hljs-string">'./worker_pool.js'</span>;
<span class="hljs-keyword">import</span> os <span class="hljs-keyword">from</span> <span class="hljs-string">'node:os'</span>;

<span class="hljs-keyword">const</span> pool = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WorkerPool</span>(os.<span class="hljs-title function_">availableParallelism</span>());

<span class="hljs-keyword">let</span> finished = <span class="hljs-number">0</span>;
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; <span class="hljs-number">10</span>; i++) {
  pool.<span class="hljs-title function_">runTask</span>({ <span class="hljs-attr">a</span>: <span class="hljs-number">42</span>, <span class="hljs-attr">b</span>: <span class="hljs-number">100</span> }, <span class="hljs-function">(<span class="hljs-params">err, result</span>) =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(i, err, result);
    <span class="hljs-keyword">if</span> (++finished === <span class="hljs-number">10</span>)
      pool.<span class="hljs-title function_">close</span>();
  });
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">WorkerPool</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./worker_pool.js'</span>);
<span class="hljs-keyword">const</span> os = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:os'</span>);

<span class="hljs-keyword">const</span> pool = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WorkerPool</span>(os.<span class="hljs-title function_">availableParallelism</span>());

<span class="hljs-keyword">let</span> finished = <span class="hljs-number">0</span>;
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; <span class="hljs-number">10</span>; i++) {
  pool.<span class="hljs-title function_">runTask</span>({ <span class="hljs-attr">a</span>: <span class="hljs-number">42</span>, <span class="hljs-attr">b</span>: <span class="hljs-number">100</span> }, <span class="hljs-function">(<span class="hljs-params">err, result</span>) =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(i, err, result);
    <span class="hljs-keyword">if</span> (++finished === <span class="hljs-number">10</span>)
      pool.<span class="hljs-title function_">close</span>();
  });
}</code><button class="copy-button">copy</button></pre>
<h4>Integrating <code>AsyncResource</code> with <code>EventEmitter</code><span><a class="mark" href="#all_async_context_integrating-asyncresource-with-eventemitter" id="all_async_context_integrating-asyncresource-with-eventemitter">#</a></span><a aria-hidden="true" class="legacy" id="async_context_integrating_asyncresource_with_eventemitter"></a></h4>
<p>Event listeners triggered by an <a href="#all_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="#all_stream_stream"><code>Stream</code></a> or a similar event-driven class.</p>

<pre class="with-72-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">AsyncResource</span>, executionAsyncId } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;

<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
  req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-title class_">AsyncResource</span>.<span class="hljs-title function_">bind</span>(<span class="hljs-function">() =></span> {
    <span class="hljs-comment">// Execution context is bound to the current outer scope.</span>
  }));
  req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">() =></span> {
    <span class="hljs-comment">// Execution context is bound to the scope that caused 'close' to emit.</span>
  });
  res.<span class="hljs-title function_">end</span>();
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">3000</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { createServer } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">AsyncResource</span>, executionAsyncId } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);

<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
  req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-title class_">AsyncResource</span>.<span class="hljs-title function_">bind</span>(<span class="hljs-function">() =></span> {
    <span class="hljs-comment">// Execution context is bound to the current outer scope.</span>
  }));
  req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">() =></span> {
    <span class="hljs-comment">// Execution context is bound to the scope that caused 'close' to emit.</span>
  });
  res.<span class="hljs-title function_">end</span>();
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">3000</span>);</code><button class="copy-button">copy</button></pre></section>
        </section>
<section><h2>Async hooks<span><a class="mark" href="#all_async_hooks_async-hooks" id="all_async_hooks_async-hooks">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_async_hooks"></a></h2>

<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental. Please migrate away from this API, if you can.
We do not recommend using the <a href="#all_async_hooks_async_hookscreatehookcallbacks"><code>createHook</code></a>, <a href="#all_async_hooks_class-asynchook"><code>AsyncHook</code></a>, and
<a href="#all_async_hooks_async_hooksexecutionasyncresource"><code>executionAsyncResource</code></a> APIs as they have usability issues, safety risks,
and performance implications. Async context tracking use cases are better
served by the stable <a href="#all_async_context_class-asynclocalstorage"><code>AsyncLocalStorage</code></a> API. If you have a use case for
<code>createHook</code>, <code>AsyncHook</code>, or <code>executionAsyncResource</code> beyond the context
tracking need solved by <a href="#all_async_context_class-asynclocalstorage"><code>AsyncLocalStorage</code></a> or diagnostics data currently
provided by <a href="diagnostics_channel.html">Diagnostics Channel</a>, please open an issue at
<a href="https://github.com/nodejs/node/issues">https://github.com/nodejs/node/issues</a> describing your use case so we can
create a more purpose-focused API.</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/async_hooks.js">lib/async_hooks.js</a></p>
<p>We strongly discourage the use of the <code>async_hooks</code> API.
Other APIs that can cover most of its use cases include:</p>
<ul>
<li><a href="#all_async_context_class-asynclocalstorage"><code>AsyncLocalStorage</code></a> tracks async context</li>
<li><a href="#all_process_processgetactiveresourcesinfo"><code>process.getActiveResourcesInfo()</code></a> tracks active resources</li>
</ul>
<p>The <code>node:async_hooks</code> module provides an API to track asynchronous resources.
It can be accessed using:</p>

<pre class="with-48-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> async_hooks <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> async_hooks = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);</code><button class="copy-button">copy</button></pre>
<section><h3>Terminology<span><a class="mark" href="#all_async_hooks_terminology" id="all_async_hooks_terminology">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_terminology"></a></h3>
<p>An asynchronous resource represents an object with an associated callback.
This callback may be called multiple times, such as 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="#all_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>
</section><section><h3>Overview<span><a class="mark" href="#all_async_hooks_overview" id="all_async_hooks_overview">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_overview"></a></h3>
<p>Following is a simple overview of the public API.</p>

<pre class="with-48-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> async_hooks <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;

<span class="hljs-comment">// Return the ID of the current execution context.</span>
<span class="hljs-keyword">const</span> eid = async_hooks.<span class="hljs-title function_">executionAsyncId</span>();

<span class="hljs-comment">// Return the ID of the handle responsible for triggering the callback of the</span>
<span class="hljs-comment">// current execution scope to call.</span>
<span class="hljs-keyword">const</span> tid = async_hooks.<span class="hljs-title function_">triggerAsyncId</span>();

<span class="hljs-comment">// Create a new AsyncHook instance. All of these callbacks are optional.</span>
<span class="hljs-keyword">const</span> asyncHook =
    async_hooks.<span class="hljs-title function_">createHook</span>({ init, before, after, destroy, promiseResolve });

<span class="hljs-comment">// Allow callbacks of this AsyncHook instance to call. This is not an implicit</span>
<span class="hljs-comment">// action after running the constructor, and must be explicitly run to begin</span>
<span class="hljs-comment">// executing callbacks.</span>
asyncHook.<span class="hljs-title function_">enable</span>();

<span class="hljs-comment">// Disable listening for new asynchronous events.</span>
asyncHook.<span class="hljs-title function_">disable</span>();

<span class="hljs-comment">//</span>
<span class="hljs-comment">// The following are the callbacks that can be passed to createHook().</span>
<span class="hljs-comment">//</span>

<span class="hljs-comment">// init() is called during object construction. The resource may not have</span>
<span class="hljs-comment">// completed construction when this callback runs. Therefore, all fields of the</span>
<span class="hljs-comment">// resource referenced by "asyncId" may not have been populated.</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">init</span>(<span class="hljs-params">asyncId, type, triggerAsyncId, resource</span>) { }

<span class="hljs-comment">// before() is called just before the resource's callback is called. It can be</span>
<span class="hljs-comment">// called 0-N times for handles (such as TCPWrap), and will be called exactly 1</span>
<span class="hljs-comment">// time for requests (such as FSReqCallback).</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">before</span>(<span class="hljs-params">asyncId</span>) { }

<span class="hljs-comment">// after() is called just after the resource's callback has finished.</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">after</span>(<span class="hljs-params">asyncId</span>) { }

<span class="hljs-comment">// destroy() is called when the resource is destroyed.</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">destroy</span>(<span class="hljs-params">asyncId</span>) { }

<span class="hljs-comment">// promiseResolve() is called only for promise resources, when the</span>
<span class="hljs-comment">// resolve() function passed to the Promise constructor is invoked</span>
<span class="hljs-comment">// (either directly or through other means of resolving a promise).</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">promiseResolve</span>(<span class="hljs-params">asyncId</span>) { }</code><code class="language-js cjs"><span class="hljs-keyword">const</span> async_hooks = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);

<span class="hljs-comment">// Return the ID of the current execution context.</span>
<span class="hljs-keyword">const</span> eid = async_hooks.<span class="hljs-title function_">executionAsyncId</span>();

<span class="hljs-comment">// Return the ID of the handle responsible for triggering the callback of the</span>
<span class="hljs-comment">// current execution scope to call.</span>
<span class="hljs-keyword">const</span> tid = async_hooks.<span class="hljs-title function_">triggerAsyncId</span>();

<span class="hljs-comment">// Create a new AsyncHook instance. All of these callbacks are optional.</span>
<span class="hljs-keyword">const</span> asyncHook =
    async_hooks.<span class="hljs-title function_">createHook</span>({ init, before, after, destroy, promiseResolve });

<span class="hljs-comment">// Allow callbacks of this AsyncHook instance to call. This is not an implicit</span>
<span class="hljs-comment">// action after running the constructor, and must be explicitly run to begin</span>
<span class="hljs-comment">// executing callbacks.</span>
asyncHook.<span class="hljs-title function_">enable</span>();

<span class="hljs-comment">// Disable listening for new asynchronous events.</span>
asyncHook.<span class="hljs-title function_">disable</span>();

<span class="hljs-comment">//</span>
<span class="hljs-comment">// The following are the callbacks that can be passed to createHook().</span>
<span class="hljs-comment">//</span>

<span class="hljs-comment">// init() is called during object construction. The resource may not have</span>
<span class="hljs-comment">// completed construction when this callback runs. Therefore, all fields of the</span>
<span class="hljs-comment">// resource referenced by "asyncId" may not have been populated.</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">init</span>(<span class="hljs-params">asyncId, type, triggerAsyncId, resource</span>) { }

<span class="hljs-comment">// before() is called just before the resource's callback is called. It can be</span>
<span class="hljs-comment">// called 0-N times for handles (such as TCPWrap), and will be called exactly 1</span>
<span class="hljs-comment">// time for requests (such as FSReqCallback).</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">before</span>(<span class="hljs-params">asyncId</span>) { }

<span class="hljs-comment">// after() is called just after the resource's callback has finished.</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">after</span>(<span class="hljs-params">asyncId</span>) { }

<span class="hljs-comment">// destroy() is called when the resource is destroyed.</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">destroy</span>(<span class="hljs-params">asyncId</span>) { }

<span class="hljs-comment">// promiseResolve() is called only for promise resources, when the</span>
<span class="hljs-comment">// resolve() function passed to the Promise constructor is invoked</span>
<span class="hljs-comment">// (either directly or through other means of resolving a promise).</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">promiseResolve</span>(<span class="hljs-params">asyncId</span>) { }</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>async_hooks.createHook(callbacks)</code><span><a class="mark" href="#all_async_hooks_async_hookscreatehookcallbacks" id="all_async_hooks_async_hookscreatehookcallbacks">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_async_hooks_createhook_callbacks"></a></h3>
<div class="api_metadata">
<span>Added in: v8.1.0</span>
</div>
<ul>
<li><code>callbacks</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> The <a href="#all_async_hooks_hook-callbacks">Hook Callbacks</a> to register
<ul>
<li><code>init</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The <a href="#all_async_hooks_initasyncid-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="#all_async_hooks_beforeasyncid"><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="#all_async_hooks_afterasyncid"><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="#all_async_hooks_destroyasyncid"><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="#all_async_hooks_promiseresolveasyncid"><code>promiseResolve</code> callback</a>.</li>
</ul>
</li>
<li>Returns: <a href="#all_async_hooks_async_hookscreatehookcallbacks" 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="#all_async_hooks_hook-callbacks">Hook Callbacks</a> section.</p>

<pre class="with-48-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createHook } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;

<span class="hljs-keyword">const</span> asyncHook = <span class="hljs-title function_">createHook</span>({
  <span class="hljs-title function_">init</span>(<span class="hljs-params">asyncId, type, triggerAsyncId, resource</span>) { },
  <span class="hljs-title function_">destroy</span>(<span class="hljs-params">asyncId</span>) { },
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> async_hooks = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);

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

<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyAddedCallbacks</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">MyAsyncCallbacks</span> {
  <span class="hljs-title function_">before</span>(<span class="hljs-params">asyncId</span>) { }
  <span class="hljs-title function_">after</span>(<span class="hljs-params">asyncId</span>) { }
}

<span class="hljs-keyword">const</span> asyncHook = async_hooks.<span class="hljs-title function_">createHook</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">MyAddedCallbacks</span>());</code> <button class="copy-button">copy</button></pre>
<p>Because promises are asynchronous resources whose lifecycle is tracked
via the async hooks mechanism, the <code>init()</code>, <code>before()</code>, <code>after()</code>, and
<code>destroy()</code> callbacks <em>must not</em> be async functions that return promises.</p>
<h4>Error handling<span><a class="mark" href="#all_async_hooks_error-handling" id="all_async_hooks_error-handling">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_error_handling"></a></h4>
<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>
<h4>Printing in <code>AsyncHook</code> callbacks<span><a class="mark" href="#all_async_hooks_printing-in-asynchook-callbacks" id="all_async_hooks_printing-in-asynchook-callbacks">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_printing_in_asynchook_callbacks"></a></h4>
<p>Because printing to the console is an asynchronous operation, <code>console.log()</code>
will cause <code>AsyncHook</code> callbacks to be called. Using <code>console.log()</code> or
similar asynchronous operations inside an <code>AsyncHook</code> callback function will
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 <code>AsyncHook</code> recursively because
it is synchronous.</p>

<pre class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { writeFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">import</span> { format } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;

<span class="hljs-keyword">function</span> <span class="hljs-title function_">debug</span>(<span class="hljs-params">...args</span>) {
  <span class="hljs-comment">// Use a function like this one when debugging inside an AsyncHook callback</span>
  <span class="hljs-title function_">writeFileSync</span>(<span class="hljs-string">'log.out'</span>, <span class="hljs-string">`<span class="hljs-subst">${format(...args)}</span>\n`</span>, { <span class="hljs-attr">flag</span>: <span class="hljs-string">'a'</span> });
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

<span class="hljs-keyword">function</span> <span class="hljs-title function_">debug</span>(<span class="hljs-params">...args</span>) {
  <span class="hljs-comment">// Use a function like this one when debugging inside an AsyncHook callback</span>
  fs.<span class="hljs-title function_">writeFileSync</span>(<span class="hljs-string">'log.out'</span>, <span class="hljs-string">`<span class="hljs-subst">${util.format(...args)}</span>\n`</span>, { <span class="hljs-attr">flag</span>: <span class="hljs-string">'a'</span> });
}</code><button class="copy-button">copy</button></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 <code>AsyncHook</code> itself. The logging should then be skipped when
it was the logging itself that caused the <code>AsyncHook</code> callback to be called. By
doing this, the otherwise infinite recursion is broken.</p>
</section><section><h3>Class: <code>AsyncHook</code><span><a class="mark" href="#all_async_hooks_class-asynchook" id="all_async_hooks_class-asynchook">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_class_asynchook"></a></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="#all_async_hooks_asynchookenable" id="all_async_hooks_asynchookenable">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_asynchook_enable"></a></h4>
<ul>
<li>Returns: <a href="#all_async_hooks_async_hookscreatehookcallbacks" 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 no-op.</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 class="with-48-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createHook } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;

<span class="hljs-keyword">const</span> hook = <span class="hljs-title function_">createHook</span>(callbacks).<span class="hljs-title function_">enable</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> async_hooks = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);

<span class="hljs-keyword">const</span> hook = async_hooks.<span class="hljs-title function_">createHook</span>(callbacks).<span class="hljs-title function_">enable</span>();</code><button class="copy-button">copy</button></pre>
<h4><code>asyncHook.disable()</code><span><a class="mark" href="#all_async_hooks_asynchookdisable" id="all_async_hooks_asynchookdisable">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_asynchook_disable"></a></h4>
<ul>
<li>Returns: <a href="#all_async_hooks_async_hookscreatehookcallbacks" 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="#all_async_hooks_hook-callbacks" id="all_async_hooks_hook-callbacks">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_hook_callbacks"></a></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="#all_async_hooks_initasyncid-type-triggerasyncid-resource" id="all_async_hooks_initasyncid-type-triggerasyncid-resource">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_init_asyncid_type_triggerasyncid_resource"></a></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 class="with-72-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:net'</span>;

<span class="hljs-title function_">createServer</span>().<span class="hljs-title function_">listen</span>(<span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) { <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">close</span>(); });
<span class="hljs-comment">// OR</span>
<span class="hljs-built_in">clearTimeout</span>(<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {}, <span class="hljs-number">10</span>));</code><code class="language-js cjs"><span class="hljs-built_in">require</span>(<span class="hljs-string">'node:net'</span>).<span class="hljs-title function_">createServer</span>().<span class="hljs-title function_">listen</span>(<span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) { <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">close</span>(); });
<span class="hljs-comment">// OR</span>
<span class="hljs-built_in">clearTimeout</span>(<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {}, <span class="hljs-number">10</span>));</code><button class="copy-button">copy</button></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="#all_async_hooks_type" id="all_async_hooks_type">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_type"></a></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>
<p>The <code>type</code> of resources created by Node.js itself can change in any Node.js
release. Valid values include <code>TLSWRAP</code>,
<code>TCPWRAP</code>, <code>TCPSERVERWRAP</code>, <code>GETADDRINFOREQWRAP</code>, <code>FSREQCALLBACK</code>,
<code>Microtask</code>, and <code>Timeout</code>. Inspect the source code of the Node.js version used
to get the full list.</p>
<p>Furthermore users of <a href="#all_async_context_class-asyncresource"><code>AsyncResource</code></a> create async resources independent
of Node.js itself.</p>
<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="#all_async_hooks_triggerasyncid" id="all_async_hooks_triggerasyncid">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_triggerasyncid"></a></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 class="with-69-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createHook, executionAsyncId } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;
<span class="hljs-keyword">import</span> { stdout } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">import</span> net <span class="hljs-keyword">from</span> <span class="hljs-string">'node:net'</span>;
<span class="hljs-keyword">import</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-title function_">createHook</span>({
  <span class="hljs-title function_">init</span>(<span class="hljs-params">asyncId, type, triggerAsyncId</span>) {
    <span class="hljs-keyword">const</span> eid = <span class="hljs-title function_">executionAsyncId</span>();
    fs.<span class="hljs-title function_">writeSync</span>(
      stdout.<span class="hljs-property">fd</span>,
      <span class="hljs-string">`<span class="hljs-subst">${type}</span>(<span class="hljs-subst">${asyncId}</span>): trigger: <span class="hljs-subst">${triggerAsyncId}</span> execution: <span class="hljs-subst">${eid}</span>\n`</span>);
  },
}).<span class="hljs-title function_">enable</span>();

net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">conn</span>) =></span> {}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8080</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { createHook, executionAsyncId } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);
<span class="hljs-keyword">const</span> { stdout } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">const</span> net = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:net'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);

<span class="hljs-title function_">createHook</span>({
  <span class="hljs-title function_">init</span>(<span class="hljs-params">asyncId, type, triggerAsyncId</span>) {
    <span class="hljs-keyword">const</span> eid = <span class="hljs-title function_">executionAsyncId</span>();
    fs.<span class="hljs-title function_">writeSync</span>(
      stdout.<span class="hljs-property">fd</span>,
      <span class="hljs-string">`<span class="hljs-subst">${type}</span>(<span class="hljs-subst">${asyncId}</span>): trigger: <span class="hljs-subst">${triggerAsyncId}</span> execution: <span class="hljs-subst">${eid}</span>\n`</span>);
  },
}).<span class="hljs-title function_">enable</span>();

net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">conn</span>) =></span> {}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8080</span>);</code><button class="copy-button">copy</button></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> <button class="copy-button">copy</button></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="#all_async_hooks_resource" id="all_async_hooks_resource">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_resource"></a></h6>
<p><code>resource</code> is an object that represents the actual async resource that has
been initialized. The API to access the object may be specified by the
creator of the resource. Resources created by Node.js itself are internal
and may change at any time. Therefore no API is specified for these.</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="#all_async_hooks_asynchronous-context-example" id="all_async_hooks_asynchronous-context-example">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_asynchronous_context_example"></a></h6>
<p>The context tracking use case is covered by the stable API <a href="#all_async_context_class-asynclocalstorage"><code>AsyncLocalStorage</code></a>.
This example only illustrates async hooks operation but <a href="#all_async_context_class-asynclocalstorage"><code>AsyncLocalStorage</code></a>
fits better to this use case.</p>
<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 class="with-48-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> async_hooks <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;
<span class="hljs-keyword">import</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">import</span> net <span class="hljs-keyword">from</span> <span class="hljs-string">'node:net'</span>;
<span class="hljs-keyword">import</span> { stdout } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">const</span> { fd } = stdout;

<span class="hljs-keyword">let</span> indent = <span class="hljs-number">0</span>;
async_hooks.<span class="hljs-title function_">createHook</span>({
  <span class="hljs-title function_">init</span>(<span class="hljs-params">asyncId, type, triggerAsyncId</span>) {
    <span class="hljs-keyword">const</span> eid = async_hooks.<span class="hljs-title function_">executionAsyncId</span>();
    <span class="hljs-keyword">const</span> indentStr = <span class="hljs-string">' '</span>.<span class="hljs-title function_">repeat</span>(indent);
    fs.<span class="hljs-title function_">writeSync</span>(
      fd,
      <span class="hljs-string">`<span class="hljs-subst">${indentStr}</span><span class="hljs-subst">${type}</span>(<span class="hljs-subst">${asyncId}</span>):`</span> +
      <span class="hljs-string">` trigger: <span class="hljs-subst">${triggerAsyncId}</span> execution: <span class="hljs-subst">${eid}</span>\n`</span>);
  },
  <span class="hljs-title function_">before</span>(<span class="hljs-params">asyncId</span>) {
    <span class="hljs-keyword">const</span> indentStr = <span class="hljs-string">' '</span>.<span class="hljs-title function_">repeat</span>(indent);
    fs.<span class="hljs-title function_">writeSync</span>(fd, <span class="hljs-string">`<span class="hljs-subst">${indentStr}</span>before:  <span class="hljs-subst">${asyncId}</span>\n`</span>);
    indent += <span class="hljs-number">2</span>;
  },
  <span class="hljs-title function_">after</span>(<span class="hljs-params">asyncId</span>) {
    indent -= <span class="hljs-number">2</span>;
    <span class="hljs-keyword">const</span> indentStr = <span class="hljs-string">' '</span>.<span class="hljs-title function_">repeat</span>(indent);
    fs.<span class="hljs-title function_">writeSync</span>(fd, <span class="hljs-string">`<span class="hljs-subst">${indentStr}</span>after:  <span class="hljs-subst">${asyncId}</span>\n`</span>);
  },
  <span class="hljs-title function_">destroy</span>(<span class="hljs-params">asyncId</span>) {
    <span class="hljs-keyword">const</span> indentStr = <span class="hljs-string">' '</span>.<span class="hljs-title function_">repeat</span>(indent);
    fs.<span class="hljs-title function_">writeSync</span>(fd, <span class="hljs-string">`<span class="hljs-subst">${indentStr}</span>destroy:  <span class="hljs-subst">${asyncId}</span>\n`</span>);
  },
}).<span class="hljs-title function_">enable</span>();

net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">() =></span> {}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8080</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-comment">// Let's wait 10ms before logging the server started.</span>
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'>>>'</span>, async_hooks.<span class="hljs-title function_">executionAsyncId</span>());
  }, <span class="hljs-number">10</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> async_hooks = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> net = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:net'</span>);
<span class="hljs-keyword">const</span> { fd } = process.<span class="hljs-property">stdout</span>;

<span class="hljs-keyword">let</span> indent = <span class="hljs-number">0</span>;
async_hooks.<span class="hljs-title function_">createHook</span>({
  <span class="hljs-title function_">init</span>(<span class="hljs-params">asyncId, type, triggerAsyncId</span>) {
    <span class="hljs-keyword">const</span> eid = async_hooks.<span class="hljs-title function_">executionAsyncId</span>();
    <span class="hljs-keyword">const</span> indentStr = <span class="hljs-string">' '</span>.<span class="hljs-title function_">repeat</span>(indent);
    fs.<span class="hljs-title function_">writeSync</span>(
      fd,
      <span class="hljs-string">`<span class="hljs-subst">${indentStr}</span><span class="hljs-subst">${type}</span>(<span class="hljs-subst">${asyncId}</span>):`</span> +
      <span class="hljs-string">` trigger: <span class="hljs-subst">${triggerAsyncId}</span> execution: <span class="hljs-subst">${eid}</span>\n`</span>);
  },
  <span class="hljs-title function_">before</span>(<span class="hljs-params">asyncId</span>) {
    <span class="hljs-keyword">const</span> indentStr = <span class="hljs-string">' '</span>.<span class="hljs-title function_">repeat</span>(indent);
    fs.<span class="hljs-title function_">writeSync</span>(fd, <span class="hljs-string">`<span class="hljs-subst">${indentStr}</span>before:  <span class="hljs-subst">${asyncId}</span>\n`</span>);
    indent += <span class="hljs-number">2</span>;
  },
  <span class="hljs-title function_">after</span>(<span class="hljs-params">asyncId</span>) {
    indent -= <span class="hljs-number">2</span>;
    <span class="hljs-keyword">const</span> indentStr = <span class="hljs-string">' '</span>.<span class="hljs-title function_">repeat</span>(indent);
    fs.<span class="hljs-title function_">writeSync</span>(fd, <span class="hljs-string">`<span class="hljs-subst">${indentStr}</span>after:  <span class="hljs-subst">${asyncId}</span>\n`</span>);
  },
  <span class="hljs-title function_">destroy</span>(<span class="hljs-params">asyncId</span>) {
    <span class="hljs-keyword">const</span> indentStr = <span class="hljs-string">' '</span>.<span class="hljs-title function_">repeat</span>(indent);
    fs.<span class="hljs-title function_">writeSync</span>(fd, <span class="hljs-string">`<span class="hljs-subst">${indentStr}</span>destroy:  <span class="hljs-subst">${asyncId}</span>\n`</span>);
  },
}).<span class="hljs-title function_">enable</span>();

net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">() =></span> {}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8080</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-comment">// Let's wait 10ms before logging the server started.</span>
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'>>>'</span>, async_hooks.<span class="hljs-title function_">executionAsyncId</span>());
  }, <span class="hljs-number">10</span>);
});</code><button class="copy-button">copy</button></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
<span class="hljs-meta prompt_">></span><span class="language-bash">>> 7</span>
  TickObject(8): trigger: 7 execution: 7
after:   7
before:  8
after:   8</code> <button class="copy-button">copy</button></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">  root(1)
     ^
     |
TickObject(6)
     ^
     |
 Timeout(7)</code> <button class="copy-button">copy</button></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>. Which is why
<code>TickObject</code> is present in the output and is a 'parent' for <code>.listen()</code>
callback.</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>. Which can be represented with the following
graph:</p>
<pre><code class="language-console"> bootstrap(1)
     |
     ˅
TCPSERVERWRAP(5)
     |
     ˅
 TickObject(6)
     |
     ˅
  Timeout(7)</code> <button class="copy-button">copy</button></pre>
<h5><code>before(asyncId)</code><span><a class="mark" href="#all_async_hooks_beforeasyncid" id="all_async_hooks_beforeasyncid">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_before_asyncid"></a></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="#all_async_hooks_afterasyncid" id="all_async_hooks_afterasyncid">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_after_asyncid"></a></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="#all_async_hooks_destroyasyncid" id="all_async_hooks_destroyasyncid">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_destroy_asyncid"></a></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>
<p>Using the destroy hook results in additional overhead because it enables
tracking of <code>Promise</code> instances via the garbage collector.</p>
<h5><code>promiseResolve(asyncId)</code><span><a class="mark" href="#all_async_hooks_promiseresolveasyncid" id="all_async_hooks_promiseresolveasyncid">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_promiseresolve_asyncid"></a></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"><span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =></span> <span class="hljs-title function_">resolve</span>(<span class="hljs-literal">true</span>)).<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">a</span>) =></span> {});</code> <button class="copy-button">copy</button></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> <button class="copy-button">copy</button></pre>
<h4><code>async_hooks.executionAsyncResource()</code><span><a class="mark" href="#all_async_hooks_async_hooksexecutionasyncresource" id="all_async_hooks_async_hooksexecutionasyncresource">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_async_hooks_executionasyncresource"></a></h4>
<div class="api_metadata">
<span>Added in: v13.9.0, 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 class="with-81-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { open } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">import</span> { executionAsyncId, executionAsyncResource } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">executionAsyncId</span>(), <span class="hljs-title function_">executionAsyncResource</span>());  <span class="hljs-comment">// 1 {}</span>
<span class="hljs-title function_">open</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>), <span class="hljs-string">'r'</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">executionAsyncId</span>(), <span class="hljs-title function_">executionAsyncResource</span>());  <span class="hljs-comment">// 7 FSReqWrap</span>
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { open } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> { executionAsyncId, executionAsyncResource } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">executionAsyncId</span>(), <span class="hljs-title function_">executionAsyncResource</span>());  <span class="hljs-comment">// 1 {}</span>
<span class="hljs-title function_">open</span>(__filename, <span class="hljs-string">'r'</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">executionAsyncId</span>(), <span class="hljs-title function_">executionAsyncResource</span>());  <span class="hljs-comment">// 7 FSReqWrap</span>
});</code><button class="copy-button">copy</button></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 class="with-46-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;
<span class="hljs-keyword">import</span> {
  executionAsyncId,
  executionAsyncResource,
  createHook,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;
<span class="hljs-keyword">const</span> sym = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'state'</span>); <span class="hljs-comment">// Private symbol to avoid pollution</span>

<span class="hljs-title function_">createHook</span>({
  <span class="hljs-title function_">init</span>(<span class="hljs-params">asyncId, type, triggerAsyncId, resource</span>) {
    <span class="hljs-keyword">const</span> cr = <span class="hljs-title function_">executionAsyncResource</span>();
    <span class="hljs-keyword">if</span> (cr) {
      resource[sym] = cr[sym];
    }
  },
}).<span class="hljs-title function_">enable</span>();

<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
  <span class="hljs-title function_">executionAsyncResource</span>()[sym] = { <span class="hljs-attr">state</span>: req.<span class="hljs-property">url</span> };
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) {
    res.<span class="hljs-title function_">end</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(<span class="hljs-title function_">executionAsyncResource</span>()[sym]));
  }, <span class="hljs-number">100</span>);
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">3000</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { createServer } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);
<span class="hljs-keyword">const</span> {
  executionAsyncId,
  executionAsyncResource,
  createHook,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);
<span class="hljs-keyword">const</span> sym = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'state'</span>); <span class="hljs-comment">// Private symbol to avoid pollution</span>

<span class="hljs-title function_">createHook</span>({
  <span class="hljs-title function_">init</span>(<span class="hljs-params">asyncId, type, triggerAsyncId, resource</span>) {
    <span class="hljs-keyword">const</span> cr = <span class="hljs-title function_">executionAsyncResource</span>();
    <span class="hljs-keyword">if</span> (cr) {
      resource[sym] = cr[sym];
    }
  },
}).<span class="hljs-title function_">enable</span>();

<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
  <span class="hljs-title function_">executionAsyncResource</span>()[sym] = { <span class="hljs-attr">state</span>: req.<span class="hljs-property">url</span> };
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) {
    res.<span class="hljs-title function_">end</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(<span class="hljs-title function_">executionAsyncResource</span>()[sym]));
  }, <span class="hljs-number">100</span>);
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">3000</span>);</code><button class="copy-button">copy</button></pre>
<h4><code>async_hooks.executionAsyncId()</code><span><a class="mark" href="#all_async_hooks_async_hooksexecutionasyncid" id="all_async_hooks_async_hooksexecutionasyncid">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_async_hooks_executionasyncid"></a></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 class="with-52-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { executionAsyncId } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;
<span class="hljs-keyword">import</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">executionAsyncId</span>());  <span class="hljs-comment">// 1 - bootstrap</span>
<span class="hljs-keyword">const</span> path = <span class="hljs-string">'.'</span>;
fs.<span class="hljs-title function_">open</span>(path, <span class="hljs-string">'r'</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">executionAsyncId</span>());  <span class="hljs-comment">// 6 - open()</span>
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> async_hooks = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(async_hooks.<span class="hljs-title function_">executionAsyncId</span>());  <span class="hljs-comment">// 1 - bootstrap</span>
<span class="hljs-keyword">const</span> path = <span class="hljs-string">'.'</span>;
fs.<span class="hljs-title function_">open</span>(path, <span class="hljs-string">'r'</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(async_hooks.<span class="hljs-title function_">executionAsyncId</span>());  <span class="hljs-comment">// 6 - open()</span>
});</code><button class="copy-button">copy</button></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"><span class="hljs-keyword">const</span> server = net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">conn</span>) =></span> {
  <span class="hljs-comment">// Returns the ID of the server, not of the new connection, because the</span>
  <span class="hljs-comment">// callback runs in the execution scope of the server's MakeCallback().</span>
  async_hooks.<span class="hljs-title function_">executionAsyncId</span>();

}).<span class="hljs-title function_">listen</span>(port, <span class="hljs-function">() =></span> {
  <span class="hljs-comment">// Returns the ID of a TickObject (process.nextTick()) because all</span>
  <span class="hljs-comment">// callbacks passed to .listen() are wrapped in a nextTick().</span>
  async_hooks.<span class="hljs-title function_">executionAsyncId</span>();
});</code> <button class="copy-button">copy</button></pre>
<p>Promise contexts may not get precise <code>executionAsyncIds</code> by default.
See the section on <a href="#all_async_hooks_promise-execution-tracking">promise execution tracking</a>.</p>
<h4><code>async_hooks.triggerAsyncId()</code><span><a class="mark" href="#all_async_hooks_async_hookstriggerasyncid" id="all_async_hooks_async_hookstriggerasyncid">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_async_hooks_triggerasyncid"></a></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"><span class="hljs-keyword">const</span> server = net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">conn</span>) =></span> {
  <span class="hljs-comment">// The resource that caused (or triggered) this callback to be called</span>
  <span class="hljs-comment">// was that of the new connection. Thus the return value of triggerAsyncId()</span>
  <span class="hljs-comment">// is the asyncId of "conn".</span>
  async_hooks.<span class="hljs-title function_">triggerAsyncId</span>();

}).<span class="hljs-title function_">listen</span>(port, <span class="hljs-function">() =></span> {
  <span class="hljs-comment">// Even though all callbacks passed to .listen() are wrapped in a nextTick()</span>
  <span class="hljs-comment">// the callback itself exists because the call to the server's .listen()</span>
  <span class="hljs-comment">// was made. So the return value would be the ID of the server.</span>
  async_hooks.<span class="hljs-title function_">triggerAsyncId</span>();
});</code> <button class="copy-button">copy</button></pre>
<p>Promise contexts may not get valid <code>triggerAsyncId</code>s by default. See
the section on <a href="#all_async_hooks_promise-execution-tracking">promise execution tracking</a>.</p>
<h4><code>async_hooks.asyncWrapProviders</code><span><a class="mark" href="#all_async_hooks_async_hooksasyncwrapproviders" id="all_async_hooks_async_hooksasyncwrapproviders">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_async_hooks_asyncwrapproviders"></a></h4>
<div class="api_metadata">
<span>Added in: v17.2.0, v16.14.0</span>
</div>
<ul>
<li>Returns: A map of provider types to the corresponding numeric id.
This map contains all the event types that might be emitted by the <code>async_hooks.init()</code> event.</li>
</ul>
<p>This feature suppresses the deprecated usage of <code>process.binding('async_wrap').Providers</code>.
See: <a href="#all_deprecations_dep0111-processbinding">DEP0111</a></p>
</section><section><h3>Promise execution tracking<span><a class="mark" href="#all_async_hooks_promise-execution-tracking" id="all_async_hooks_promise-execution-tracking">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_promise_execution_tracking"></a></h3>
<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 class="with-73-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { executionAsyncId, triggerAsyncId } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;

<span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">resolve</span>(<span class="hljs-number">1729</span>).<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`eid <span class="hljs-subst">${executionAsyncId()}</span> tid <span class="hljs-subst">${triggerAsyncId()}</span>`</span>);
});
<span class="hljs-comment">// produces:</span>
<span class="hljs-comment">// eid 1 tid 0</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { executionAsyncId, triggerAsyncId } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);

<span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">resolve</span>(<span class="hljs-number">1729</span>).<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`eid <span class="hljs-subst">${executionAsyncId()}</span> tid <span class="hljs-subst">${triggerAsyncId()}</span>`</span>);
});
<span class="hljs-comment">// produces:</span>
<span class="hljs-comment">// eid 1 tid 0</span></code><button class="copy-button">copy</button></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 class="with-85-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createHook, executionAsyncId, triggerAsyncId } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;
<span class="hljs-title function_">createHook</span>({ <span class="hljs-title function_">init</span>(<span class="hljs-params"></span>) {} }).<span class="hljs-title function_">enable</span>(); <span class="hljs-comment">// forces PromiseHooks to be enabled.</span>
<span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">resolve</span>(<span class="hljs-number">1729</span>).<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`eid <span class="hljs-subst">${executionAsyncId()}</span> tid <span class="hljs-subst">${triggerAsyncId()}</span>`</span>);
});
<span class="hljs-comment">// produces:</span>
<span class="hljs-comment">// eid 7 tid 6</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { createHook, executionAsyncId, triggerAsyncId } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);

<span class="hljs-title function_">createHook</span>({ <span class="hljs-title function_">init</span>(<span class="hljs-params"></span>) {} }).<span class="hljs-title function_">enable</span>(); <span class="hljs-comment">// forces PromiseHooks to be enabled.</span>
<span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">resolve</span>(<span class="hljs-number">1729</span>).<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`eid <span class="hljs-subst">${executionAsyncId()}</span> tid <span class="hljs-subst">${triggerAsyncId()}</span>`</span>);
});
<span class="hljs-comment">// produces:</span>
<span class="hljs-comment">// eid 7 tid 6</span></code><button class="copy-button">copy</button></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>
</section><section><h3>JavaScript embedder API<span><a class="mark" href="#all_async_hooks_javascript-embedder-api" id="all_async_hooks_javascript-embedder-api">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_javascript_embedder_api"></a></h3>
<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>
<h4>Class: <code>AsyncResource</code><span><a class="mark" href="#all_async_hooks_class-asyncresource" id="all_async_hooks_class-asyncresource">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_class_asyncresource"></a></h4>
<p>The documentation for this class has moved <a href="#all_async_context_class-asyncresource"><code>AsyncResource</code></a>.</p>
</section><section><h3>Class: <code>AsyncLocalStorage</code><span><a class="mark" href="#all_async_hooks_class-asynclocalstorage" id="all_async_hooks_class-asynclocalstorage">#</a></span><a aria-hidden="true" class="legacy" id="async_hooks_class_asynclocalstorage"></a></h3>
<p>The documentation for this class has moved <a href="#all_async_context_class-asynclocalstorage"><code>AsyncLocalStorage</code></a>.</p></section>
        </section>
<section><h2>Buffer<span><a class="mark" href="#all_buffer_buffer" id="all_buffer_buffer">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buffer"></a></h2>

<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/buffer.js">lib/buffer.js</a></p>
<p><code>Buffer</code> objects are used to represent a fixed-length sequence of bytes. Many
Node.js APIs support <code>Buffer</code>s.</p>
<p>The <code>Buffer</code> class is a subclass of JavaScript's <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a> class and
extends it with methods 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>While the <code>Buffer</code> class is available within the global scope, it is still
recommended to explicitly reference it via an import or require statement.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-comment">// Creates a zero-filled Buffer of length 10.</span>
<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">10</span>);

<span class="hljs-comment">// Creates a Buffer of length 10,</span>
<span class="hljs-comment">// filled with bytes which all have the value `1`.</span>
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">10</span>, <span class="hljs-number">1</span>);

<span class="hljs-comment">// Creates an uninitialized buffer of length 10.</span>
<span class="hljs-comment">// This is faster than calling Buffer.alloc() but the returned</span>
<span class="hljs-comment">// Buffer instance might contain old data that needs to be</span>
<span class="hljs-comment">// overwritten using fill(), write(), or other functions that fill the Buffer's</span>
<span class="hljs-comment">// contents.</span>
<span class="hljs-keyword">const</span> buf3 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">10</span>);

<span class="hljs-comment">// Creates a Buffer containing the bytes [1, 2, 3].</span>
<span class="hljs-keyword">const</span> buf4 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]);

<span class="hljs-comment">// Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries</span>
<span class="hljs-comment">// are all truncated using `(value &#x26; 255)` to fit into the range 0–255.</span>
<span class="hljs-keyword">const</span> buf5 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">257</span>, <span class="hljs-number">257.5</span>, -<span class="hljs-number">255</span>, <span class="hljs-string">'1'</span>]);

<span class="hljs-comment">// Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést':</span>
<span class="hljs-comment">// [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation)</span>
<span class="hljs-comment">// [116, 195, 169, 115, 116] (in decimal notation)</span>
<span class="hljs-keyword">const</span> buf6 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'tést'</span>);

<span class="hljs-comment">// Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74].</span>
<span class="hljs-keyword">const</span> buf7 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'tést'</span>, <span class="hljs-string">'latin1'</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-comment">// Creates a zero-filled Buffer of length 10.</span>
<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">10</span>);

<span class="hljs-comment">// Creates a Buffer of length 10,</span>
<span class="hljs-comment">// filled with bytes which all have the value `1`.</span>
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">10</span>, <span class="hljs-number">1</span>);

<span class="hljs-comment">// Creates an uninitialized buffer of length 10.</span>
<span class="hljs-comment">// This is faster than calling Buffer.alloc() but the returned</span>
<span class="hljs-comment">// Buffer instance might contain old data that needs to be</span>
<span class="hljs-comment">// overwritten using fill(), write(), or other functions that fill the Buffer's</span>
<span class="hljs-comment">// contents.</span>
<span class="hljs-keyword">const</span> buf3 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">10</span>);

<span class="hljs-comment">// Creates a Buffer containing the bytes [1, 2, 3].</span>
<span class="hljs-keyword">const</span> buf4 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]);

<span class="hljs-comment">// Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries</span>
<span class="hljs-comment">// are all truncated using `(value &#x26; 255)` to fit into the range 0–255.</span>
<span class="hljs-keyword">const</span> buf5 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">257</span>, <span class="hljs-number">257.5</span>, -<span class="hljs-number">255</span>, <span class="hljs-string">'1'</span>]);

<span class="hljs-comment">// Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést':</span>
<span class="hljs-comment">// [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation)</span>
<span class="hljs-comment">// [116, 195, 169, 115, 116] (in decimal notation)</span>
<span class="hljs-keyword">const</span> buf6 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'tést'</span>);

<span class="hljs-comment">// Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74].</span>
<span class="hljs-keyword">const</span> buf7 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'tést'</span>, <span class="hljs-string">'latin1'</span>);</code><button class="copy-button">copy</button></pre>
<section><h3>Buffers and character encodings<span><a class="mark" href="#all_buffer_buffers-and-character-encodings" id="all_buffer_buffers-and-character-encodings">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buffers_and_character_encodings"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.7.0, v14.18.0</td>
<td><p>Introduced <code>base64url</code> encoding.</p></td></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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'hello world'</span>, <span class="hljs-string">'utf8'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// Prints: 68656c6c6f20776f726c64</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'base64'</span>));
<span class="hljs-comment">// Prints: aGVsbG8gd29ybGQ=</span>

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'fhqwhgads'</span>, <span class="hljs-string">'utf8'</span>));
<span class="hljs-comment">// Prints: &#x3C;Buffer 66 68 71 77 68 67 61 64 73></span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'fhqwhgads'</span>, <span class="hljs-string">'utf16le'</span>));
<span class="hljs-comment">// Prints: &#x3C;Buffer 66 00 68 00 71 00 77 00 68 00 67 00 61 00 64 00 73 00></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'hello world'</span>, <span class="hljs-string">'utf8'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// Prints: 68656c6c6f20776f726c64</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'base64'</span>));
<span class="hljs-comment">// Prints: aGVsbG8gd29ybGQ=</span>

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'fhqwhgads'</span>, <span class="hljs-string">'utf8'</span>));
<span class="hljs-comment">// Prints: &#x3C;Buffer 66 68 71 77 68 67 61 64 73></span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'fhqwhgads'</span>, <span class="hljs-string">'utf16le'</span>));
<span class="hljs-comment">// Prints: &#x3C;Buffer 66 00 68 00 71 00 77 00 68 00 67 00 61 00 64 00 73 00></span></code><button class="copy-button">copy</button></pre>
<p>Node.js buffers accept all case variations of encoding strings that they
receive. For example, UTF-8 can be specified as <code>'utf8'</code>, <code>'UTF8'</code>, or <code>'uTf8'</code>.</p>
<p>The character encodings currently supported by Node.js are the following:</p>
<ul>
<li>
<p><code>'utf8'</code> (alias: <code>'utf-8'</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> (alias: <code>'utf-16le'</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 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>. Whitespace characters such as spaces,
tabs, and new lines contained within the base64-encoded string are ignored.</p>
</li>
<li>
<p><code>'base64url'</code>: <a href="https://tools.ietf.org/html/rfc4648#section-5">base64url</a> encoding as specified in
<a href="https://tools.ietf.org/html/rfc4648#section-5">RFC 4648, Section 5</a>. When creating a <code>Buffer</code> from a string, this
encoding will also correctly accept regular base64-encoded strings. When
encoding a <code>Buffer</code> to a string, this encoding will omit padding.</p>
</li>
<li>
<p><code>'hex'</code>: Encode each byte as two hexadecimal characters. Data truncation
may occur when decoding strings that do not exclusively consist of an even
number of 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 this encoding 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>.
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>'utf8'</code> is the right choice.</p>
</li>
<li>
<p><code>'ucs2'</code>, <code>'ucs-2'</code>: Aliases 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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'1ag123'</span>, <span class="hljs-string">'hex'</span>);
<span class="hljs-comment">// Prints &#x3C;Buffer 1a>, data truncated when first non-hexadecimal value</span>
<span class="hljs-comment">// ('g') encountered.</span>

<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'1a7'</span>, <span class="hljs-string">'hex'</span>);
<span class="hljs-comment">// Prints &#x3C;Buffer 1a>, data truncated when data ends in single digit ('7').</span>

<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'1634'</span>, <span class="hljs-string">'hex'</span>);
<span class="hljs-comment">// Prints &#x3C;Buffer 16 34>, all data represented.</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'1ag123'</span>, <span class="hljs-string">'hex'</span>);
<span class="hljs-comment">// Prints &#x3C;Buffer 1a>, data truncated when first non-hexadecimal value</span>
<span class="hljs-comment">// ('g') encountered.</span>

<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'1a7'</span>, <span class="hljs-string">'hex'</span>);
<span class="hljs-comment">// Prints &#x3C;Buffer 1a>, data truncated when data ends in single digit ('7').</span>

<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'1634'</span>, <span class="hljs-string">'hex'</span>);
<span class="hljs-comment">// Prints &#x3C;Buffer 16 34>, all data represented.</span></code><button class="copy-button">copy</button></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>
</section><section><h3>Buffers and TypedArrays<span><a class="mark" href="#all_buffer_buffers-and-typedarrays" id="all_buffer_buffers-and-typedarrays">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buffers_and_typedarrays"></a></h3>
<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 JavaScript <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a>
instances. All <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a> methods are available on <code>Buffer</code>s. There are,
however, 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.prototype.slice()</code></a> creates a copy of part of the <code>TypedArray</code>,
<a href="#all_buffer_bufslicestart-end"><code>Buffer.prototype.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.prototype.subarray()</code></a> can be used to achieve
the behavior of <a href="#all_buffer_bufslicestart-end"><code>Buffer.prototype.slice()</code></a> on both <code>Buffer</code>s
and other <code>TypedArray</code>s and should be preferred.</li>
<li><a href="#all_buffer_buftostringencoding-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="#all_buffer_bufindexofvalue-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>
<ul>
<li>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 will copy the <code>Buffer</code>s
contents, interpreted as an array of integers, and not as a byte sequence
of the target type.</li>
</ul>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]);
<span class="hljs-keyword">const</span> uint32array = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint32Array</span>(buf);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(uint32array);

<span class="hljs-comment">// Prints: Uint32Array(4) [ 1, 2, 3, 4 ]</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]);
<span class="hljs-keyword">const</span> uint32array = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint32Array</span>(buf);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(uint32array);

<span class="hljs-comment">// Prints: Uint32Array(4) [ 1, 2, 3, 4 ]</span></code><button class="copy-button">copy</button></pre>
<ul>
<li>Passing the <code>Buffer</code>s underlying <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a> will 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>.</li>
</ul>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'hello'</span>, <span class="hljs-string">'utf16le'</span>);
<span class="hljs-keyword">const</span> uint16array = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint16Array</span>(
  buf.<span class="hljs-property">buffer</span>,
  buf.<span class="hljs-property">byteOffset</span>,
  buf.<span class="hljs-property">length</span> / <span class="hljs-title class_">Uint16Array</span>.<span class="hljs-property">BYTES_PER_ELEMENT</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(uint16array);

<span class="hljs-comment">// Prints: Uint16Array(5) [ 104, 101, 108, 108, 111 ]</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'hello'</span>, <span class="hljs-string">'utf16le'</span>);
<span class="hljs-keyword">const</span> uint16array = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint16Array</span>(
  buf.<span class="hljs-property">buffer</span>,
  buf.<span class="hljs-property">byteOffset</span>,
  buf.<span class="hljs-property">length</span> / <span class="hljs-title class_">Uint16Array</span>.<span class="hljs-property">BYTES_PER_ELEMENT</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(uint16array);

<span class="hljs-comment">// Prints: Uint16Array(5) [ 104, 101, 108, 108, 111 ]</span></code><button class="copy-button">copy</button></pre>
<p>It is possible to create a new <code>Buffer</code> that shares the same allocated
memory as a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a> instance by using the <code>TypedArray</code> object's
<code>.buffer</code> property in the same way. <a href="#all_buffer_static-method-bufferfromarraybuffer-byteoffset-length"><code>Buffer.from()</code></a>
behaves like <code>new Uint8Array()</code> in this context.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> arr = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint16Array</span>(<span class="hljs-number">2</span>);

arr[<span class="hljs-number">0</span>] = <span class="hljs-number">5000</span>;
arr[<span class="hljs-number">1</span>] = <span class="hljs-number">4000</span>;

<span class="hljs-comment">// Copies the contents of `arr`.</span>
<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(arr);

<span class="hljs-comment">// Shares memory with `arr`.</span>
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(arr.<span class="hljs-property">buffer</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1);
<span class="hljs-comment">// Prints: &#x3C;Buffer 88 a0></span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2);
<span class="hljs-comment">// Prints: &#x3C;Buffer 88 13 a0 0f></span>

arr[<span class="hljs-number">1</span>] = <span class="hljs-number">6000</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1);
<span class="hljs-comment">// Prints: &#x3C;Buffer 88 a0></span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2);
<span class="hljs-comment">// Prints: &#x3C;Buffer 88 13 70 17></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> arr = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint16Array</span>(<span class="hljs-number">2</span>);

arr[<span class="hljs-number">0</span>] = <span class="hljs-number">5000</span>;
arr[<span class="hljs-number">1</span>] = <span class="hljs-number">4000</span>;

<span class="hljs-comment">// Copies the contents of `arr`.</span>
<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(arr);

<span class="hljs-comment">// Shares memory with `arr`.</span>
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(arr.<span class="hljs-property">buffer</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1);
<span class="hljs-comment">// Prints: &#x3C;Buffer 88 a0></span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2);
<span class="hljs-comment">// Prints: &#x3C;Buffer 88 13 a0 0f></span>

arr[<span class="hljs-number">1</span>] = <span class="hljs-number">6000</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1);
<span class="hljs-comment">// Prints: &#x3C;Buffer 88 a0></span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2);
<span class="hljs-comment">// Prints: &#x3C;Buffer 88 13 70 17></span></code><button class="copy-button">copy</button></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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> arr = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint16Array</span>(<span class="hljs-number">20</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(arr.<span class="hljs-property">buffer</span>, <span class="hljs-number">0</span>, <span class="hljs-number">16</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-property">length</span>);
<span class="hljs-comment">// Prints: 16</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> arr = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint16Array</span>(<span class="hljs-number">20</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(arr.<span class="hljs-property">buffer</span>, <span class="hljs-number">0</span>, <span class="hljs-number">16</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-property">length</span>);
<span class="hljs-comment">// Prints: 16</span></code><button class="copy-button">copy</button></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="#all_buffer_static-method-bufferfromarray"><code>Buffer.from(array)</code></a></li>
<li><a href="#all_buffer_static-method-bufferfrombuffer"><code>Buffer.from(buffer)</code></a></li>
<li><a href="#all_buffer_static-method-bufferfromarraybuffer-byteoffset-length"><code>Buffer.from(arrayBuffer[, byteOffset[, length]])</code></a></li>
<li><a href="#all_buffer_static-method-bufferfromstring-encoding"><code>Buffer.from(string[, encoding])</code></a></li>
</ul>
</section><section><h3>Buffers and iteration<span><a class="mark" href="#all_buffer_buffers-and-iteration" id="all_buffer_buffers-and-iteration">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buffers_and_iteration"></a></h3>
<p><code>Buffer</code> instances can be iterated over using <code>for..of</code> syntax:</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]);

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> b <span class="hljs-keyword">of</span> buf) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b);
}
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   1</span>
<span class="hljs-comment">//   2</span>
<span class="hljs-comment">//   3</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]);

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> b <span class="hljs-keyword">of</span> buf) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b);
}
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   1</span>
<span class="hljs-comment">//   2</span>
<span class="hljs-comment">//   3</span></code><button class="copy-button">copy</button></pre>
<p>Additionally, the <a href="#all_buffer_bufvalues"><code>buf.values()</code></a>, <a href="#all_buffer_bufkeys"><code>buf.keys()</code></a>, and
<a href="#all_buffer_bufentries"><code>buf.entries()</code></a> methods can be used to create iterators.</p>
</section><section><h3>Class: <code>Blob</code><span><a class="mark" href="#all_buffer_class-blob" id="all_buffer_class-blob">#</a></span><a aria-hidden="true" class="legacy" id="buffer_class_blob"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0, v16.17.0</td>
<td><p>No longer experimental.</p></td></tr>
<tr><td>v15.7.0, v14.18.0</td>
<td><p><span>Added in: v15.7.0, v14.18.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>A <a href="https://developer.mozilla.org/en-US/docs/Web/API/Blob"><code>Blob</code></a> encapsulates immutable, raw data that can be safely shared across
multiple worker threads.</p>
<h4><code>new buffer.Blob([sources[, options]])</code><span><a class="mark" href="#all_buffer_new-bufferblobsources-options" id="all_buffer_new-bufferblobsources-options">#</a></span><a aria-hidden="true" class="legacy" id="buffer_new_buffer_blob_sources_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.7.0</td>
<td><p>Added the standard <code>endings</code> option to replace line-endings, and removed the non-standard <code>encoding</code> option.</p></td></tr>
<tr><td>v15.7.0, v14.18.0</td>
<td><p><span>Added in: v15.7.0, v14.18.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>sources</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/ArrayBuffer" class="type">&#x3C;ArrayBuffer[]></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="#all_buffer_class-blob" class="type">&#x3C;Blob[]></a> An
array of string, <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/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>, or <a href="#all_buffer_class-blob" class="type">&#x3C;Blob></a> objects,
or any mix of such objects, that will be stored within the <code>Blob</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>
<ul>
<li><code>endings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> One of either <code>'transparent'</code> or <code>'native'</code>. When set
to <code>'native'</code>, line endings in string source parts will be converted to
the platform native line-ending as specified by <code>require('node:os').EOL</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> The Blob content-type. The intent is for <code>type</code> to convey
the MIME media type of the data, however no validation of the type format
is performed.</li>
</ul>
</li>
</ul>
<p>Creates a new <code>Blob</code> object containing a concatenation of the given sources.</p>
<p><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/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>, and <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> sources are copied into
the 'Blob' and can therefore be safely modified after the 'Blob' is created.</p>
<p>String sources are encoded as UTF-8 byte sequences and copied into the Blob.
Unmatched surrogate pairs within each string part will be replaced by Unicode
U+FFFD replacement characters.</p>
<h4><code>blob.arrayBuffer()</code><span><a class="mark" href="#all_buffer_blobarraybuffer" id="all_buffer_blobarraybuffer">#</a></span><a aria-hidden="true" class="legacy" id="buffer_blob_arraybuffer"></a></h4>
<div class="api_metadata">
<span>Added in: v15.7.0, v14.18.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>Returns a promise that fulfills with an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> containing a copy of
the <code>Blob</code> data.</p>
<h5><code>blob.bytes()</code><span><a class="mark" href="#all_buffer_blobbytes" id="all_buffer_blobbytes">#</a></span><a aria-hidden="true" class="legacy" id="buffer_blob_bytes"></a></h5>
<div class="api_metadata">
<span>Added in: v22.3.0, v20.16.0</span>
</div>
<p>The <code>blob.bytes()</code> method returns the byte of the <code>Blob</code> object as a <code>Promise&#x3C;Uint8Array></code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> blob = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Blob</span>([<span class="hljs-string">'hello'</span>]);
blob.<span class="hljs-title function_">bytes</span>().<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">bytes</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(bytes); <span class="hljs-comment">// Outputs: Uint8Array(5) [ 104, 101, 108, 108, 111 ]</span>
});</code> <button class="copy-button">copy</button></pre>
<h4><code>blob.size</code><span><a class="mark" href="#all_buffer_blobsize" id="all_buffer_blobsize">#</a></span><a aria-hidden="true" class="legacy" id="buffer_blob_size"></a></h4>
<div class="api_metadata">
<span>Added in: v15.7.0, v14.18.0</span>
</div>
<p>The total size of the <code>Blob</code> in bytes.</p>
<h4><code>blob.slice([start[, end[, type]]])</code><span><a class="mark" href="#all_buffer_blobslicestart-end-type" id="all_buffer_blobslicestart-end-type">#</a></span><a aria-hidden="true" class="legacy" id="buffer_blob_slice_start_end_type"></a></h4>
<div class="api_metadata">
<span>Added in: v15.7.0, v14.18.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;number></a> The starting index.</li>
<li><code>end</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The ending index.</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 content-type for the new <code>Blob</code></li>
</ul>
<p>Creates and returns a new <code>Blob</code> containing a subset of this <code>Blob</code> objects
data. The original <code>Blob</code> is not altered.</p>
<h4><code>blob.stream()</code><span><a class="mark" href="#all_buffer_blobstream" id="all_buffer_blobstream">#</a></span><a aria-hidden="true" class="legacy" id="buffer_blob_stream"></a></h4>
<div class="api_metadata">
<span>Added in: v16.7.0</span>
</div>
<ul>
<li>Returns: <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a></li>
</ul>
<p>Returns a new <code>ReadableStream</code> that allows the content of the <code>Blob</code> to be read.</p>
<h4><code>blob.text()</code><span><a class="mark" href="#all_buffer_blobtext" id="all_buffer_blobtext">#</a></span><a aria-hidden="true" class="legacy" id="buffer_blob_text"></a></h4>
<div class="api_metadata">
<span>Added in: v15.7.0, v14.18.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>Returns a promise that fulfills with the contents of the <code>Blob</code> decoded as a
UTF-8 string.</p>
<h4><code>blob.type</code><span><a class="mark" href="#all_buffer_blobtype" id="all_buffer_blobtype">#</a></span><a aria-hidden="true" class="legacy" id="buffer_blob_type"></a></h4>
<div class="api_metadata">
<span>Added in: v15.7.0, v14.18.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The content-type of the <code>Blob</code>.</p>
<h4><code>Blob</code> objects and <code>MessageChannel</code><span><a class="mark" href="#all_buffer_blob-objects-and-messagechannel" id="all_buffer_blob-objects-and-messagechannel">#</a></span><a aria-hidden="true" class="legacy" id="buffer_blob_objects_and_messagechannel"></a></h4>
<p>Once a <a href="#all_buffer_class-blob" class="type">&#x3C;Blob></a> object is created, it can be sent via <code>MessagePort</code> to multiple
destinations without transferring or immediately copying the data. The data
contained by the <code>Blob</code> is copied only when the <code>arrayBuffer()</code> or <code>text()</code>
methods are called.</p>

<pre class="with-62-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Blob</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-built_in">setTimeout</span> <span class="hljs-keyword">as</span> delay } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:timers/promises'</span>;

<span class="hljs-keyword">const</span> blob = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Blob</span>([<span class="hljs-string">'hello there'</span>]);

<span class="hljs-keyword">const</span> mc1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
<span class="hljs-keyword">const</span> mc2 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();

mc1.<span class="hljs-property">port1</span>.<span class="hljs-property">onmessage</span> = <span class="hljs-keyword">async</span> ({ data }) => {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-keyword">await</span> data.<span class="hljs-title function_">arrayBuffer</span>());
  mc1.<span class="hljs-property">port1</span>.<span class="hljs-title function_">close</span>();
};

mc2.<span class="hljs-property">port1</span>.<span class="hljs-property">onmessage</span> = <span class="hljs-keyword">async</span> ({ data }) => {
  <span class="hljs-keyword">await</span> <span class="hljs-title function_">delay</span>(<span class="hljs-number">1000</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-keyword">await</span> data.<span class="hljs-title function_">arrayBuffer</span>());
  mc2.<span class="hljs-property">port1</span>.<span class="hljs-title function_">close</span>();
};

mc1.<span class="hljs-property">port2</span>.<span class="hljs-title function_">postMessage</span>(blob);
mc2.<span class="hljs-property">port2</span>.<span class="hljs-title function_">postMessage</span>(blob);

<span class="hljs-comment">// The Blob is still usable after posting.</span>
blob.<span class="hljs-title function_">text</span>().<span class="hljs-title function_">then</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Blob</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-attr">setTimeout</span>: delay } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:timers/promises'</span>);

<span class="hljs-keyword">const</span> blob = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Blob</span>([<span class="hljs-string">'hello there'</span>]);

<span class="hljs-keyword">const</span> mc1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
<span class="hljs-keyword">const</span> mc2 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();

mc1.<span class="hljs-property">port1</span>.<span class="hljs-property">onmessage</span> = <span class="hljs-keyword">async</span> ({ data }) => {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-keyword">await</span> data.<span class="hljs-title function_">arrayBuffer</span>());
  mc1.<span class="hljs-property">port1</span>.<span class="hljs-title function_">close</span>();
};

mc2.<span class="hljs-property">port1</span>.<span class="hljs-property">onmessage</span> = <span class="hljs-keyword">async</span> ({ data }) => {
  <span class="hljs-keyword">await</span> <span class="hljs-title function_">delay</span>(<span class="hljs-number">1000</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-keyword">await</span> data.<span class="hljs-title function_">arrayBuffer</span>());
  mc2.<span class="hljs-property">port1</span>.<span class="hljs-title function_">close</span>();
};

mc1.<span class="hljs-property">port2</span>.<span class="hljs-title function_">postMessage</span>(blob);
mc2.<span class="hljs-property">port2</span>.<span class="hljs-title function_">postMessage</span>(blob);

<span class="hljs-comment">// The Blob is still usable after posting.</span>
blob.<span class="hljs-title function_">text</span>().<span class="hljs-title function_">then</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>);</code><button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>Buffer</code><span><a class="mark" href="#all_buffer_class-buffer" id="all_buffer_class-buffer">#</a></span><a aria-hidden="true" class="legacy" id="buffer_class_buffer"></a></h3>
<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>
<h4>Static method: <code>Buffer.alloc(size[, fill[, encoding]])</code><span><a class="mark" href="#all_buffer_static-method-bufferallocsize-fill-encoding" id="all_buffer_static-method-bufferallocsize-fill-encoding">#</a></span><a aria-hidden="true" class="legacy" id="buffer_static_method_buffer_alloc_size_fill_encoding"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>Throw ERR_INVALID_ARG_TYPE or ERR_OUT_OF_RANGE instead of ERR_INVALID_ARG_VALUE for invalid input arguments.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p>Throw ERR_INVALID_ARG_VALUE instead of ERR_INVALID_OPT_VALUE for invalid input arguments.</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>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="#all_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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">5</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer 00 00 00 00 00></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">5</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer 00 00 00 00 00></span></code><button class="copy-button">copy</button></pre>
<p>If <code>size</code> is larger than
<a href="#all_buffer_bufferconstantsmax_length"><code>buffer.constants.MAX_LENGTH</code></a> or smaller than 0, <a href="#all_errors_err_out_of_range"><code>ERR_OUT_OF_RANGE</code></a>
is thrown.</p>
<p>If <code>fill</code> is specified, the allocated <code>Buffer</code> will be initialized by calling
<a href="#all_buffer_buffillvalue-offset-end-encoding"><code>buf.fill(fill)</code></a>.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">5</span>, <span class="hljs-string">'a'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer 61 61 61 61 61></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">5</span>, <span class="hljs-string">'a'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer 61 61 61 61 61></span></code><button class="copy-button">copy</button></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="#all_buffer_buffillvalue-offset-end-encoding"><code>buf.fill(fill, encoding)</code></a>.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">11</span>, <span class="hljs-string">'aGVsbG8gd29ybGQ='</span>, <span class="hljs-string">'base64'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">11</span>, <span class="hljs-string">'aGVsbG8gd29ybGQ='</span>, <span class="hljs-string">'base64'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64></span></code><button class="copy-button">copy</button></pre>
<p>Calling <a href="#all_buffer_static-method-bufferallocsize-fill-encoding"><code>Buffer.alloc()</code></a> can be measurably slower than the alternative
<a href="#all_buffer_static-method-bufferallocunsafesize"><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>
<h4>Static method: <code>Buffer.allocUnsafe(size)</code><span><a class="mark" href="#all_buffer_static-method-bufferallocunsafesize" id="all_buffer_static-method-bufferallocunsafesize">#</a></span><a aria-hidden="true" class="legacy" id="buffer_static_method_buffer_allocunsafe_size"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>Throw ERR_INVALID_ARG_TYPE or ERR_OUT_OF_RANGE instead of ERR_INVALID_ARG_VALUE for invalid input arguments.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p>Throw ERR_INVALID_ARG_VALUE instead of ERR_INVALID_OPT_VALUE for invalid input arguments.</p></td></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="#all_buffer_bufferconstantsmax_length"><code>buffer.constants.MAX_LENGTH</code></a> or smaller than 0, <a href="#all_errors_err_out_of_range"><code>ERR_OUT_OF_RANGE</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="#all_buffer_static-method-bufferallocsize-fill-encoding"><code>Buffer.alloc()</code></a> instead to initialize
<code>Buffer</code> instances with zeroes.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">10</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints (contents may vary): &#x3C;Buffer a0 8b 28 3f 01 00 00 00 50 32></span>

buf.<span class="hljs-title function_">fill</span>(<span class="hljs-number">0</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer 00 00 00 00 00 00 00 00 00 00></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">10</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints (contents may vary): &#x3C;Buffer a0 8b 28 3f 01 00 00 00 50 32></span>

buf.<span class="hljs-title function_">fill</span>(<span class="hljs-number">0</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer 00 00 00 00 00 00 00 00 00 00></span></code><button class="copy-button">copy</button></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="#all_buffer_class-property-bufferpoolsize"><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="#all_buffer_static-method-bufferallocunsafesize"><code>Buffer.allocUnsafe()</code></a>, <a href="#all_buffer_static-method-bufferfromarray"><code>Buffer.from(array)</code></a>,
<a href="#all_buffer_static-method-bufferfromstring-encoding"><code>Buffer.from(string)</code></a>, and <a href="#all_buffer_static-method-bufferconcatlist-totallength"><code>Buffer.concat()</code></a> only when <code>size</code> is less than
<code>Buffer.poolSize >>> 1</code> (floor of <a href="#all_buffer_class-property-bufferpoolsize"><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="#all_buffer_class-property-bufferpoolsize"><code>Buffer.poolSize</code></a>. The
difference is subtle but can be important when an application requires the
additional performance that <a href="#all_buffer_static-method-bufferallocunsafesize"><code>Buffer.allocUnsafe()</code></a> provides.</p>
<h4>Static method: <code>Buffer.allocUnsafeSlow(size)</code><span><a class="mark" href="#all_buffer_static-method-bufferallocunsafeslowsize" id="all_buffer_static-method-bufferallocunsafeslowsize">#</a></span><a aria-hidden="true" class="legacy" id="buffer_static_method_buffer_allocunsafeslow_size"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>Throw ERR_INVALID_ARG_TYPE or ERR_OUT_OF_RANGE instead of ERR_INVALID_ARG_VALUE for invalid input arguments.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p>Throw ERR_INVALID_ARG_VALUE instead of ERR_INVALID_OPT_VALUE for invalid input arguments.</p></td></tr>
<tr><td>v5.12.0</td>
<td><p><span>Added in: v5.12.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="#all_buffer_bufferconstantsmax_length"><code>buffer.constants.MAX_LENGTH</code></a> or smaller than 0, <a href="#all_errors_err_out_of_range"><code>ERR_OUT_OF_RANGE</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="#all_buffer_buffillvalue-offset-end-encoding"><code>buf.fill(0)</code></a> to initialize
such <code>Buffer</code> instances with zeroes.</p>
<p>When using <a href="#all_buffer_static-method-bufferallocunsafesize"><code>Buffer.allocUnsafe()</code></a> to allocate new <code>Buffer</code> instances,
allocations less than <code>Buffer.poolSize >>> 1</code> (4KiB when default poolSize is used) 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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-comment">// Need to keep around a few small chunks of memory.</span>
<span class="hljs-keyword">const</span> store = [];

socket.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-keyword">let</span> data;
  <span class="hljs-keyword">while</span> (<span class="hljs-literal">null</span> !== (data = readable.<span class="hljs-title function_">read</span>())) {
    <span class="hljs-comment">// Allocate for retained data.</span>
    <span class="hljs-keyword">const</span> sb = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafeSlow</span>(<span class="hljs-number">10</span>);

    <span class="hljs-comment">// Copy the data into the new allocation.</span>
    data.<span class="hljs-title function_">copy</span>(sb, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">10</span>);

    store.<span class="hljs-title function_">push</span>(sb);
  }
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-comment">// Need to keep around a few small chunks of memory.</span>
<span class="hljs-keyword">const</span> store = [];

socket.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-keyword">let</span> data;
  <span class="hljs-keyword">while</span> (<span class="hljs-literal">null</span> !== (data = readable.<span class="hljs-title function_">read</span>())) {
    <span class="hljs-comment">// Allocate for retained data.</span>
    <span class="hljs-keyword">const</span> sb = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafeSlow</span>(<span class="hljs-number">10</span>);

    <span class="hljs-comment">// Copy the data into the new allocation.</span>
    data.<span class="hljs-title function_">copy</span>(sb, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">10</span>);

    store.<span class="hljs-title function_">push</span>(sb);
  }
});</code><button class="copy-button">copy</button></pre>
<p>A <code>TypeError</code> will be thrown if <code>size</code> is not a number.</p>
<h4>Static method: <code>Buffer.byteLength(string[, encoding])</code><span><a class="mark" href="#all_buffer_static-method-bufferbytelengthstring-encoding" id="all_buffer_static-method-bufferbytelengthstring-encoding">#</a></span><a aria-hidden="true" class="legacy" id="buffer_static_method_buffer_bytelength_string_encoding"></a></h4>
<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="#all_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>, <code>'base64url'</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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> str = <span class="hljs-string">'\u00bd + \u00bc = \u00be'</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${str}</span>: <span class="hljs-subst">${str.length}</span> characters, `</span> +
            <span class="hljs-string">`<span class="hljs-subst">${Buffer.byteLength(str, <span class="hljs-string">'utf8'</span>)}</span> bytes`</span>);
<span class="hljs-comment">// Prints: ½ + ¼ = ¾: 9 characters, 12 bytes</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> str = <span class="hljs-string">'\u00bd + \u00bc = \u00be'</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${str}</span>: <span class="hljs-subst">${str.length}</span> characters, `</span> +
            <span class="hljs-string">`<span class="hljs-subst">${Buffer.byteLength(str, <span class="hljs-string">'utf8'</span>)}</span> bytes`</span>);
<span class="hljs-comment">// Prints: ½ + ¼ = ¾: 9 characters, 12 bytes</span></code><button class="copy-button">copy</button></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>
<h4>Static method: <code>Buffer.compare(buf1, buf2)</code><span><a class="mark" href="#all_buffer_static-method-buffercomparebuf1-buf2" id="all_buffer_static-method-buffercomparebuf1-buf2">#</a></span><a aria-hidden="true" class="legacy" id="buffer_static_method_buffer_compare_buf1_buf2"></a></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 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="#all_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="#all_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="#all_buffer_bufcomparetarget-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="#all_buffer_bufcomparetarget-targetstart-targetend-sourcestart-sourceend"><code>buf1.compare(buf2)</code></a>.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'1234'</span>);
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'0123'</span>);
<span class="hljs-keyword">const</span> arr = [buf1, buf2];

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(arr.<span class="hljs-title function_">sort</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-property">compare</span>));
<span class="hljs-comment">// Prints: [ &#x3C;Buffer 30 31 32 33>, &#x3C;Buffer 31 32 33 34> ]</span>
<span class="hljs-comment">// (This result is equal to: [buf2, buf1].)</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'1234'</span>);
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'0123'</span>);
<span class="hljs-keyword">const</span> arr = [buf1, buf2];

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(arr.<span class="hljs-title function_">sort</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-property">compare</span>));
<span class="hljs-comment">// Prints: [ &#x3C;Buffer 30 31 32 33>, &#x3C;Buffer 31 32 33 34> ]</span>
<span class="hljs-comment">// (This result is equal to: [buf2, buf1].)</span></code><button class="copy-button">copy</button></pre>
<h4>Static method: <code>Buffer.concat(list[, totalLength])</code><span><a class="mark" href="#all_buffer_static-method-bufferconcatlist-totallength" id="all_buffer_static-method-bufferconcatlist-totallength">#</a></span><a aria-hidden="true" class="legacy" id="buffer_static_method_buffer_concat_list_totallength"></a></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 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="#all_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="#all_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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-comment">// Create a single `Buffer` from a list of three `Buffer` instances.</span>

<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">10</span>);
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">14</span>);
<span class="hljs-keyword">const</span> buf3 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">18</span>);
<span class="hljs-keyword">const</span> totalLength = buf1.<span class="hljs-property">length</span> + buf2.<span class="hljs-property">length</span> + buf3.<span class="hljs-property">length</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(totalLength);
<span class="hljs-comment">// Prints: 42</span>

<span class="hljs-keyword">const</span> bufA = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">concat</span>([buf1, buf2, buf3], totalLength);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(bufA);
<span class="hljs-comment">// Prints: &#x3C;Buffer 00 00 00 00 ...></span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(bufA.<span class="hljs-property">length</span>);
<span class="hljs-comment">// Prints: 42</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-comment">// Create a single `Buffer` from a list of three `Buffer` instances.</span>

<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">10</span>);
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">14</span>);
<span class="hljs-keyword">const</span> buf3 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">18</span>);
<span class="hljs-keyword">const</span> totalLength = buf1.<span class="hljs-property">length</span> + buf2.<span class="hljs-property">length</span> + buf3.<span class="hljs-property">length</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(totalLength);
<span class="hljs-comment">// Prints: 42</span>

<span class="hljs-keyword">const</span> bufA = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">concat</span>([buf1, buf2, buf3], totalLength);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(bufA);
<span class="hljs-comment">// Prints: &#x3C;Buffer 00 00 00 00 ...></span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(bufA.<span class="hljs-property">length</span>);
<span class="hljs-comment">// Prints: 42</span></code><button class="copy-button">copy</button></pre>
<p><code>Buffer.concat()</code> may also use the internal <code>Buffer</code> pool like
<a href="#all_buffer_static-method-bufferallocunsafesize"><code>Buffer.allocUnsafe()</code></a> does.</p>
<h4>Static method: <code>Buffer.copyBytesFrom(view[, offset[, length]])</code><span><a class="mark" href="#all_buffer_static-method-buffercopybytesfromview-offset-length" id="all_buffer_static-method-buffercopybytesfromview-offset-length">#</a></span><a aria-hidden="true" class="legacy" id="buffer_static_method_buffer_copybytesfrom_view_offset_length"></a></h4>
<div class="api_metadata">
<span>Added in: v19.8.0</span>
</div>
<ul>
<li><code>view</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> to copy.</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> The starting offset within <code>view</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> The number of elements from <code>view</code> to copy.
<strong>Default:</strong> <code>view.length - offset</code>.</li>
</ul>
<p>Copies the underlying memory of <code>view</code> into a new <code>Buffer</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> u16 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint16Array</span>([<span class="hljs-number">0</span>, <span class="hljs-number">0xffff</span>]);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">copyBytesFrom</span>(u16, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>);
u16[<span class="hljs-number">1</span>] = <span class="hljs-number">0</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-property">length</span>); <span class="hljs-comment">// 2</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf[<span class="hljs-number">0</span>]); <span class="hljs-comment">// 255</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf[<span class="hljs-number">1</span>]); <span class="hljs-comment">// 255</span></code> <button class="copy-button">copy</button></pre>
<h4>Static method: <code>Buffer.from(array)</code><span><a class="mark" href="#all_buffer_static-method-bufferfromarray" id="all_buffer_static-method-bufferfromarray">#</a></span><a aria-hidden="true" class="legacy" id="buffer_static_method_buffer_from_array"></a></h4>
<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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-comment">// Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'.</span>
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x62</span>, <span class="hljs-number">0x75</span>, <span class="hljs-number">0x66</span>, <span class="hljs-number">0x66</span>, <span class="hljs-number">0x65</span>, <span class="hljs-number">0x72</span>]);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-comment">// Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'.</span>
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x62</span>, <span class="hljs-number">0x75</span>, <span class="hljs-number">0x66</span>, <span class="hljs-number">0x66</span>, <span class="hljs-number">0x65</span>, <span class="hljs-number">0x72</span>]);</code><button class="copy-button">copy</button></pre>
<p>If <code>array</code> is an <code>Array</code>-like object (that is, one with a <code>length</code> property of
type <code>number</code>), it is treated as if it is an array, unless it is a <code>Buffer</code> or
a <code>Uint8Array</code>. This means all other <code>TypedArray</code> variants get treated as an
<code>Array</code>. To create a <code>Buffer</code> from the bytes backing a <code>TypedArray</code>, use
<a href="#all_buffer_static-method-buffercopybytesfromview-offset-length"><code>Buffer.copyBytesFrom()</code></a>.</p>
<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="#all_buffer_static-method-bufferfromstring-encoding"><code>Buffer.from(string)</code></a> may also use the internal
<code>Buffer</code> pool like <a href="#all_buffer_static-method-bufferallocunsafesize"><code>Buffer.allocUnsafe()</code></a> does.</p>
<h4>Static method: <code>Buffer.from(arrayBuffer[, byteOffset[, length]])</code><span><a class="mark" href="#all_buffer_static-method-bufferfromarraybuffer-byteoffset-length" id="all_buffer_static-method-bufferfromarraybuffer-byteoffset-length">#</a></span><a aria-hidden="true" class="legacy" id="buffer_static_method_buffer_from_arraybuffer_byteoffset_length"></a></h4>
<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>'s underlying <code>ArrayBuffer</code>.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> arr = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint16Array</span>(<span class="hljs-number">2</span>);

arr[<span class="hljs-number">0</span>] = <span class="hljs-number">5000</span>;
arr[<span class="hljs-number">1</span>] = <span class="hljs-number">4000</span>;

<span class="hljs-comment">// Shares memory with `arr`.</span>
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(arr.<span class="hljs-property">buffer</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer 88 13 a0 0f></span>

<span class="hljs-comment">// Changing the original Uint16Array changes the Buffer also.</span>
arr[<span class="hljs-number">1</span>] = <span class="hljs-number">6000</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer 88 13 70 17></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> arr = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint16Array</span>(<span class="hljs-number">2</span>);

arr[<span class="hljs-number">0</span>] = <span class="hljs-number">5000</span>;
arr[<span class="hljs-number">1</span>] = <span class="hljs-number">4000</span>;

<span class="hljs-comment">// Shares memory with `arr`.</span>
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(arr.<span class="hljs-property">buffer</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer 88 13 a0 0f></span>

<span class="hljs-comment">// Changing the original Uint16Array changes the Buffer also.</span>
arr[<span class="hljs-number">1</span>] = <span class="hljs-number">6000</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer 88 13 70 17></span></code><button class="copy-button">copy</button></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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> ab = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>(<span class="hljs-number">10</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(ab, <span class="hljs-number">0</span>, <span class="hljs-number">2</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-property">length</span>);
<span class="hljs-comment">// Prints: 2</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> ab = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>(<span class="hljs-number">10</span>);
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(ab, <span class="hljs-number">0</span>, <span class="hljs-number">2</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-property">length</span>);
<span class="hljs-comment">// Prints: 2</span></code><button class="copy-button">copy</button></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>
<p>It is important to remember that a backing <code>ArrayBuffer</code> can cover a range
of memory that extends beyond the bounds of a <code>TypedArray</code> view. A new
<code>Buffer</code> created using the <code>buffer</code> property of a <code>TypedArray</code> may extend
beyond the range of the <code>TypedArray</code>:</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> arrA = <span class="hljs-title class_">Uint8Array</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x63</span>, <span class="hljs-number">0x64</span>, <span class="hljs-number">0x65</span>, <span class="hljs-number">0x66</span>]); <span class="hljs-comment">// 4 elements</span>
<span class="hljs-keyword">const</span> arrB = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(arrA.<span class="hljs-property">buffer</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>); <span class="hljs-comment">// 2 elements</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(arrA.<span class="hljs-property">buffer</span> === arrB.<span class="hljs-property">buffer</span>); <span class="hljs-comment">// true</span>

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(arrB.<span class="hljs-property">buffer</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer 63 64 65 66></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> arrA = <span class="hljs-title class_">Uint8Array</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x63</span>, <span class="hljs-number">0x64</span>, <span class="hljs-number">0x65</span>, <span class="hljs-number">0x66</span>]); <span class="hljs-comment">// 4 elements</span>
<span class="hljs-keyword">const</span> arrB = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(arrA.<span class="hljs-property">buffer</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>); <span class="hljs-comment">// 2 elements</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(arrA.<span class="hljs-property">buffer</span> === arrB.<span class="hljs-property">buffer</span>); <span class="hljs-comment">// true</span>

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(arrB.<span class="hljs-property">buffer</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer 63 64 65 66></span></code><button class="copy-button">copy</button></pre>
<h4>Static method: <code>Buffer.from(buffer)</code><span><a class="mark" href="#all_buffer_static-method-bufferfrombuffer" id="all_buffer_static-method-bufferfrombuffer">#</a></span><a aria-hidden="true" class="legacy" id="buffer_static_method_buffer_from_buffer"></a></h4>
<div class="api_metadata">
<span>Added in: v5.10.0</span>
</div>
<ul>
<li><code>buffer</code> <a href="#all_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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'buffer'</span>);
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(buf1);

buf1[<span class="hljs-number">0</span>] = <span class="hljs-number">0x61</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: auffer</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: buffer</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'buffer'</span>);
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(buf1);

buf1[<span class="hljs-number">0</span>] = <span class="hljs-number">0x61</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: auffer</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: buffer</span></code><button class="copy-button">copy</button></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>
<h4>Static method: <code>Buffer.from(object[, offsetOrEncoding[, length]])</code><span><a class="mark" href="#all_buffer_static-method-bufferfromobject-offsetorencoding-length" id="all_buffer_static-method-bufferfromobject-offsetorencoding-length">#</a></span><a aria-hidden="true" class="legacy" id="buffer_static_method_buffer_from_object_offsetorencoding_length"></a></h4>
<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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">String</span>(<span class="hljs-string">'this is a test'</span>));
<span class="hljs-comment">// Prints: &#x3C;Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">String</span>(<span class="hljs-string">'this is a test'</span>));
<span class="hljs-comment">// Prints: &#x3C;Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74></span></code><button class="copy-button">copy</button></pre>
<p>For objects that support <code>Symbol.toPrimitive</code>, returns
<code>Buffer.from(object[Symbol.toPrimitive]('string'), offsetOrEncoding)</code>.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">class</span> <span class="hljs-title class_">Foo</span> {
  [<span class="hljs-title class_">Symbol</span>.<span class="hljs-property">toPrimitive</span>]() {
    <span class="hljs-keyword">return</span> <span class="hljs-string">'this is a test'</span>;
  }
}

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Foo</span>(), <span class="hljs-string">'utf8'</span>);
<span class="hljs-comment">// Prints: &#x3C;Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">class</span> <span class="hljs-title class_">Foo</span> {
  [<span class="hljs-title class_">Symbol</span>.<span class="hljs-property">toPrimitive</span>]() {
    <span class="hljs-keyword">return</span> <span class="hljs-string">'this is a test'</span>;
  }
}

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Foo</span>(), <span class="hljs-string">'utf8'</span>);
<span class="hljs-comment">// Prints: &#x3C;Buffer 74 68 69 73 20 69 73 20 61 20 74 65 73 74></span></code><button class="copy-button">copy</button></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>
<h4>Static method: <code>Buffer.from(string[, encoding])</code><span><a class="mark" href="#all_buffer_static-method-bufferfromstring-encoding" id="all_buffer_static-method-bufferfromstring-encoding">#</a></span><a aria-hidden="true" class="legacy" id="buffer_static_method_buffer_from_string_encoding"></a></h4>
<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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'this is a tést'</span>);
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'7468697320697320612074c3a97374'</span>, <span class="hljs-string">'hex'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: this is a tést</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: this is a tést</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'latin1'</span>));
<span class="hljs-comment">// Prints: this is a tést</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'this is a tést'</span>);
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'7468697320697320612074c3a97374'</span>, <span class="hljs-string">'hex'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: this is a tést</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: this is a tést</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'latin1'</span>));
<span class="hljs-comment">// Prints: this is a tést</span></code><button class="copy-button">copy</button></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>
<p><a href="#all_buffer_static-method-bufferfromstring-encoding"><code>Buffer.from(string)</code></a> may also use the internal <code>Buffer</code> pool like
<a href="#all_buffer_static-method-bufferallocunsafesize"><code>Buffer.allocUnsafe()</code></a> does.</p>
<h4>Static method: <code>Buffer.isBuffer(obj)</code><span><a class="mark" href="#all_buffer_static-method-bufferisbufferobj" id="all_buffer_static-method-bufferisbufferobj">#</a></span><a aria-hidden="true" class="legacy" id="buffer_static_method_buffer_isbuffer_obj"></a></h4>
<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>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">isBuffer</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">10</span>)); <span class="hljs-comment">// true</span>
<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">isBuffer</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'foo'</span>)); <span class="hljs-comment">// true</span>
<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">isBuffer</span>(<span class="hljs-string">'a string'</span>); <span class="hljs-comment">// false</span>
<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">isBuffer</span>([]); <span class="hljs-comment">// false</span>
<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">isBuffer</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(<span class="hljs-number">1024</span>)); <span class="hljs-comment">// false</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">isBuffer</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">10</span>)); <span class="hljs-comment">// true</span>
<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">isBuffer</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'foo'</span>)); <span class="hljs-comment">// true</span>
<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">isBuffer</span>(<span class="hljs-string">'a string'</span>); <span class="hljs-comment">// false</span>
<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">isBuffer</span>([]); <span class="hljs-comment">// false</span>
<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">isBuffer</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(<span class="hljs-number">1024</span>)); <span class="hljs-comment">// false</span></code><button class="copy-button">copy</button></pre>
<h4>Static method: <code>Buffer.isEncoding(encoding)</code><span><a class="mark" href="#all_buffer_static-method-bufferisencodingencoding" id="all_buffer_static-method-bufferisencodingencoding">#</a></span><a aria-hidden="true" class="legacy" id="buffer_static_method_buffer_isencoding_encoding"></a></h4>
<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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">isEncoding</span>(<span class="hljs-string">'utf8'</span>));
<span class="hljs-comment">// Prints: true</span>

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">isEncoding</span>(<span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// Prints: true</span>

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">isEncoding</span>(<span class="hljs-string">'utf/8'</span>));
<span class="hljs-comment">// Prints: false</span>

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">isEncoding</span>(<span class="hljs-string">''</span>));
<span class="hljs-comment">// Prints: false</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">isEncoding</span>(<span class="hljs-string">'utf8'</span>));
<span class="hljs-comment">// Prints: true</span>

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">isEncoding</span>(<span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// Prints: true</span>

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">isEncoding</span>(<span class="hljs-string">'utf/8'</span>));
<span class="hljs-comment">// Prints: false</span>

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">isEncoding</span>(<span class="hljs-string">''</span>));
<span class="hljs-comment">// Prints: false</span></code><button class="copy-button">copy</button></pre>
<h4>Class property: <code>Buffer.poolSize</code><span><a class="mark" href="#all_buffer_class-property-bufferpoolsize" id="all_buffer_class-property-bufferpoolsize">#</a></span><a aria-hidden="true" class="legacy" id="buffer_class_property_buffer_poolsize"></a></h4>
<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>
<h4><code>buf[index]</code><span><a class="mark" href="#all_buffer_bufindex" id="all_buffer_bufindex">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_index"></a></h4>
<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 greater or equal to <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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-comment">// Copy an ASCII string into a `Buffer` one byte at a time.</span>
<span class="hljs-comment">// (This only works for ASCII-only strings. In general, one should use</span>
<span class="hljs-comment">// `Buffer.from()` to perform this conversion.)</span>

<span class="hljs-keyword">const</span> str = <span class="hljs-string">'Node.js'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(str.<span class="hljs-property">length</span>);

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; str.<span class="hljs-property">length</span>; i++) {
  buf[i] = str.<span class="hljs-title function_">charCodeAt</span>(i);
}

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'utf8'</span>));
<span class="hljs-comment">// Prints: Node.js</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-comment">// Copy an ASCII string into a `Buffer` one byte at a time.</span>
<span class="hljs-comment">// (This only works for ASCII-only strings. In general, one should use</span>
<span class="hljs-comment">// `Buffer.from()` to perform this conversion.)</span>

<span class="hljs-keyword">const</span> str = <span class="hljs-string">'Node.js'</span>;
<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(str.<span class="hljs-property">length</span>);

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; str.<span class="hljs-property">length</span>; i++) {
  buf[i] = str.<span class="hljs-title function_">charCodeAt</span>(i);
}

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'utf8'</span>));
<span class="hljs-comment">// Prints: Node.js</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.buffer</code><span><a class="mark" href="#all_buffer_bufbuffer" id="all_buffer_bufbuffer">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_buffer"></a></h4>
<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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> arrayBuffer = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>(<span class="hljs-number">16</span>);
<span class="hljs-keyword">const</span> buffer = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(arrayBuffer);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buffer.<span class="hljs-property">buffer</span> === arrayBuffer);
<span class="hljs-comment">// Prints: true</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> arrayBuffer = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>(<span class="hljs-number">16</span>);
<span class="hljs-keyword">const</span> buffer = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(arrayBuffer);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buffer.<span class="hljs-property">buffer</span> === arrayBuffer);
<span class="hljs-comment">// Prints: true</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.byteOffset</code><span><a class="mark" href="#all_buffer_bufbyteoffset" id="all_buffer_bufbyteoffset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_byteoffset"></a></h4>
<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> of the <code>Buffer</code>s underlying <code>ArrayBuffer</code> object.</li>
</ul>
<p>When setting <code>byteOffset</code> in <code>Buffer.from(ArrayBuffer, byteOffset, length)</code>,
or sometimes when allocating a <code>Buffer</code> smaller than <code>Buffer.poolSize</code>, the
buffer does not 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>Buffer</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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-comment">// Create a buffer smaller than `Buffer.poolSize`.</span>
<span class="hljs-keyword">const</span> nodeBuffer = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>]);

<span class="hljs-comment">// When casting the Node.js Buffer to an Int8Array, use the byteOffset</span>
<span class="hljs-comment">// to refer only to the part of `nodeBuffer.buffer` that contains the memory</span>
<span class="hljs-comment">// for `nodeBuffer`.</span>
<span class="hljs-keyword">new</span> <span class="hljs-title class_">Int8Array</span>(nodeBuffer.<span class="hljs-property">buffer</span>, nodeBuffer.<span class="hljs-property">byteOffset</span>, nodeBuffer.<span class="hljs-property">length</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-comment">// Create a buffer smaller than `Buffer.poolSize`.</span>
<span class="hljs-keyword">const</span> nodeBuffer = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>]);

<span class="hljs-comment">// When casting the Node.js Buffer to an Int8Array, use the byteOffset</span>
<span class="hljs-comment">// to refer only to the part of `nodeBuffer.buffer` that contains the memory</span>
<span class="hljs-comment">// for `nodeBuffer`.</span>
<span class="hljs-keyword">new</span> <span class="hljs-title class_">Int8Array</span>(nodeBuffer.<span class="hljs-property">buffer</span>, nodeBuffer.<span class="hljs-property">byteOffset</span>, nodeBuffer.<span class="hljs-property">length</span>);</code><button class="copy-button">copy</button></pre>
<h4><code>buf.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]])</code><span><a class="mark" href="#all_buffer_bufcomparetarget-targetstart-targetend-sourcestart-sourceend" id="all_buffer_bufcomparetarget-targetstart-targetend-sourcestart-sourceend">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_compare_target_targetstart_targetend_sourcestart_sourceend"></a></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>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="#all_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="#all_buffer_buflength"><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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'ABC'</span>);
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'BCD'</span>);
<span class="hljs-keyword">const</span> buf3 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'ABCD'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">compare</span>(buf1));
<span class="hljs-comment">// Prints: 0</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">compare</span>(buf2));
<span class="hljs-comment">// Prints: -1</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">compare</span>(buf3));
<span class="hljs-comment">// Prints: -1</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2.<span class="hljs-title function_">compare</span>(buf1));
<span class="hljs-comment">// Prints: 1</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2.<span class="hljs-title function_">compare</span>(buf3));
<span class="hljs-comment">// Prints: 1</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>([buf1, buf2, buf3].<span class="hljs-title function_">sort</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-property">compare</span>));
<span class="hljs-comment">// Prints: [ &#x3C;Buffer 41 42 43>, &#x3C;Buffer 41 42 43 44>, &#x3C;Buffer 42 43 44> ]</span>
<span class="hljs-comment">// (This result is equal to: [buf1, buf3, buf2].)</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'ABC'</span>);
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'BCD'</span>);
<span class="hljs-keyword">const</span> buf3 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'ABCD'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">compare</span>(buf1));
<span class="hljs-comment">// Prints: 0</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">compare</span>(buf2));
<span class="hljs-comment">// Prints: -1</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">compare</span>(buf3));
<span class="hljs-comment">// Prints: -1</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2.<span class="hljs-title function_">compare</span>(buf1));
<span class="hljs-comment">// Prints: 1</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2.<span class="hljs-title function_">compare</span>(buf3));
<span class="hljs-comment">// Prints: 1</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>([buf1, buf2, buf3].<span class="hljs-title function_">sort</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-property">compare</span>));
<span class="hljs-comment">// Prints: [ &#x3C;Buffer 41 42 43>, &#x3C;Buffer 41 42 43 44>, &#x3C;Buffer 42 43 44> ]</span>
<span class="hljs-comment">// (This result is equal to: [buf1, buf3, buf2].)</span></code><button class="copy-button">copy</button></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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>]);
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">compare</span>(buf2, <span class="hljs-number">5</span>, <span class="hljs-number">9</span>, <span class="hljs-number">0</span>, <span class="hljs-number">4</span>));
<span class="hljs-comment">// Prints: 0</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">compare</span>(buf2, <span class="hljs-number">0</span>, <span class="hljs-number">6</span>, <span class="hljs-number">4</span>));
<span class="hljs-comment">// Prints: -1</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">compare</span>(buf2, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">5</span>));
<span class="hljs-comment">// Prints: 1</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>]);
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">compare</span>(buf2, <span class="hljs-number">5</span>, <span class="hljs-number">9</span>, <span class="hljs-number">0</span>, <span class="hljs-number">4</span>));
<span class="hljs-comment">// Prints: 0</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">compare</span>(buf2, <span class="hljs-number">0</span>, <span class="hljs-number">6</span>, <span class="hljs-number">4</span>));
<span class="hljs-comment">// Prints: -1</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">compare</span>(buf2, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">5</span>));
<span class="hljs-comment">// Prints: 1</span></code><button class="copy-button">copy</button></pre>
<p><a href="#all_errors_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>
<h4><code>buf.copy(target[, targetStart[, sourceStart[, sourceEnd]]])</code><span><a class="mark" href="#all_buffer_bufcopytarget-targetstart-sourcestart-sourceend" id="all_buffer_bufcopytarget-targetstart-sourcestart-sourceend">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_copy_target_targetstart_sourcestart_sourceend"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><code>target</code> <a href="#all_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="#all_buffer_buflength"><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.prototype.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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-comment">// Create two `Buffer` instances.</span>
<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">26</span>);
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">26</span>).<span class="hljs-title function_">fill</span>(<span class="hljs-string">'!'</span>);

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; <span class="hljs-number">26</span>; i++) {
  <span class="hljs-comment">// 97 is the decimal ASCII value for 'a'.</span>
  buf1[i] = i + <span class="hljs-number">97</span>;
}

<span class="hljs-comment">// Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`.</span>
buf1.<span class="hljs-title function_">copy</span>(buf2, <span class="hljs-number">8</span>, <span class="hljs-number">16</span>, <span class="hljs-number">20</span>);
<span class="hljs-comment">// This is equivalent to:</span>
<span class="hljs-comment">// buf2.set(buf1.subarray(16, 20), 8);</span>

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'ascii'</span>, <span class="hljs-number">0</span>, <span class="hljs-number">25</span>));
<span class="hljs-comment">// Prints: !!!!!!!!qrst!!!!!!!!!!!!!</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-comment">// Create two `Buffer` instances.</span>
<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">26</span>);
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">26</span>).<span class="hljs-title function_">fill</span>(<span class="hljs-string">'!'</span>);

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; <span class="hljs-number">26</span>; i++) {
  <span class="hljs-comment">// 97 is the decimal ASCII value for 'a'.</span>
  buf1[i] = i + <span class="hljs-number">97</span>;
}

<span class="hljs-comment">// Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`.</span>
buf1.<span class="hljs-title function_">copy</span>(buf2, <span class="hljs-number">8</span>, <span class="hljs-number">16</span>, <span class="hljs-number">20</span>);
<span class="hljs-comment">// This is equivalent to:</span>
<span class="hljs-comment">// buf2.set(buf1.subarray(16, 20), 8);</span>

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'ascii'</span>, <span class="hljs-number">0</span>, <span class="hljs-number">25</span>));
<span class="hljs-comment">// Prints: !!!!!!!!qrst!!!!!!!!!!!!!</span></code><button class="copy-button">copy</button></pre>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-comment">// Create a `Buffer` and copy data from one region to an overlapping region</span>
<span class="hljs-comment">// within the same `Buffer`.</span>

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">26</span>);

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; <span class="hljs-number">26</span>; i++) {
  <span class="hljs-comment">// 97 is the decimal ASCII value for 'a'.</span>
  buf[i] = i + <span class="hljs-number">97</span>;
}

buf.<span class="hljs-title function_">copy</span>(buf, <span class="hljs-number">0</span>, <span class="hljs-number">4</span>, <span class="hljs-number">10</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: efghijghijklmnopqrstuvwxyz</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-comment">// Create a `Buffer` and copy data from one region to an overlapping region</span>
<span class="hljs-comment">// within the same `Buffer`.</span>

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">26</span>);

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; <span class="hljs-number">26</span>; i++) {
  <span class="hljs-comment">// 97 is the decimal ASCII value for 'a'.</span>
  buf[i] = i + <span class="hljs-number">97</span>;
}

buf.<span class="hljs-title function_">copy</span>(buf, <span class="hljs-number">0</span>, <span class="hljs-number">4</span>, <span class="hljs-number">10</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: efghijghijklmnopqrstuvwxyz</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.entries()</code><span><a class="mark" href="#all_buffer_bufentries" id="all_buffer_bufentries">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_entries"></a></h4>
<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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-comment">// Log the entire contents of a `Buffer`.</span>

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'buffer'</span>);

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> pair <span class="hljs-keyword">of</span> buf.<span class="hljs-title function_">entries</span>()) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(pair);
}
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   [0, 98]</span>
<span class="hljs-comment">//   [1, 117]</span>
<span class="hljs-comment">//   [2, 102]</span>
<span class="hljs-comment">//   [3, 102]</span>
<span class="hljs-comment">//   [4, 101]</span>
<span class="hljs-comment">//   [5, 114]</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-comment">// Log the entire contents of a `Buffer`.</span>

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'buffer'</span>);

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> pair <span class="hljs-keyword">of</span> buf.<span class="hljs-title function_">entries</span>()) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(pair);
}
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   [0, 98]</span>
<span class="hljs-comment">//   [1, 117]</span>
<span class="hljs-comment">//   [2, 102]</span>
<span class="hljs-comment">//   [3, 102]</span>
<span class="hljs-comment">//   [4, 101]</span>
<span class="hljs-comment">//   [5, 114]</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.equals(otherBuffer)</code><span><a class="mark" href="#all_buffer_bufequalsotherbuffer" id="all_buffer_bufequalsotherbuffer">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_equals_otherbuffer"></a></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 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="#all_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="#all_buffer_bufcomparetarget-targetstart-targetend-sourcestart-sourceend"><code>buf.compare(otherBuffer) === 0</code></a>.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'ABC'</span>);
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'414243'</span>, <span class="hljs-string">'hex'</span>);
<span class="hljs-keyword">const</span> buf3 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'ABCD'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">equals</span>(buf2));
<span class="hljs-comment">// Prints: true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">equals</span>(buf3));
<span class="hljs-comment">// Prints: false</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'ABC'</span>);
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'414243'</span>, <span class="hljs-string">'hex'</span>);
<span class="hljs-keyword">const</span> buf3 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'ABCD'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">equals</span>(buf2));
<span class="hljs-comment">// Prints: true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">equals</span>(buf3));
<span class="hljs-comment">// Prints: false</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.fill(value[, offset[, end]][, encoding])</code><span><a class="mark" href="#all_buffer_buffillvalue-offset-end-encoding" id="all_buffer_buffillvalue-offset-end-encoding">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_fill_value_offset_end_encoding"></a></h4>
<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="#all_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>.
Empty value (string, Uint8Array, Buffer) is coerced to <code>0</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="#all_buffer_buflength"><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="#all_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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-comment">// Fill a `Buffer` with the ASCII character 'h'.</span>

<span class="hljs-keyword">const</span> b = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">50</span>).<span class="hljs-title function_">fill</span>(<span class="hljs-string">'h'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh</span>

<span class="hljs-comment">// Fill a buffer with empty string</span>
<span class="hljs-keyword">const</span> c = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">5</span>).<span class="hljs-title function_">fill</span>(<span class="hljs-string">''</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(c.<span class="hljs-title function_">fill</span>(<span class="hljs-string">''</span>));
<span class="hljs-comment">// Prints: &#x3C;Buffer 00 00 00 00 00></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-comment">// Fill a `Buffer` with the ASCII character 'h'.</span>

<span class="hljs-keyword">const</span> b = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">50</span>).<span class="hljs-title function_">fill</span>(<span class="hljs-string">'h'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh</span>

<span class="hljs-comment">// Fill a buffer with empty string</span>
<span class="hljs-keyword">const</span> c = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">5</span>).<span class="hljs-title function_">fill</span>(<span class="hljs-string">''</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(c.<span class="hljs-title function_">fill</span>(<span class="hljs-string">''</span>));
<span class="hljs-comment">// Prints: &#x3C;Buffer 00 00 00 00 00></span></code><button class="copy-button">copy</button></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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-comment">// Fill a `Buffer` with character that takes up two bytes in UTF-8.</span>

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">5</span>).<span class="hljs-title function_">fill</span>(<span class="hljs-string">'\u0222'</span>));
<span class="hljs-comment">// Prints: &#x3C;Buffer c8 a2 c8 a2 c8></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-comment">// Fill a `Buffer` with character that takes up two bytes in UTF-8.</span>

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">5</span>).<span class="hljs-title function_">fill</span>(<span class="hljs-string">'\u0222'</span>));
<span class="hljs-comment">// Prints: &#x3C;Buffer c8 a2 c8 a2 c8></span></code><button class="copy-button">copy</button></pre>
<p>If <code>value</code> contains invalid characters, it is truncated; if no valid
fill data remains, an exception is thrown:</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">5</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">fill</span>(<span class="hljs-string">'a'</span>));
<span class="hljs-comment">// Prints: &#x3C;Buffer 61 61 61 61 61></span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">fill</span>(<span class="hljs-string">'aazz'</span>, <span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// Prints: &#x3C;Buffer aa aa aa aa aa></span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">fill</span>(<span class="hljs-string">'zz'</span>, <span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// Throws an exception.</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">5</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">fill</span>(<span class="hljs-string">'a'</span>));
<span class="hljs-comment">// Prints: &#x3C;Buffer 61 61 61 61 61></span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">fill</span>(<span class="hljs-string">'aazz'</span>, <span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// Prints: &#x3C;Buffer aa aa aa aa aa></span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">fill</span>(<span class="hljs-string">'zz'</span>, <span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// Throws an exception.</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.includes(value[, byteOffset][, encoding])</code><span><a class="mark" href="#all_buffer_bufincludesvalue-byteoffset-encoding" id="all_buffer_bufincludesvalue-byteoffset-encoding">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_includes_value_byteoffset_encoding"></a></h4>
<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="#all_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="#all_buffer_bufindexofvalue-byteoffset-encoding"><code>buf.indexOf() !== -1</code></a>.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'this is a buffer'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">includes</span>(<span class="hljs-string">'this'</span>));
<span class="hljs-comment">// Prints: true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">includes</span>(<span class="hljs-string">'is'</span>));
<span class="hljs-comment">// Prints: true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">includes</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'a buffer'</span>)));
<span class="hljs-comment">// Prints: true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">includes</span>(<span class="hljs-number">97</span>));
<span class="hljs-comment">// Prints: true (97 is the decimal ASCII value for 'a')</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">includes</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'a buffer example'</span>)));
<span class="hljs-comment">// Prints: false</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">includes</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'a buffer example'</span>).<span class="hljs-title function_">slice</span>(<span class="hljs-number">0</span>, <span class="hljs-number">8</span>)));
<span class="hljs-comment">// Prints: true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">includes</span>(<span class="hljs-string">'this'</span>, <span class="hljs-number">4</span>));
<span class="hljs-comment">// Prints: false</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'this is a buffer'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">includes</span>(<span class="hljs-string">'this'</span>));
<span class="hljs-comment">// Prints: true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">includes</span>(<span class="hljs-string">'is'</span>));
<span class="hljs-comment">// Prints: true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">includes</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'a buffer'</span>)));
<span class="hljs-comment">// Prints: true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">includes</span>(<span class="hljs-number">97</span>));
<span class="hljs-comment">// Prints: true (97 is the decimal ASCII value for 'a')</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">includes</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'a buffer example'</span>)));
<span class="hljs-comment">// Prints: false</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">includes</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'a buffer example'</span>).<span class="hljs-title function_">slice</span>(<span class="hljs-number">0</span>, <span class="hljs-number">8</span>)));
<span class="hljs-comment">// Prints: true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">includes</span>(<span class="hljs-string">'this'</span>, <span class="hljs-number">4</span>));
<span class="hljs-comment">// Prints: false</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.indexOf(value[, byteOffset][, encoding])</code><span><a class="mark" href="#all_buffer_bufindexofvalue-byteoffset-encoding" id="all_buffer_bufindexofvalue-byteoffset-encoding">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_indexof_value_byteoffset_encoding"></a></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>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="#all_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="#all_buffer_bufsubarraystart-end"><code>buf.subarray</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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'this is a buffer'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">'this'</span>));
<span class="hljs-comment">// Prints: 0</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">'is'</span>));
<span class="hljs-comment">// Prints: 2</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">indexOf</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'a buffer'</span>)));
<span class="hljs-comment">// Prints: 8</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">indexOf</span>(<span class="hljs-number">97</span>));
<span class="hljs-comment">// Prints: 8 (97 is the decimal ASCII value for 'a')</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">indexOf</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'a buffer example'</span>)));
<span class="hljs-comment">// Prints: -1</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">indexOf</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'a buffer example'</span>).<span class="hljs-title function_">slice</span>(<span class="hljs-number">0</span>, <span class="hljs-number">8</span>)));
<span class="hljs-comment">// Prints: 8</span>

<span class="hljs-keyword">const</span> utf16Buffer = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'\u039a\u0391\u03a3\u03a3\u0395'</span>, <span class="hljs-string">'utf16le'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(utf16Buffer.<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">'\u03a3'</span>, <span class="hljs-number">0</span>, <span class="hljs-string">'utf16le'</span>));
<span class="hljs-comment">// Prints: 4</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(utf16Buffer.<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">'\u03a3'</span>, -<span class="hljs-number">4</span>, <span class="hljs-string">'utf16le'</span>));
<span class="hljs-comment">// Prints: 6</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'this is a buffer'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">'this'</span>));
<span class="hljs-comment">// Prints: 0</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">'is'</span>));
<span class="hljs-comment">// Prints: 2</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">indexOf</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'a buffer'</span>)));
<span class="hljs-comment">// Prints: 8</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">indexOf</span>(<span class="hljs-number">97</span>));
<span class="hljs-comment">// Prints: 8 (97 is the decimal ASCII value for 'a')</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">indexOf</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'a buffer example'</span>)));
<span class="hljs-comment">// Prints: -1</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">indexOf</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'a buffer example'</span>).<span class="hljs-title function_">slice</span>(<span class="hljs-number">0</span>, <span class="hljs-number">8</span>)));
<span class="hljs-comment">// Prints: 8</span>

<span class="hljs-keyword">const</span> utf16Buffer = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'\u039a\u0391\u03a3\u03a3\u0395'</span>, <span class="hljs-string">'utf16le'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(utf16Buffer.<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">'\u03a3'</span>, <span class="hljs-number">0</span>, <span class="hljs-string">'utf16le'</span>));
<span class="hljs-comment">// Prints: 4</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(utf16Buffer.<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">'\u03a3'</span>, -<span class="hljs-number">4</span>, <span class="hljs-string">'utf16le'</span>));
<span class="hljs-comment">// Prints: 6</span></code><button class="copy-button">copy</button></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.prototype.indexOf()</code></a>.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> b = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'abcdef'</span>);

<span class="hljs-comment">// Passing a value that's a number, but not a valid byte.</span>
<span class="hljs-comment">// Prints: 2, equivalent to searching for 99 or 'c'.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">indexOf</span>(<span class="hljs-number">99.9</span>));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">indexOf</span>(<span class="hljs-number">256</span> + <span class="hljs-number">99</span>));

<span class="hljs-comment">// Passing a byteOffset that coerces to NaN or 0.</span>
<span class="hljs-comment">// Prints: 1, searching the whole buffer.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">'b'</span>, <span class="hljs-literal">undefined</span>));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">'b'</span>, {}));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">'b'</span>, <span class="hljs-literal">null</span>));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">'b'</span>, []));</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> b = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'abcdef'</span>);

<span class="hljs-comment">// Passing a value that's a number, but not a valid byte.</span>
<span class="hljs-comment">// Prints: 2, equivalent to searching for 99 or 'c'.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">indexOf</span>(<span class="hljs-number">99.9</span>));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">indexOf</span>(<span class="hljs-number">256</span> + <span class="hljs-number">99</span>));

<span class="hljs-comment">// Passing a byteOffset that coerces to NaN or 0.</span>
<span class="hljs-comment">// Prints: 1, searching the whole buffer.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">'b'</span>, <span class="hljs-literal">undefined</span>));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">'b'</span>, {}));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">'b'</span>, <span class="hljs-literal">null</span>));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">'b'</span>, []));</code><button class="copy-button">copy</button></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>
<h4><code>buf.keys()</code><span><a class="mark" href="#all_buffer_bufkeys" id="all_buffer_bufkeys">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_keys"></a></h4>
<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 (indexes).</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'buffer'</span>);

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> key <span class="hljs-keyword">of</span> buf.<span class="hljs-title function_">keys</span>()) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(key);
}
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   0</span>
<span class="hljs-comment">//   1</span>
<span class="hljs-comment">//   2</span>
<span class="hljs-comment">//   3</span>
<span class="hljs-comment">//   4</span>
<span class="hljs-comment">//   5</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'buffer'</span>);

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> key <span class="hljs-keyword">of</span> buf.<span class="hljs-title function_">keys</span>()) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(key);
}
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   0</span>
<span class="hljs-comment">//   1</span>
<span class="hljs-comment">//   2</span>
<span class="hljs-comment">//   3</span>
<span class="hljs-comment">//   4</span>
<span class="hljs-comment">//   5</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.lastIndexOf(value[, byteOffset][, encoding])</code><span><a class="mark" href="#all_buffer_buflastindexofvalue-byteoffset-encoding" id="all_buffer_buflastindexofvalue-byteoffset-encoding">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_lastindexof_value_byteoffset_encoding"></a></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>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="#all_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="#all_buffer_bufindexofvalue-byteoffset-encoding"><code>buf.indexOf()</code></a>, except the last occurrence of <code>value</code> is found
rather than the first occurrence.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'this buffer is a buffer'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-string">'this'</span>));
<span class="hljs-comment">// Prints: 0</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-string">'buffer'</span>));
<span class="hljs-comment">// Prints: 17</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'buffer'</span>)));
<span class="hljs-comment">// Prints: 17</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-number">97</span>));
<span class="hljs-comment">// Prints: 15 (97 is the decimal ASCII value for 'a')</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'yolo'</span>)));
<span class="hljs-comment">// Prints: -1</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-string">'buffer'</span>, <span class="hljs-number">5</span>));
<span class="hljs-comment">// Prints: 5</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-string">'buffer'</span>, <span class="hljs-number">4</span>));
<span class="hljs-comment">// Prints: -1</span>

<span class="hljs-keyword">const</span> utf16Buffer = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'\u039a\u0391\u03a3\u03a3\u0395'</span>, <span class="hljs-string">'utf16le'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(utf16Buffer.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-string">'\u03a3'</span>, <span class="hljs-literal">undefined</span>, <span class="hljs-string">'utf16le'</span>));
<span class="hljs-comment">// Prints: 6</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(utf16Buffer.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-string">'\u03a3'</span>, -<span class="hljs-number">5</span>, <span class="hljs-string">'utf16le'</span>));
<span class="hljs-comment">// Prints: 4</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'this buffer is a buffer'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-string">'this'</span>));
<span class="hljs-comment">// Prints: 0</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-string">'buffer'</span>));
<span class="hljs-comment">// Prints: 17</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'buffer'</span>)));
<span class="hljs-comment">// Prints: 17</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-number">97</span>));
<span class="hljs-comment">// Prints: 15 (97 is the decimal ASCII value for 'a')</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'yolo'</span>)));
<span class="hljs-comment">// Prints: -1</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-string">'buffer'</span>, <span class="hljs-number">5</span>));
<span class="hljs-comment">// Prints: 5</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-string">'buffer'</span>, <span class="hljs-number">4</span>));
<span class="hljs-comment">// Prints: -1</span>

<span class="hljs-keyword">const</span> utf16Buffer = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'\u039a\u0391\u03a3\u03a3\u0395'</span>, <span class="hljs-string">'utf16le'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(utf16Buffer.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-string">'\u03a3'</span>, <span class="hljs-literal">undefined</span>, <span class="hljs-string">'utf16le'</span>));
<span class="hljs-comment">// Prints: 6</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(utf16Buffer.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-string">'\u03a3'</span>, -<span class="hljs-number">5</span>, <span class="hljs-string">'utf16le'</span>));
<span class="hljs-comment">// Prints: 4</span></code><button class="copy-button">copy</button></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.prototype.lastIndexOf()</code></a>.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> b = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'abcdef'</span>);

<span class="hljs-comment">// Passing a value that's a number, but not a valid byte.</span>
<span class="hljs-comment">// Prints: 2, equivalent to searching for 99 or 'c'.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-number">99.9</span>));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-number">256</span> + <span class="hljs-number">99</span>));

<span class="hljs-comment">// Passing a byteOffset that coerces to NaN.</span>
<span class="hljs-comment">// Prints: 1, searching the whole buffer.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-string">'b'</span>, <span class="hljs-literal">undefined</span>));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-string">'b'</span>, {}));

<span class="hljs-comment">// Passing a byteOffset that coerces to 0.</span>
<span class="hljs-comment">// Prints: -1, equivalent to passing 0.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-string">'b'</span>, <span class="hljs-literal">null</span>));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-string">'b'</span>, []));</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> b = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'abcdef'</span>);

<span class="hljs-comment">// Passing a value that's a number, but not a valid byte.</span>
<span class="hljs-comment">// Prints: 2, equivalent to searching for 99 or 'c'.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-number">99.9</span>));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-number">256</span> + <span class="hljs-number">99</span>));

<span class="hljs-comment">// Passing a byteOffset that coerces to NaN.</span>
<span class="hljs-comment">// Prints: 1, searching the whole buffer.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-string">'b'</span>, <span class="hljs-literal">undefined</span>));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-string">'b'</span>, {}));

<span class="hljs-comment">// Passing a byteOffset that coerces to 0.</span>
<span class="hljs-comment">// Prints: -1, equivalent to passing 0.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-string">'b'</span>, <span class="hljs-literal">null</span>));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(b.<span class="hljs-title function_">lastIndexOf</span>(<span class="hljs-string">'b'</span>, []));</code><button class="copy-button">copy</button></pre>
<p>If <code>value</code> is an empty string or empty <code>Buffer</code>, <code>byteOffset</code> will be returned.</p>
<h4><code>buf.length</code><span><a class="mark" href="#all_buffer_buflength" id="all_buffer_buflength">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_length"></a></h4>
<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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-comment">// Create a `Buffer` and write a shorter string to it using UTF-8.</span>

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">1234</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-property">length</span>);
<span class="hljs-comment">// Prints: 1234</span>

buf.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some string'</span>, <span class="hljs-number">0</span>, <span class="hljs-string">'utf8'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-property">length</span>);
<span class="hljs-comment">// Prints: 1234</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-comment">// Create a `Buffer` and write a shorter string to it using UTF-8.</span>

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">1234</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-property">length</span>);
<span class="hljs-comment">// Prints: 1234</span>

buf.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some string'</span>, <span class="hljs-number">0</span>, <span class="hljs-string">'utf8'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-property">length</span>);
<span class="hljs-comment">// Prints: 1234</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.parent</code><span><a class="mark" href="#all_buffer_bufparent" id="all_buffer_bufparent">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_parent"></a></h4>
<div class="api_metadata">
<span>Deprecated since: v8.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_buffer_bufbuffer"><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>
<h4><code>buf.readBigInt64BE([offset])</code><span><a class="mark" href="#all_buffer_bufreadbigint64beoffset" id="all_buffer_bufreadbigint64beoffset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readbigint64be_offset"></a></h4>
<div class="api_metadata">
<span>Added in: v12.0.0, v10.20.0</span>
</div>
<ul>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#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, big-endian 64-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>
<h4><code>buf.readBigInt64LE([offset])</code><span><a class="mark" href="#all_buffer_bufreadbigint64leoffset" id="all_buffer_bufreadbigint64leoffset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readbigint64le_offset"></a></h4>
<div class="api_metadata">
<span>Added in: v12.0.0, v10.20.0</span>
</div>
<ul>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#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, little-endian 64-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>
<h4><code>buf.readBigUInt64BE([offset])</code><span><a class="mark" href="#all_buffer_bufreadbiguint64beoffset" id="all_buffer_bufreadbiguint64beoffset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readbiguint64be_offset"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.10.0, v12.19.0</td>
<td><p>This function is also available as <code>buf.readBigUint64BE()</code>.</p></td></tr>
<tr><td>v12.0.0, v10.20.0</td>
<td><p><span>Added in: v12.0.0, v10.20.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 - 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, big-endian 64-bit integer from <code>buf</code> at the specified
<code>offset</code>.</p>
<p>This function is also available under the <code>readBigUint64BE</code> alias.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x00</span>, <span class="hljs-number">0x00</span>, <span class="hljs-number">0x00</span>, <span class="hljs-number">0x00</span>, <span class="hljs-number">0xff</span>, <span class="hljs-number">0xff</span>, <span class="hljs-number">0xff</span>, <span class="hljs-number">0xff</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readBigUInt64BE</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 4294967295n</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x00</span>, <span class="hljs-number">0x00</span>, <span class="hljs-number">0x00</span>, <span class="hljs-number">0x00</span>, <span class="hljs-number">0xff</span>, <span class="hljs-number">0xff</span>, <span class="hljs-number">0xff</span>, <span class="hljs-number">0xff</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readBigUInt64BE</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 4294967295n</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.readBigUInt64LE([offset])</code><span><a class="mark" href="#all_buffer_bufreadbiguint64leoffset" id="all_buffer_bufreadbiguint64leoffset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readbiguint64le_offset"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.10.0, v12.19.0</td>
<td><p>This function is also available as <code>buf.readBigUint64LE()</code>.</p></td></tr>
<tr><td>v12.0.0, v10.20.0</td>
<td><p><span>Added in: v12.0.0, v10.20.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 - 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, little-endian 64-bit integer from <code>buf</code> at the specified
<code>offset</code>.</p>
<p>This function is also available under the <code>readBigUint64LE</code> alias.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x00</span>, <span class="hljs-number">0x00</span>, <span class="hljs-number">0x00</span>, <span class="hljs-number">0x00</span>, <span class="hljs-number">0xff</span>, <span class="hljs-number">0xff</span>, <span class="hljs-number">0xff</span>, <span class="hljs-number">0xff</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readBigUInt64LE</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 18446744069414584320n</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x00</span>, <span class="hljs-number">0x00</span>, <span class="hljs-number">0x00</span>, <span class="hljs-number">0x00</span>, <span class="hljs-number">0xff</span>, <span class="hljs-number">0xff</span>, <span class="hljs-number">0xff</span>, <span class="hljs-number">0xff</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readBigUInt64LE</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 18446744069414584320n</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.readDoubleBE([offset])</code><span><a class="mark" href="#all_buffer_bufreaddoublebeoffset" id="all_buffer_bufreaddoublebeoffset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readdoublebe_offset"></a></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>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, big-endian double from <code>buf</code> at the specified <code>offset</code>.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readDoubleBE</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 8.20788039913184e-304</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readDoubleBE</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 8.20788039913184e-304</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.readDoubleLE([offset])</code><span><a class="mark" href="#all_buffer_bufreaddoubleleoffset" id="all_buffer_bufreaddoubleleoffset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readdoublele_offset"></a></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>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, little-endian double from <code>buf</code> at the specified <code>offset</code>.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readDoubleLE</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 5.447603722011605e-270</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readDoubleLE</span>(<span class="hljs-number">1</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readDoubleLE</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 5.447603722011605e-270</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readDoubleLE</span>(<span class="hljs-number">1</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.readFloatBE([offset])</code><span><a class="mark" href="#all_buffer_bufreadfloatbeoffset" id="all_buffer_bufreadfloatbeoffset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readfloatbe_offset"></a></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>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, big-endian float from <code>buf</code> at the specified <code>offset</code>.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readFloatBE</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 2.387939260590663e-38</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readFloatBE</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 2.387939260590663e-38</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.readFloatLE([offset])</code><span><a class="mark" href="#all_buffer_bufreadfloatleoffset" id="all_buffer_bufreadfloatleoffset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readfloatle_offset"></a></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>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, little-endian float from <code>buf</code> at the specified <code>offset</code>.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readFloatLE</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 1.539989614439558e-36</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readFloatLE</span>(<span class="hljs-number">1</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readFloatLE</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 1.539989614439558e-36</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readFloatLE</span>(<span class="hljs-number">1</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.readInt8([offset])</code><span><a class="mark" href="#all_buffer_bufreadint8offset" id="all_buffer_bufreadint8offset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readint8_offset"></a></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>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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([-<span class="hljs-number">1</span>, <span class="hljs-number">5</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readInt8</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: -1</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readInt8</span>(<span class="hljs-number">1</span>));
<span class="hljs-comment">// Prints: 5</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readInt8</span>(<span class="hljs-number">2</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([-<span class="hljs-number">1</span>, <span class="hljs-number">5</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readInt8</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: -1</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readInt8</span>(<span class="hljs-number">1</span>));
<span class="hljs-comment">// Prints: 5</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readInt8</span>(<span class="hljs-number">2</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.readInt16BE([offset])</code><span><a class="mark" href="#all_buffer_bufreadint16beoffset" id="all_buffer_bufreadint16beoffset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readint16be_offset"></a></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>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, big-endian 16-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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0</span>, <span class="hljs-number">5</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readInt16BE</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 5</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0</span>, <span class="hljs-number">5</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readInt16BE</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 5</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.readInt16LE([offset])</code><span><a class="mark" href="#all_buffer_bufreadint16leoffset" id="all_buffer_bufreadint16leoffset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readint16le_offset"></a></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>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, little-endian 16-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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0</span>, <span class="hljs-number">5</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readInt16LE</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 1280</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readInt16LE</span>(<span class="hljs-number">1</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0</span>, <span class="hljs-number">5</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readInt16LE</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 1280</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readInt16LE</span>(<span class="hljs-number">1</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.readInt32BE([offset])</code><span><a class="mark" href="#all_buffer_bufreadint32beoffset" id="all_buffer_bufreadint32beoffset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readint32be_offset"></a></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>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, big-endian 32-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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">5</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readInt32BE</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 5</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">5</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readInt32BE</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 5</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.readInt32LE([offset])</code><span><a class="mark" href="#all_buffer_bufreadint32leoffset" id="all_buffer_bufreadint32leoffset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readint32le_offset"></a></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>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, little-endian 32-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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">5</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readInt32LE</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 83886080</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readInt32LE</span>(<span class="hljs-number">1</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">5</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readInt32LE</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 83886080</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readInt32LE</span>(<span class="hljs-number">1</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.readIntBE(offset, byteLength)</code><span><a class="mark" href="#all_buffer_bufreadintbeoffset-bytelength" id="all_buffer_bufreadintbeoffset-bytelength">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readintbe_offset_bytelength"></a></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>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 big-endian, two's complement signed value
supporting up to 48 bits of accuracy.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x12</span>, <span class="hljs-number">0x34</span>, <span class="hljs-number">0x56</span>, <span class="hljs-number">0x78</span>, <span class="hljs-number">0x90</span>, <span class="hljs-number">0xab</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readIntBE</span>(<span class="hljs-number">0</span>, <span class="hljs-number">6</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Prints: 1234567890ab</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readIntBE</span>(<span class="hljs-number">1</span>, <span class="hljs-number">6</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readIntBE</span>(<span class="hljs-number">1</span>, <span class="hljs-number">0</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x12</span>, <span class="hljs-number">0x34</span>, <span class="hljs-number">0x56</span>, <span class="hljs-number">0x78</span>, <span class="hljs-number">0x90</span>, <span class="hljs-number">0xab</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readIntBE</span>(<span class="hljs-number">0</span>, <span class="hljs-number">6</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Prints: 1234567890ab</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readIntBE</span>(<span class="hljs-number">1</span>, <span class="hljs-number">6</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readIntBE</span>(<span class="hljs-number">1</span>, <span class="hljs-number">0</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.readIntLE(offset, byteLength)</code><span><a class="mark" href="#all_buffer_bufreadintleoffset-bytelength" id="all_buffer_bufreadintleoffset-bytelength">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readintle_offset_bytelength"></a></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>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 little-endian, two's complement signed value
supporting up to 48 bits of accuracy.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x12</span>, <span class="hljs-number">0x34</span>, <span class="hljs-number">0x56</span>, <span class="hljs-number">0x78</span>, <span class="hljs-number">0x90</span>, <span class="hljs-number">0xab</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readIntLE</span>(<span class="hljs-number">0</span>, <span class="hljs-number">6</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Prints: -546f87a9cbee</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x12</span>, <span class="hljs-number">0x34</span>, <span class="hljs-number">0x56</span>, <span class="hljs-number">0x78</span>, <span class="hljs-number">0x90</span>, <span class="hljs-number">0xab</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readIntLE</span>(<span class="hljs-number">0</span>, <span class="hljs-number">6</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Prints: -546f87a9cbee</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.readUInt8([offset])</code><span><a class="mark" href="#all_buffer_bufreaduint8offset" id="all_buffer_bufreaduint8offset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readuint8_offset"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.9.0, v12.19.0</td>
<td><p>This function is also available as <code>buf.readUint8()</code>.</p></td></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>
<p>This function is also available under the <code>readUint8</code> alias.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, -<span class="hljs-number">2</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt8</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 1</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt8</span>(<span class="hljs-number">1</span>));
<span class="hljs-comment">// Prints: 254</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt8</span>(<span class="hljs-number">2</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, -<span class="hljs-number">2</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt8</span>(<span class="hljs-number">0</span>));
<span class="hljs-comment">// Prints: 1</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt8</span>(<span class="hljs-number">1</span>));
<span class="hljs-comment">// Prints: 254</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt8</span>(<span class="hljs-number">2</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.readUInt16BE([offset])</code><span><a class="mark" href="#all_buffer_bufreaduint16beoffset" id="all_buffer_bufreaduint16beoffset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readuint16be_offset"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.9.0, v12.19.0</td>
<td><p>This function is also available as <code>buf.readUint16BE()</code>.</p></td></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, big-endian 16-bit integer from <code>buf</code> at the specified
<code>offset</code>.</p>
<p>This function is also available under the <code>readUint16BE</code> alias.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x12</span>, <span class="hljs-number">0x34</span>, <span class="hljs-number">0x56</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt16BE</span>(<span class="hljs-number">0</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Prints: 1234</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt16BE</span>(<span class="hljs-number">1</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Prints: 3456</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x12</span>, <span class="hljs-number">0x34</span>, <span class="hljs-number">0x56</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt16BE</span>(<span class="hljs-number">0</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Prints: 1234</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt16BE</span>(<span class="hljs-number">1</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Prints: 3456</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.readUInt16LE([offset])</code><span><a class="mark" href="#all_buffer_bufreaduint16leoffset" id="all_buffer_bufreaduint16leoffset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readuint16le_offset"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.9.0, v12.19.0</td>
<td><p>This function is also available as <code>buf.readUint16LE()</code>.</p></td></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, little-endian 16-bit integer from <code>buf</code> at the specified
<code>offset</code>.</p>
<p>This function is also available under the <code>readUint16LE</code> alias.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x12</span>, <span class="hljs-number">0x34</span>, <span class="hljs-number">0x56</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt16LE</span>(<span class="hljs-number">0</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Prints: 3412</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt16LE</span>(<span class="hljs-number">1</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Prints: 5634</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt16LE</span>(<span class="hljs-number">2</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x12</span>, <span class="hljs-number">0x34</span>, <span class="hljs-number">0x56</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt16LE</span>(<span class="hljs-number">0</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Prints: 3412</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt16LE</span>(<span class="hljs-number">1</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Prints: 5634</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt16LE</span>(<span class="hljs-number">2</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.readUInt32BE([offset])</code><span><a class="mark" href="#all_buffer_bufreaduint32beoffset" id="all_buffer_bufreaduint32beoffset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readuint32be_offset"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.9.0, v12.19.0</td>
<td><p>This function is also available as <code>buf.readUint32BE()</code>.</p></td></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, big-endian 32-bit integer from <code>buf</code> at the specified
<code>offset</code>.</p>
<p>This function is also available under the <code>readUint32BE</code> alias.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x12</span>, <span class="hljs-number">0x34</span>, <span class="hljs-number">0x56</span>, <span class="hljs-number">0x78</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt32BE</span>(<span class="hljs-number">0</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Prints: 12345678</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x12</span>, <span class="hljs-number">0x34</span>, <span class="hljs-number">0x56</span>, <span class="hljs-number">0x78</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt32BE</span>(<span class="hljs-number">0</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Prints: 12345678</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.readUInt32LE([offset])</code><span><a class="mark" href="#all_buffer_bufreaduint32leoffset" id="all_buffer_bufreaduint32leoffset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readuint32le_offset"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.9.0, v12.19.0</td>
<td><p>This function is also available as <code>buf.readUint32LE()</code>.</p></td></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, little-endian 32-bit integer from <code>buf</code> at the specified
<code>offset</code>.</p>
<p>This function is also available under the <code>readUint32LE</code> alias.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x12</span>, <span class="hljs-number">0x34</span>, <span class="hljs-number">0x56</span>, <span class="hljs-number">0x78</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt32LE</span>(<span class="hljs-number">0</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Prints: 78563412</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt32LE</span>(<span class="hljs-number">1</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x12</span>, <span class="hljs-number">0x34</span>, <span class="hljs-number">0x56</span>, <span class="hljs-number">0x78</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt32LE</span>(<span class="hljs-number">0</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Prints: 78563412</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUInt32LE</span>(<span class="hljs-number">1</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.readUIntBE(offset, byteLength)</code><span><a class="mark" href="#all_buffer_bufreaduintbeoffset-bytelength" id="all_buffer_bufreaduintbeoffset-bytelength">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readuintbe_offset_bytelength"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.9.0, v12.19.0</td>
<td><p>This function is also available as <code>buf.readUintBE()</code>.</p></td></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 big-endian integer supporting
up to 48 bits of accuracy.</p>
<p>This function is also available under the <code>readUintBE</code> alias.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x12</span>, <span class="hljs-number">0x34</span>, <span class="hljs-number">0x56</span>, <span class="hljs-number">0x78</span>, <span class="hljs-number">0x90</span>, <span class="hljs-number">0xab</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUIntBE</span>(<span class="hljs-number">0</span>, <span class="hljs-number">6</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Prints: 1234567890ab</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUIntBE</span>(<span class="hljs-number">1</span>, <span class="hljs-number">6</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x12</span>, <span class="hljs-number">0x34</span>, <span class="hljs-number">0x56</span>, <span class="hljs-number">0x78</span>, <span class="hljs-number">0x90</span>, <span class="hljs-number">0xab</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUIntBE</span>(<span class="hljs-number">0</span>, <span class="hljs-number">6</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Prints: 1234567890ab</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUIntBE</span>(<span class="hljs-number">1</span>, <span class="hljs-number">6</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Throws ERR_OUT_OF_RANGE.</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.readUIntLE(offset, byteLength)</code><span><a class="mark" href="#all_buffer_bufreaduintleoffset-bytelength" id="all_buffer_bufreaduintleoffset-bytelength">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_readuintle_offset_bytelength"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.9.0, v12.19.0</td>
<td><p>This function is also available as <code>buf.readUintLE()</code>.</p></td></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, little-endian integer supporting
up to 48 bits of accuracy.</p>
<p>This function is also available under the <code>readUintLE</code> alias.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x12</span>, <span class="hljs-number">0x34</span>, <span class="hljs-number">0x56</span>, <span class="hljs-number">0x78</span>, <span class="hljs-number">0x90</span>, <span class="hljs-number">0xab</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUIntLE</span>(<span class="hljs-number">0</span>, <span class="hljs-number">6</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Prints: ab9078563412</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x12</span>, <span class="hljs-number">0x34</span>, <span class="hljs-number">0x56</span>, <span class="hljs-number">0x78</span>, <span class="hljs-number">0x90</span>, <span class="hljs-number">0xab</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">readUIntLE</span>(<span class="hljs-number">0</span>, <span class="hljs-number">6</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>));
<span class="hljs-comment">// Prints: ab9078563412</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.subarray([start[, end]])</code><span><a class="mark" href="#all_buffer_bufsubarraystart-end" id="all_buffer_bufsubarraystart-end">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_subarray_start_end"></a></h4>
<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="#all_buffer_buflength"><code>buf.length</code></a>.</li>
<li>Returns: <a href="#all_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> indexes.</p>
<p>Specifying <code>end</code> greater than <a href="#all_buffer_buflength"><code>buf.length</code></a> will return the same result as
that of <code>end</code> equal to <a href="#all_buffer_buflength"><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.prototype.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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-comment">// Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte</span>
<span class="hljs-comment">// from the original `Buffer`.</span>

<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">26</span>);

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; <span class="hljs-number">26</span>; i++) {
  <span class="hljs-comment">// 97 is the decimal ASCII value for 'a'.</span>
  buf1[i] = i + <span class="hljs-number">97</span>;
}

<span class="hljs-keyword">const</span> buf2 = buf1.<span class="hljs-title function_">subarray</span>(<span class="hljs-number">0</span>, <span class="hljs-number">3</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'ascii'</span>, <span class="hljs-number">0</span>, buf2.<span class="hljs-property">length</span>));
<span class="hljs-comment">// Prints: abc</span>

buf1[<span class="hljs-number">0</span>] = <span class="hljs-number">33</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'ascii'</span>, <span class="hljs-number">0</span>, buf2.<span class="hljs-property">length</span>));
<span class="hljs-comment">// Prints: !bc</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-comment">// Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte</span>
<span class="hljs-comment">// from the original `Buffer`.</span>

<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">26</span>);

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; <span class="hljs-number">26</span>; i++) {
  <span class="hljs-comment">// 97 is the decimal ASCII value for 'a'.</span>
  buf1[i] = i + <span class="hljs-number">97</span>;
}

<span class="hljs-keyword">const</span> buf2 = buf1.<span class="hljs-title function_">subarray</span>(<span class="hljs-number">0</span>, <span class="hljs-number">3</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'ascii'</span>, <span class="hljs-number">0</span>, buf2.<span class="hljs-property">length</span>));
<span class="hljs-comment">// Prints: abc</span>

buf1[<span class="hljs-number">0</span>] = <span class="hljs-number">33</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'ascii'</span>, <span class="hljs-number">0</span>, buf2.<span class="hljs-property">length</span>));
<span class="hljs-comment">// Prints: !bc</span></code><button class="copy-button">copy</button></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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'buffer'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">subarray</span>(-<span class="hljs-number">6</span>, -<span class="hljs-number">1</span>).<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: buffe</span>
<span class="hljs-comment">// (Equivalent to buf.subarray(0, 5).)</span>

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">subarray</span>(-<span class="hljs-number">6</span>, -<span class="hljs-number">2</span>).<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: buff</span>
<span class="hljs-comment">// (Equivalent to buf.subarray(0, 4).)</span>

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">subarray</span>(-<span class="hljs-number">5</span>, -<span class="hljs-number">2</span>).<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: uff</span>
<span class="hljs-comment">// (Equivalent to buf.subarray(1, 4).)</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'buffer'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">subarray</span>(-<span class="hljs-number">6</span>, -<span class="hljs-number">1</span>).<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: buffe</span>
<span class="hljs-comment">// (Equivalent to buf.subarray(0, 5).)</span>

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">subarray</span>(-<span class="hljs-number">6</span>, -<span class="hljs-number">2</span>).<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: buff</span>
<span class="hljs-comment">// (Equivalent to buf.subarray(0, 4).)</span>

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">subarray</span>(-<span class="hljs-number">5</span>, -<span class="hljs-number">2</span>).<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: uff</span>
<span class="hljs-comment">// (Equivalent to buf.subarray(1, 4).)</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.slice([start[, end]])</code><span><a class="mark" href="#all_buffer_bufslicestart-end" id="all_buffer_bufslicestart-end">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_slice_start_end"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.5.0, v16.15.0</td>
<td><p>The buf.slice() method has been deprecated.</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>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>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="#all_buffer_buflength"><code>buf.length</code></a>.</li>
<li>Returns: <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a></li>
</ul>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_buffer_bufsubarraystart-end"><code>buf.subarray</code></a> instead.</div><p></p>
<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> indexes.</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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'buffer'</span>);

<span class="hljs-keyword">const</span> copiedBuf = <span class="hljs-title class_">Uint8Array</span>.<span class="hljs-property"><span class="hljs-keyword">prototype</span></span>.<span class="hljs-property">slice</span>.<span class="hljs-title function_">call</span>(buf);
copiedBuf[<span class="hljs-number">0</span>]++;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(copiedBuf.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: cuffer</span>

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: buffer</span>

<span class="hljs-comment">// With buf.slice(), the original buffer is modified.</span>
<span class="hljs-keyword">const</span> notReallyCopiedBuf = buf.<span class="hljs-title function_">slice</span>();
notReallyCopiedBuf[<span class="hljs-number">0</span>]++;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(notReallyCopiedBuf.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: cuffer</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Also prints: cuffer (!)</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'buffer'</span>);

<span class="hljs-keyword">const</span> copiedBuf = <span class="hljs-title class_">Uint8Array</span>.<span class="hljs-property"><span class="hljs-keyword">prototype</span></span>.<span class="hljs-property">slice</span>.<span class="hljs-title function_">call</span>(buf);
copiedBuf[<span class="hljs-number">0</span>]++;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(copiedBuf.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: cuffer</span>

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: buffer</span>

<span class="hljs-comment">// With buf.slice(), the original buffer is modified.</span>
<span class="hljs-keyword">const</span> notReallyCopiedBuf = buf.<span class="hljs-title function_">slice</span>();
notReallyCopiedBuf[<span class="hljs-number">0</span>]++;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(notReallyCopiedBuf.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: cuffer</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Also prints: cuffer (!)</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.swap16()</code><span><a class="mark" href="#all_buffer_bufswap16" id="all_buffer_bufswap16">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_swap16"></a></h4>
<div class="api_metadata">
<span>Added in: v5.10.0</span>
</div>
<ul>
<li>Returns: <a href="#all_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="#all_errors_err_invalid_buffer_size"><code>ERR_INVALID_BUFFER_SIZE</code></a> if <a href="#all_buffer_buflength"><code>buf.length</code></a>
is not a multiple of 2.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x1</span>, <span class="hljs-number">0x2</span>, <span class="hljs-number">0x3</span>, <span class="hljs-number">0x4</span>, <span class="hljs-number">0x5</span>, <span class="hljs-number">0x6</span>, <span class="hljs-number">0x7</span>, <span class="hljs-number">0x8</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1);
<span class="hljs-comment">// Prints: &#x3C;Buffer 01 02 03 04 05 06 07 08></span>

buf1.<span class="hljs-title function_">swap16</span>();

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1);
<span class="hljs-comment">// Prints: &#x3C;Buffer 02 01 04 03 06 05 08 07></span>

<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x1</span>, <span class="hljs-number">0x2</span>, <span class="hljs-number">0x3</span>]);

buf2.<span class="hljs-title function_">swap16</span>();
<span class="hljs-comment">// Throws ERR_INVALID_BUFFER_SIZE.</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x1</span>, <span class="hljs-number">0x2</span>, <span class="hljs-number">0x3</span>, <span class="hljs-number">0x4</span>, <span class="hljs-number">0x5</span>, <span class="hljs-number">0x6</span>, <span class="hljs-number">0x7</span>, <span class="hljs-number">0x8</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1);
<span class="hljs-comment">// Prints: &#x3C;Buffer 01 02 03 04 05 06 07 08></span>

buf1.<span class="hljs-title function_">swap16</span>();

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1);
<span class="hljs-comment">// Prints: &#x3C;Buffer 02 01 04 03 06 05 08 07></span>

<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x1</span>, <span class="hljs-number">0x2</span>, <span class="hljs-number">0x3</span>]);

buf2.<span class="hljs-title function_">swap16</span>();
<span class="hljs-comment">// Throws ERR_INVALID_BUFFER_SIZE.</span></code><button class="copy-button">copy</button></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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'This is little-endian UTF-16'</span>, <span class="hljs-string">'utf16le'</span>);
buf.<span class="hljs-title function_">swap16</span>(); <span class="hljs-comment">// Convert to big-endian UTF-16 text.</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'This is little-endian UTF-16'</span>, <span class="hljs-string">'utf16le'</span>);
buf.<span class="hljs-title function_">swap16</span>(); <span class="hljs-comment">// Convert to big-endian UTF-16 text.</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.swap32()</code><span><a class="mark" href="#all_buffer_bufswap32" id="all_buffer_bufswap32">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_swap32"></a></h4>
<div class="api_metadata">
<span>Added in: v5.10.0</span>
</div>
<ul>
<li>Returns: <a href="#all_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="#all_errors_err_invalid_buffer_size"><code>ERR_INVALID_BUFFER_SIZE</code></a> if <a href="#all_buffer_buflength"><code>buf.length</code></a>
is not a multiple of 4.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x1</span>, <span class="hljs-number">0x2</span>, <span class="hljs-number">0x3</span>, <span class="hljs-number">0x4</span>, <span class="hljs-number">0x5</span>, <span class="hljs-number">0x6</span>, <span class="hljs-number">0x7</span>, <span class="hljs-number">0x8</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1);
<span class="hljs-comment">// Prints: &#x3C;Buffer 01 02 03 04 05 06 07 08></span>

buf1.<span class="hljs-title function_">swap32</span>();

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1);
<span class="hljs-comment">// Prints: &#x3C;Buffer 04 03 02 01 08 07 06 05></span>

<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x1</span>, <span class="hljs-number">0x2</span>, <span class="hljs-number">0x3</span>]);

buf2.<span class="hljs-title function_">swap32</span>();
<span class="hljs-comment">// Throws ERR_INVALID_BUFFER_SIZE.</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x1</span>, <span class="hljs-number">0x2</span>, <span class="hljs-number">0x3</span>, <span class="hljs-number">0x4</span>, <span class="hljs-number">0x5</span>, <span class="hljs-number">0x6</span>, <span class="hljs-number">0x7</span>, <span class="hljs-number">0x8</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1);
<span class="hljs-comment">// Prints: &#x3C;Buffer 01 02 03 04 05 06 07 08></span>

buf1.<span class="hljs-title function_">swap32</span>();

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1);
<span class="hljs-comment">// Prints: &#x3C;Buffer 04 03 02 01 08 07 06 05></span>

<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x1</span>, <span class="hljs-number">0x2</span>, <span class="hljs-number">0x3</span>]);

buf2.<span class="hljs-title function_">swap32</span>();
<span class="hljs-comment">// Throws ERR_INVALID_BUFFER_SIZE.</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.swap64()</code><span><a class="mark" href="#all_buffer_bufswap64" id="all_buffer_bufswap64">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_swap64"></a></h4>
<div class="api_metadata">
<span>Added in: v6.3.0</span>
</div>
<ul>
<li>Returns: <a href="#all_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="#all_errors_err_invalid_buffer_size"><code>ERR_INVALID_BUFFER_SIZE</code></a> if <a href="#all_buffer_buflength"><code>buf.length</code></a> is not a multiple of 8.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x1</span>, <span class="hljs-number">0x2</span>, <span class="hljs-number">0x3</span>, <span class="hljs-number">0x4</span>, <span class="hljs-number">0x5</span>, <span class="hljs-number">0x6</span>, <span class="hljs-number">0x7</span>, <span class="hljs-number">0x8</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1);
<span class="hljs-comment">// Prints: &#x3C;Buffer 01 02 03 04 05 06 07 08></span>

buf1.<span class="hljs-title function_">swap64</span>();

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1);
<span class="hljs-comment">// Prints: &#x3C;Buffer 08 07 06 05 04 03 02 01></span>

<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x1</span>, <span class="hljs-number">0x2</span>, <span class="hljs-number">0x3</span>]);

buf2.<span class="hljs-title function_">swap64</span>();
<span class="hljs-comment">// Throws ERR_INVALID_BUFFER_SIZE.</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x1</span>, <span class="hljs-number">0x2</span>, <span class="hljs-number">0x3</span>, <span class="hljs-number">0x4</span>, <span class="hljs-number">0x5</span>, <span class="hljs-number">0x6</span>, <span class="hljs-number">0x7</span>, <span class="hljs-number">0x8</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1);
<span class="hljs-comment">// Prints: &#x3C;Buffer 01 02 03 04 05 06 07 08></span>

buf1.<span class="hljs-title function_">swap64</span>();

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1);
<span class="hljs-comment">// Prints: &#x3C;Buffer 08 07 06 05 04 03 02 01></span>

<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x1</span>, <span class="hljs-number">0x2</span>, <span class="hljs-number">0x3</span>]);

buf2.<span class="hljs-title function_">swap64</span>();
<span class="hljs-comment">// Throws ERR_INVALID_BUFFER_SIZE.</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.toJSON()</code><span><a class="mark" href="#all_buffer_buftojson" id="all_buffer_buftojson">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_tojson"></a></h4>
<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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x1</span>, <span class="hljs-number">0x2</span>, <span class="hljs-number">0x3</span>, <span class="hljs-number">0x4</span>, <span class="hljs-number">0x5</span>]);
<span class="hljs-keyword">const</span> json = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(buf);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(json);
<span class="hljs-comment">// Prints: {"type":"Buffer","data":[1,2,3,4,5]}</span>

<span class="hljs-keyword">const</span> copy = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(json, <span class="hljs-function">(<span class="hljs-params">key, value</span>) =></span> {
  <span class="hljs-keyword">return</span> value &#x26;&#x26; value.<span class="hljs-property">type</span> === <span class="hljs-string">'Buffer'</span> ?
    <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(value) :
    value;
});

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(copy);
<span class="hljs-comment">// Prints: &#x3C;Buffer 01 02 03 04 05></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x1</span>, <span class="hljs-number">0x2</span>, <span class="hljs-number">0x3</span>, <span class="hljs-number">0x4</span>, <span class="hljs-number">0x5</span>]);
<span class="hljs-keyword">const</span> json = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(buf);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(json);
<span class="hljs-comment">// Prints: {"type":"Buffer","data":[1,2,3,4,5]}</span>

<span class="hljs-keyword">const</span> copy = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(json, <span class="hljs-function">(<span class="hljs-params">key, value</span>) =></span> {
  <span class="hljs-keyword">return</span> value &#x26;&#x26; value.<span class="hljs-property">type</span> === <span class="hljs-string">'Buffer'</span> ?
    <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(value) :
    value;
});

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(copy);
<span class="hljs-comment">// Prints: &#x3C;Buffer 01 02 03 04 05></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.toString([encoding[, start[, end]]])</code><span><a class="mark" href="#all_buffer_buftostringencoding-start-end" id="all_buffer_buftostringencoding-start-end">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_tostring_encoding_start_end"></a></h4>
<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="#all_buffer_buflength"><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="#all_buffer_bufferconstantsmax_string_length"><code>buffer.constants.MAX_STRING_LENGTH</code></a>.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">26</span>);

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; <span class="hljs-number">26</span>; i++) {
  <span class="hljs-comment">// 97 is the decimal ASCII value for 'a'.</span>
  buf1[i] = i + <span class="hljs-number">97</span>;
}

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'utf8'</span>));
<span class="hljs-comment">// Prints: abcdefghijklmnopqrstuvwxyz</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'utf8'</span>, <span class="hljs-number">0</span>, <span class="hljs-number">5</span>));
<span class="hljs-comment">// Prints: abcde</span>

<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'tést'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// Prints: 74c3a97374</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'utf8'</span>, <span class="hljs-number">0</span>, <span class="hljs-number">3</span>));
<span class="hljs-comment">// Prints: té</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2.<span class="hljs-title function_">toString</span>(<span class="hljs-literal">undefined</span>, <span class="hljs-number">0</span>, <span class="hljs-number">3</span>));
<span class="hljs-comment">// Prints: té</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">26</span>);

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; <span class="hljs-number">26</span>; i++) {
  <span class="hljs-comment">// 97 is the decimal ASCII value for 'a'.</span>
  buf1[i] = i + <span class="hljs-number">97</span>;
}

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'utf8'</span>));
<span class="hljs-comment">// Prints: abcdefghijklmnopqrstuvwxyz</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf1.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'utf8'</span>, <span class="hljs-number">0</span>, <span class="hljs-number">5</span>));
<span class="hljs-comment">// Prints: abcde</span>

<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'tést'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// Prints: 74c3a97374</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'utf8'</span>, <span class="hljs-number">0</span>, <span class="hljs-number">3</span>));
<span class="hljs-comment">// Prints: té</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf2.<span class="hljs-title function_">toString</span>(<span class="hljs-literal">undefined</span>, <span class="hljs-number">0</span>, <span class="hljs-number">3</span>));
<span class="hljs-comment">// Prints: té</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.values()</code><span><a class="mark" href="#all_buffer_bufvalues" id="all_buffer_bufvalues">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_values"></a></h4>
<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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'buffer'</span>);

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> value <span class="hljs-keyword">of</span> buf.<span class="hljs-title function_">values</span>()) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(value);
}
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   98</span>
<span class="hljs-comment">//   117</span>
<span class="hljs-comment">//   102</span>
<span class="hljs-comment">//   102</span>
<span class="hljs-comment">//   101</span>
<span class="hljs-comment">//   114</span>

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> value <span class="hljs-keyword">of</span> buf) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(value);
}
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   98</span>
<span class="hljs-comment">//   117</span>
<span class="hljs-comment">//   102</span>
<span class="hljs-comment">//   102</span>
<span class="hljs-comment">//   101</span>
<span class="hljs-comment">//   114</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'buffer'</span>);

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> value <span class="hljs-keyword">of</span> buf.<span class="hljs-title function_">values</span>()) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(value);
}
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   98</span>
<span class="hljs-comment">//   117</span>
<span class="hljs-comment">//   102</span>
<span class="hljs-comment">//   102</span>
<span class="hljs-comment">//   101</span>
<span class="hljs-comment">//   114</span>

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> value <span class="hljs-keyword">of</span> buf) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(value);
}
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   98</span>
<span class="hljs-comment">//   117</span>
<span class="hljs-comment">//   102</span>
<span class="hljs-comment">//   102</span>
<span class="hljs-comment">//   101</span>
<span class="hljs-comment">//   114</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.write(string[, offset[, length]][, encoding])</code><span><a class="mark" href="#all_buffer_bufwritestring-offset-length-encoding" id="all_buffer_bufwritestring-offset-length-encoding">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_write_string_offset_length_encoding"></a></h4>
<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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">256</span>);

<span class="hljs-keyword">const</span> len = buf.<span class="hljs-title function_">write</span>(<span class="hljs-string">'\u00bd + \u00bc = \u00be'</span>, <span class="hljs-number">0</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${len}</span> bytes: <span class="hljs-subst">${buf.toString(<span class="hljs-string">'utf8'</span>, <span class="hljs-number">0</span>, len)}</span>`</span>);
<span class="hljs-comment">// Prints: 12 bytes: ½ + ¼ = ¾</span>

<span class="hljs-keyword">const</span> buffer = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">10</span>);

<span class="hljs-keyword">const</span> length = buffer.<span class="hljs-title function_">write</span>(<span class="hljs-string">'abcd'</span>, <span class="hljs-number">8</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${length}</span> bytes: <span class="hljs-subst">${buffer.toString(<span class="hljs-string">'utf8'</span>, <span class="hljs-number">8</span>, <span class="hljs-number">10</span>)}</span>`</span>);
<span class="hljs-comment">// Prints: 2 bytes : ab</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">256</span>);

<span class="hljs-keyword">const</span> len = buf.<span class="hljs-title function_">write</span>(<span class="hljs-string">'\u00bd + \u00bc = \u00be'</span>, <span class="hljs-number">0</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${len}</span> bytes: <span class="hljs-subst">${buf.toString(<span class="hljs-string">'utf8'</span>, <span class="hljs-number">0</span>, len)}</span>`</span>);
<span class="hljs-comment">// Prints: 12 bytes: ½ + ¼ = ¾</span>

<span class="hljs-keyword">const</span> buffer = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">10</span>);

<span class="hljs-keyword">const</span> length = buffer.<span class="hljs-title function_">write</span>(<span class="hljs-string">'abcd'</span>, <span class="hljs-number">8</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${length}</span> bytes: <span class="hljs-subst">${buffer.toString(<span class="hljs-string">'utf8'</span>, <span class="hljs-number">8</span>, <span class="hljs-number">10</span>)}</span>`</span>);
<span class="hljs-comment">// Prints: 2 bytes : ab</span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeBigInt64BE(value[, offset])</code><span><a class="mark" href="#all_buffer_bufwritebigint64bevalue-offset" id="all_buffer_bufwritebigint64bevalue-offset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writebigint64be_value_offset"></a></h4>
<div class="api_metadata">
<span>Added in: v12.0.0, v10.20.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> as big-endian.</p>
<p><code>value</code> is interpreted and written as a two's complement signed integer.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">8</span>);

buf.<span class="hljs-title function_">writeBigInt64BE</span>(<span class="hljs-number">0x0102030405060708n</span>, <span class="hljs-number">0</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer 01 02 03 04 05 06 07 08></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">8</span>);

buf.<span class="hljs-title function_">writeBigInt64BE</span>(<span class="hljs-number">0x0102030405060708n</span>, <span class="hljs-number">0</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer 01 02 03 04 05 06 07 08></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeBigInt64LE(value[, offset])</code><span><a class="mark" href="#all_buffer_bufwritebigint64levalue-offset" id="all_buffer_bufwritebigint64levalue-offset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writebigint64le_value_offset"></a></h4>
<div class="api_metadata">
<span>Added in: v12.0.0, v10.20.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> as little-endian.</p>
<p><code>value</code> is interpreted and written as a two's complement signed integer.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">8</span>);

buf.<span class="hljs-title function_">writeBigInt64LE</span>(<span class="hljs-number">0x0102030405060708n</span>, <span class="hljs-number">0</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer 08 07 06 05 04 03 02 01></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">8</span>);

buf.<span class="hljs-title function_">writeBigInt64LE</span>(<span class="hljs-number">0x0102030405060708n</span>, <span class="hljs-number">0</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer 08 07 06 05 04 03 02 01></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeBigUInt64BE(value[, offset])</code><span><a class="mark" href="#all_buffer_bufwritebiguint64bevalue-offset" id="all_buffer_bufwritebiguint64bevalue-offset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writebiguint64be_value_offset"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.10.0, v12.19.0</td>
<td><p>This function is also available as <code>buf.writeBigUint64BE()</code>.</p></td></tr>
<tr><td>v12.0.0, v10.20.0</td>
<td><p><span>Added in: v12.0.0, v10.20.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/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> as big-endian.</p>
<p>This function is also available under the <code>writeBigUint64BE</code> alias.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">8</span>);

buf.<span class="hljs-title function_">writeBigUInt64BE</span>(<span class="hljs-number">0xdecafafecacefaden</span>, <span class="hljs-number">0</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer de ca fa fe ca ce fa de></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">8</span>);

buf.<span class="hljs-title function_">writeBigUInt64BE</span>(<span class="hljs-number">0xdecafafecacefaden</span>, <span class="hljs-number">0</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer de ca fa fe ca ce fa de></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeBigUInt64LE(value[, offset])</code><span><a class="mark" href="#all_buffer_bufwritebiguint64levalue-offset" id="all_buffer_bufwritebiguint64levalue-offset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writebiguint64le_value_offset"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.10.0, v12.19.0</td>
<td><p>This function is also available as <code>buf.writeBigUint64LE()</code>.</p></td></tr>
<tr><td>v12.0.0, v10.20.0</td>
<td><p><span>Added in: v12.0.0, v10.20.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/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> as little-endian</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">8</span>);

buf.<span class="hljs-title function_">writeBigUInt64LE</span>(<span class="hljs-number">0xdecafafecacefaden</span>, <span class="hljs-number">0</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer de fa ce ca fe fa ca de></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">8</span>);

buf.<span class="hljs-title function_">writeBigUInt64LE</span>(<span class="hljs-number">0xdecafafecacefaden</span>, <span class="hljs-number">0</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer de fa ce ca fe fa ca de></span></code><button class="copy-button">copy</button></pre>
<p>This function is also available under the <code>writeBigUint64LE</code> alias.</p>
<h4><code>buf.writeDoubleBE(value[, offset])</code><span><a class="mark" href="#all_buffer_bufwritedoublebevalue-offset" id="all_buffer_bufwritedoublebevalue-offset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writedoublebe_value_offset"></a></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>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> as big-endian. The <code>value</code>
must be a JavaScript number. Behavior is undefined when <code>value</code> is anything
other than a JavaScript number.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">8</span>);

buf.<span class="hljs-title function_">writeDoubleBE</span>(<span class="hljs-number">123.456</span>, <span class="hljs-number">0</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer 40 5e dd 2f 1a 9f be 77></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">8</span>);

buf.<span class="hljs-title function_">writeDoubleBE</span>(<span class="hljs-number">123.456</span>, <span class="hljs-number">0</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer 40 5e dd 2f 1a 9f be 77></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeDoubleLE(value[, offset])</code><span><a class="mark" href="#all_buffer_bufwritedoublelevalue-offset" id="all_buffer_bufwritedoublelevalue-offset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writedoublele_value_offset"></a></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>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> as little-endian. The <code>value</code>
must be a JavaScript number. Behavior is undefined when <code>value</code> is anything
other than a JavaScript number.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">8</span>);

buf.<span class="hljs-title function_">writeDoubleLE</span>(<span class="hljs-number">123.456</span>, <span class="hljs-number">0</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer 77 be 9f 1a 2f dd 5e 40></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">8</span>);

buf.<span class="hljs-title function_">writeDoubleLE</span>(<span class="hljs-number">123.456</span>, <span class="hljs-number">0</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer 77 be 9f 1a 2f dd 5e 40></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeFloatBE(value[, offset])</code><span><a class="mark" href="#all_buffer_bufwritefloatbevalue-offset" id="all_buffer_bufwritefloatbevalue-offset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writefloatbe_value_offset"></a></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>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> as big-endian. Behavior is
undefined when <code>value</code> is anything other than a JavaScript number.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">4</span>);

buf.<span class="hljs-title function_">writeFloatBE</span>(<span class="hljs-number">0xcafebabe</span>, <span class="hljs-number">0</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer 4f 4a fe bb></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">4</span>);

buf.<span class="hljs-title function_">writeFloatBE</span>(<span class="hljs-number">0xcafebabe</span>, <span class="hljs-number">0</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer 4f 4a fe bb></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeFloatLE(value[, offset])</code><span><a class="mark" href="#all_buffer_bufwritefloatlevalue-offset" id="all_buffer_bufwritefloatlevalue-offset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writefloatle_value_offset"></a></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>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> as little-endian. Behavior is
undefined when <code>value</code> is anything other than a JavaScript number.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">4</span>);

buf.<span class="hljs-title function_">writeFloatLE</span>(<span class="hljs-number">0xcafebabe</span>, <span class="hljs-number">0</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer bb fe 4a 4f></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">4</span>);

buf.<span class="hljs-title function_">writeFloatLE</span>(<span class="hljs-number">0xcafebabe</span>, <span class="hljs-number">0</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer bb fe 4a 4f></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeInt8(value[, offset])</code><span><a class="mark" href="#all_buffer_bufwriteint8value-offset" id="all_buffer_bufwriteint8value-offset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writeint8_value_offset"></a></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>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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">2</span>);

buf.<span class="hljs-title function_">writeInt8</span>(<span class="hljs-number">2</span>, <span class="hljs-number">0</span>);
buf.<span class="hljs-title function_">writeInt8</span>(-<span class="hljs-number">2</span>, <span class="hljs-number">1</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer 02 fe></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">2</span>);

buf.<span class="hljs-title function_">writeInt8</span>(<span class="hljs-number">2</span>, <span class="hljs-number">0</span>);
buf.<span class="hljs-title function_">writeInt8</span>(-<span class="hljs-number">2</span>, <span class="hljs-number">1</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer 02 fe></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeInt16BE(value[, offset])</code><span><a class="mark" href="#all_buffer_bufwriteint16bevalue-offset" id="all_buffer_bufwriteint16bevalue-offset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writeint16be_value_offset"></a></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>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> as big-endian.  The <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>The <code>value</code> is interpreted and written as a two's complement signed integer.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">2</span>);

buf.<span class="hljs-title function_">writeInt16BE</span>(<span class="hljs-number">0x0102</span>, <span class="hljs-number">0</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer 01 02></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">2</span>);

buf.<span class="hljs-title function_">writeInt16BE</span>(<span class="hljs-number">0x0102</span>, <span class="hljs-number">0</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer 01 02></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeInt16LE(value[, offset])</code><span><a class="mark" href="#all_buffer_bufwriteint16levalue-offset" id="all_buffer_bufwriteint16levalue-offset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writeint16le_value_offset"></a></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>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> as little-endian.  The <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>The <code>value</code> is interpreted and written as a two's complement signed integer.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">2</span>);

buf.<span class="hljs-title function_">writeInt16LE</span>(<span class="hljs-number">0x0304</span>, <span class="hljs-number">0</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer 04 03></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">2</span>);

buf.<span class="hljs-title function_">writeInt16LE</span>(<span class="hljs-number">0x0304</span>, <span class="hljs-number">0</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer 04 03></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeInt32BE(value[, offset])</code><span><a class="mark" href="#all_buffer_bufwriteint32bevalue-offset" id="all_buffer_bufwriteint32bevalue-offset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writeint32be_value_offset"></a></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>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> as big-endian. The <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>The <code>value</code> is interpreted and written as a two's complement signed integer.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">4</span>);

buf.<span class="hljs-title function_">writeInt32BE</span>(<span class="hljs-number">0x01020304</span>, <span class="hljs-number">0</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer 01 02 03 04></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">4</span>);

buf.<span class="hljs-title function_">writeInt32BE</span>(<span class="hljs-number">0x01020304</span>, <span class="hljs-number">0</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer 01 02 03 04></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeInt32LE(value[, offset])</code><span><a class="mark" href="#all_buffer_bufwriteint32levalue-offset" id="all_buffer_bufwriteint32levalue-offset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writeint32le_value_offset"></a></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>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> as little-endian. The <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>The <code>value</code> is interpreted and written as a two's complement signed integer.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">4</span>);

buf.<span class="hljs-title function_">writeInt32LE</span>(<span class="hljs-number">0x05060708</span>, <span class="hljs-number">0</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer 08 07 06 05></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">4</span>);

buf.<span class="hljs-title function_">writeInt32LE</span>(<span class="hljs-number">0x05060708</span>, <span class="hljs-number">0</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer 08 07 06 05></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeIntBE(value, offset, byteLength)</code><span><a class="mark" href="#all_buffer_bufwriteintbevalue-offset-bytelength" id="all_buffer_bufwriteintbevalue-offset-bytelength">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writeintbe_value_offset_bytelength"></a></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>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>
as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined when
<code>value</code> is anything other than a signed integer.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">6</span>);

buf.<span class="hljs-title function_">writeIntBE</span>(<span class="hljs-number">0x1234567890ab</span>, <span class="hljs-number">0</span>, <span class="hljs-number">6</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer 12 34 56 78 90 ab></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">6</span>);

buf.<span class="hljs-title function_">writeIntBE</span>(<span class="hljs-number">0x1234567890ab</span>, <span class="hljs-number">0</span>, <span class="hljs-number">6</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer 12 34 56 78 90 ab></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeIntLE(value, offset, byteLength)</code><span><a class="mark" href="#all_buffer_bufwriteintlevalue-offset-bytelength" id="all_buffer_bufwriteintlevalue-offset-bytelength">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writeintle_value_offset_bytelength"></a></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>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>
as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined
when <code>value</code> is anything other than a signed integer.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">6</span>);

buf.<span class="hljs-title function_">writeIntLE</span>(<span class="hljs-number">0x1234567890ab</span>, <span class="hljs-number">0</span>, <span class="hljs-number">6</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer ab 90 78 56 34 12></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">6</span>);

buf.<span class="hljs-title function_">writeIntLE</span>(<span class="hljs-number">0x1234567890ab</span>, <span class="hljs-number">0</span>, <span class="hljs-number">6</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer ab 90 78 56 34 12></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeUInt8(value[, offset])</code><span><a class="mark" href="#all_buffer_bufwriteuint8value-offset" id="all_buffer_bufwriteuint8value-offset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writeuint8_value_offset"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.9.0, v12.19.0</td>
<td><p>This function is also available as <code>buf.writeUint8()</code>.</p></td></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>
<p>This function is also available under the <code>writeUint8</code> alias.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">4</span>);

buf.<span class="hljs-title function_">writeUInt8</span>(<span class="hljs-number">0x3</span>, <span class="hljs-number">0</span>);
buf.<span class="hljs-title function_">writeUInt8</span>(<span class="hljs-number">0x4</span>, <span class="hljs-number">1</span>);
buf.<span class="hljs-title function_">writeUInt8</span>(<span class="hljs-number">0x23</span>, <span class="hljs-number">2</span>);
buf.<span class="hljs-title function_">writeUInt8</span>(<span class="hljs-number">0x42</span>, <span class="hljs-number">3</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer 03 04 23 42></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">4</span>);

buf.<span class="hljs-title function_">writeUInt8</span>(<span class="hljs-number">0x3</span>, <span class="hljs-number">0</span>);
buf.<span class="hljs-title function_">writeUInt8</span>(<span class="hljs-number">0x4</span>, <span class="hljs-number">1</span>);
buf.<span class="hljs-title function_">writeUInt8</span>(<span class="hljs-number">0x23</span>, <span class="hljs-number">2</span>);
buf.<span class="hljs-title function_">writeUInt8</span>(<span class="hljs-number">0x42</span>, <span class="hljs-number">3</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer 03 04 23 42></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeUInt16BE(value[, offset])</code><span><a class="mark" href="#all_buffer_bufwriteuint16bevalue-offset" id="all_buffer_bufwriteuint16bevalue-offset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writeuint16be_value_offset"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.9.0, v12.19.0</td>
<td><p>This function is also available as <code>buf.writeUint16BE()</code>.</p></td></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> as big-endian. The <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>
<p>This function is also available under the <code>writeUint16BE</code> alias.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">4</span>);

buf.<span class="hljs-title function_">writeUInt16BE</span>(<span class="hljs-number">0xdead</span>, <span class="hljs-number">0</span>);
buf.<span class="hljs-title function_">writeUInt16BE</span>(<span class="hljs-number">0xbeef</span>, <span class="hljs-number">2</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer de ad be ef></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">4</span>);

buf.<span class="hljs-title function_">writeUInt16BE</span>(<span class="hljs-number">0xdead</span>, <span class="hljs-number">0</span>);
buf.<span class="hljs-title function_">writeUInt16BE</span>(<span class="hljs-number">0xbeef</span>, <span class="hljs-number">2</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer de ad be ef></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeUInt16LE(value[, offset])</code><span><a class="mark" href="#all_buffer_bufwriteuint16levalue-offset" id="all_buffer_bufwriteuint16levalue-offset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writeuint16le_value_offset"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.9.0, v12.19.0</td>
<td><p>This function is also available as <code>buf.writeUint16LE()</code>.</p></td></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> as little-endian. The <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>
<p>This function is also available under the <code>writeUint16LE</code> alias.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">4</span>);

buf.<span class="hljs-title function_">writeUInt16LE</span>(<span class="hljs-number">0xdead</span>, <span class="hljs-number">0</span>);
buf.<span class="hljs-title function_">writeUInt16LE</span>(<span class="hljs-number">0xbeef</span>, <span class="hljs-number">2</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer ad de ef be></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">4</span>);

buf.<span class="hljs-title function_">writeUInt16LE</span>(<span class="hljs-number">0xdead</span>, <span class="hljs-number">0</span>);
buf.<span class="hljs-title function_">writeUInt16LE</span>(<span class="hljs-number">0xbeef</span>, <span class="hljs-number">2</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer ad de ef be></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeUInt32BE(value[, offset])</code><span><a class="mark" href="#all_buffer_bufwriteuint32bevalue-offset" id="all_buffer_bufwriteuint32bevalue-offset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writeuint32be_value_offset"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.9.0, v12.19.0</td>
<td><p>This function is also available as <code>buf.writeUint32BE()</code>.</p></td></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> as big-endian. The <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>
<p>This function is also available under the <code>writeUint32BE</code> alias.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">4</span>);

buf.<span class="hljs-title function_">writeUInt32BE</span>(<span class="hljs-number">0xfeedface</span>, <span class="hljs-number">0</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer fe ed fa ce></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">4</span>);

buf.<span class="hljs-title function_">writeUInt32BE</span>(<span class="hljs-number">0xfeedface</span>, <span class="hljs-number">0</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer fe ed fa ce></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeUInt32LE(value[, offset])</code><span><a class="mark" href="#all_buffer_bufwriteuint32levalue-offset" id="all_buffer_bufwriteuint32levalue-offset">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writeuint32le_value_offset"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.9.0, v12.19.0</td>
<td><p>This function is also available as <code>buf.writeUint32LE()</code>.</p></td></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> as little-endian. The <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>
<p>This function is also available under the <code>writeUint32LE</code> alias.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">4</span>);

buf.<span class="hljs-title function_">writeUInt32LE</span>(<span class="hljs-number">0xfeedface</span>, <span class="hljs-number">0</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer ce fa ed fe></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">4</span>);

buf.<span class="hljs-title function_">writeUInt32LE</span>(<span class="hljs-number">0xfeedface</span>, <span class="hljs-number">0</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer ce fa ed fe></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeUIntBE(value, offset, byteLength)</code><span><a class="mark" href="#all_buffer_bufwriteuintbevalue-offset-bytelength" id="all_buffer_bufwriteuintbevalue-offset-bytelength">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writeuintbe_value_offset_bytelength"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.9.0, v12.19.0</td>
<td><p>This function is also available as <code>buf.writeUintBE()</code>.</p></td></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>
as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined
when <code>value</code> is anything other than an unsigned integer.</p>
<p>This function is also available under the <code>writeUintBE</code> alias.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">6</span>);

buf.<span class="hljs-title function_">writeUIntBE</span>(<span class="hljs-number">0x1234567890ab</span>, <span class="hljs-number">0</span>, <span class="hljs-number">6</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer 12 34 56 78 90 ab></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">6</span>);

buf.<span class="hljs-title function_">writeUIntBE</span>(<span class="hljs-number">0x1234567890ab</span>, <span class="hljs-number">0</span>, <span class="hljs-number">6</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer 12 34 56 78 90 ab></span></code><button class="copy-button">copy</button></pre>
<h4><code>buf.writeUIntLE(value, offset, byteLength)</code><span><a class="mark" href="#all_buffer_bufwriteuintlevalue-offset-bytelength" id="all_buffer_bufwriteuintlevalue-offset-bytelength">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buf_writeuintle_value_offset_bytelength"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.9.0, v12.19.0</td>
<td><p>This function is also available as <code>buf.writeUintLE()</code>.</p></td></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>
as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined
when <code>value</code> is anything other than an unsigned integer.</p>
<p>This function is also available under the <code>writeUintLE</code> alias.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">6</span>);

buf.<span class="hljs-title function_">writeUIntLE</span>(<span class="hljs-number">0x1234567890ab</span>, <span class="hljs-number">0</span>, <span class="hljs-number">6</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer ab 90 78 56 34 12></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">allocUnsafe</span>(<span class="hljs-number">6</span>);

buf.<span class="hljs-title function_">writeUIntLE</span>(<span class="hljs-number">0x1234567890ab</span>, <span class="hljs-number">0</span>, <span class="hljs-number">6</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf);
<span class="hljs-comment">// Prints: &#x3C;Buffer ab 90 78 56 34 12></span></code><button class="copy-button">copy</button></pre>
<h4><code>new Buffer(array)</code><span><a class="mark" href="#all_buffer_new-bufferarray" id="all_buffer_new-bufferarray">#</a></span><a aria-hidden="true" class="legacy" id="buffer_new_buffer_array"></a></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>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="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_buffer_static-method-bufferfromarray"><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="#all_buffer_static-method-bufferfromarray"><code>Buffer.from(array)</code></a>.</p>
<h4><code>new Buffer(arrayBuffer[, byteOffset[, length]])</code><span><a class="mark" href="#all_buffer_new-bufferarraybuffer-byteoffset-length" id="all_buffer_new-bufferarraybuffer-byteoffset-length">#</a></span><a aria-hidden="true" class="legacy" id="buffer_new_buffer_arraybuffer_byteoffset_length"></a></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>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="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use
<a href="#all_buffer_static-method-bufferfromarraybuffer-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="#all_buffer_static-method-bufferfromarraybuffer-byteoffset-length"><code>Buffer.from(arrayBuffer[, byteOffset[, length]])</code></a>.</p>
<h4><code>new Buffer(buffer)</code><span><a class="mark" href="#all_buffer_new-bufferbuffer" id="all_buffer_new-bufferbuffer">#</a></span><a aria-hidden="true" class="legacy" id="buffer_new_buffer_buffer"></a></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>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="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_buffer_static-method-bufferfrombuffer"><code>Buffer.from(buffer)</code></a> instead.</div><p></p>
<ul>
<li><code>buffer</code> <a href="#all_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="#all_buffer_static-method-bufferfrombuffer"><code>Buffer.from(buffer)</code></a>.</p>
<h4><code>new Buffer(size)</code><span><a class="mark" href="#all_buffer_new-buffersize" id="all_buffer_new-buffersize">#</a></span><a aria-hidden="true" class="legacy" id="buffer_new_buffer_size"></a></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>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="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_buffer_static-method-bufferallocsize-fill-encoding"><code>Buffer.alloc()</code></a> instead (also see
<a href="#all_buffer_static-method-bufferallocunsafesize"><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="#all_buffer_static-method-bufferallocsize-fill-encoding"><code>Buffer.alloc()</code></a> and <a href="#all_buffer_static-method-bufferallocunsafesize"><code>Buffer.allocUnsafe()</code></a>. This variant of the
constructor is equivalent to <a href="#all_buffer_static-method-bufferallocsize-fill-encoding"><code>Buffer.alloc()</code></a>.</p>
<h4><code>new Buffer(string[, encoding])</code><span><a class="mark" href="#all_buffer_new-bufferstring-encoding" id="all_buffer_new-bufferstring-encoding">#</a></span><a aria-hidden="true" class="legacy" id="buffer_new_buffer_string_encoding"></a></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>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="#all_documentation_stability-index">Stability: 0</a> - Deprecated:
Use <a href="#all_buffer_static-method-bufferfromstring-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="#all_buffer_static-method-bufferfromstring-encoding"><code>Buffer.from(string[, encoding])</code></a>.</p>
</section><section><h3>Class: <code>File</code><span><a class="mark" href="#all_buffer_class-file" id="all_buffer_class-file">#</a></span><a aria-hidden="true" class="legacy" id="buffer_class_file"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>No longer experimental.</p></td></tr>
<tr><td>v19.2.0, v18.13.0</td>
<td><p><span>Added in: v19.2.0, v18.13.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Extends: <a href="#all_buffer_class-blob" class="type">&#x3C;Blob></a></li>
</ul>
<p>A <a href="https://developer.mozilla.org/en-US/docs/Web/API/File"><code>File</code></a> provides information about files.</p>
<h4><code>new buffer.File(sources, fileName[, options])</code><span><a class="mark" href="#all_buffer_new-bufferfilesources-filename-options" id="all_buffer_new-bufferfilesources-filename-options">#</a></span><a aria-hidden="true" class="legacy" id="buffer_new_buffer_file_sources_filename_options"></a></h4>
<div class="api_metadata">
<span>Added in: v19.2.0, v18.13.0</span>
</div>
<ul>
<li><code>sources</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/ArrayBuffer" class="type">&#x3C;ArrayBuffer[]></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="#all_buffer_class-blob" class="type">&#x3C;Blob[]></a> | <a href="#all_buffer_class-file" class="type">&#x3C;File[]></a>
An array of string, <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/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="#all_buffer_class-file" class="type">&#x3C;File></a>, or <a href="#all_buffer_class-blob" class="type">&#x3C;Blob></a>
objects, or any mix of such objects, that will be stored within the <code>File</code>.</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> The name of the file.</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>
<ul>
<li><code>endings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> One of either <code>'transparent'</code> or <code>'native'</code>. When set
to <code>'native'</code>, line endings in string source parts will be converted to
the platform native line-ending as specified by <code>require('node:os').EOL</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> The File content-type.</li>
<li><code>lastModified</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The last modified date of the file.
<strong>Default:</strong> <code>Date.now()</code>.</li>
</ul>
</li>
</ul>
<h4><code>file.name</code><span><a class="mark" href="#all_buffer_filename" id="all_buffer_filename">#</a></span><a aria-hidden="true" class="legacy" id="buffer_file_name"></a></h4>
<div class="api_metadata">
<span>Added in: v19.2.0, v18.13.0</span>
</div>
<ul>
<li>Type: <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 <code>File</code>.</p>
<h4><code>file.lastModified</code><span><a class="mark" href="#all_buffer_filelastmodified" id="all_buffer_filelastmodified">#</a></span><a aria-hidden="true" class="legacy" id="buffer_file_lastmodified"></a></h4>
<div class="api_metadata">
<span>Added in: v19.2.0, v18.13.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>The last modified date of the <code>File</code>.</p>
</section><section><h3><code>node:buffer</code> module APIs<span><a class="mark" href="#all_buffer_nodebuffer-module-apis" id="all_buffer_nodebuffer-module-apis">#</a></span><a aria-hidden="true" class="legacy" id="buffer_node_buffer_module_apis"></a></h3>
<p>While, the <code>Buffer</code> object is available as a global, there are additional
<code>Buffer</code>-related APIs that are available only via the <code>node:buffer</code> module
accessed using <code>require('node:buffer')</code>.</p>
<h4><code>buffer.atob(data)</code><span><a class="mark" href="#all_buffer_bufferatobdata" id="all_buffer_bufferatobdata">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buffer_atob_data"></a></h4>
<div class="api_metadata">
<span>Added in: v15.13.0, v14.17.0</span>
</div>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy. Use <code>Buffer.from(data, 'base64')</code> instead.</div><p></p>
<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> The Base64-encoded input string.</li>
</ul>
<p>Decodes a string of Base64-encoded data into bytes, and encodes those bytes
into a string using Latin-1 (ISO-8859-1).</p>
<p>The <code>data</code> may be any JavaScript-value that can be coerced into a string.</p>
<p><strong>This function is only provided for compatibility with legacy web platform APIs
and should never be used in new code, because they use strings to represent
binary data and predate the introduction of typed arrays in JavaScript.
For code running using Node.js APIs, converting between base64-encoded strings
and binary data should be performed using <code>Buffer.from(str, 'base64')</code> and
<code>buf.toString('base64')</code>.</strong></p>
<h4><code>buffer.btoa(data)</code><span><a class="mark" href="#all_buffer_bufferbtoadata" id="all_buffer_bufferbtoadata">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buffer_btoa_data"></a></h4>
<div class="api_metadata">
<span>Added in: v15.13.0, v14.17.0</span>
</div>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy. Use <code>buf.toString('base64')</code> instead.</div><p></p>
<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> An ASCII (Latin1) string.</li>
</ul>
<p>Decodes a string into bytes using Latin-1 (ISO-8859), and encodes those bytes
into a string using Base64.</p>
<p>The <code>data</code> may be any JavaScript-value that can be coerced into a string.</p>
<p><strong>This function is only provided for compatibility with legacy web platform APIs
and should never be used in new code, because they use strings to represent
binary data and predate the introduction of typed arrays in JavaScript.
For code running using Node.js APIs, converting between base64-encoded strings
and binary data should be performed using <code>Buffer.from(str, 'base64')</code> and
<code>buf.toString('base64')</code>.</strong></p>
<h4><code>buffer.isAscii(input)</code><span><a class="mark" href="#all_buffer_bufferisasciiinput" id="all_buffer_bufferisasciiinput">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buffer_isascii_input"></a></h4>
<div class="api_metadata">
<span>Added in: v19.6.0, v18.15.0</span>
</div>
<ul>
<li>input <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></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/TypedArray" class="type">&#x3C;TypedArray></a> The input to validate.</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 returns <code>true</code> if <code>input</code> contains only valid ASCII-encoded data,
including the case in which <code>input</code> is empty.</p>
<p>Throws if the <code>input</code> is a detached array buffer.</p>
<h4><code>buffer.isUtf8(input)</code><span><a class="mark" href="#all_buffer_bufferisutf8input" id="all_buffer_bufferisutf8input">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buffer_isutf8_input"></a></h4>
<div class="api_metadata">
<span>Added in: v19.4.0, v18.14.0</span>
</div>
<ul>
<li>input <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></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/TypedArray" class="type">&#x3C;TypedArray></a> The input to validate.</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 returns <code>true</code> if <code>input</code> contains only valid UTF-8-encoded data,
including the case in which <code>input</code> is empty.</p>
<p>Throws if the <code>input</code> is a detached array buffer.</p>
<h4><code>buffer.INSPECT_MAX_BYTES</code><span><a class="mark" href="#all_buffer_bufferinspect_max_bytes" id="all_buffer_bufferinspect_max_bytes">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buffer_inspect_max_bytes"></a></h4>
<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="#all_util_utilinspectobject-options"><code>util.inspect()</code></a> for more details on <code>buf.inspect()</code> behavior.</p>
<h4><code>buffer.kMaxLength</code><span><a class="mark" href="#all_buffer_bufferkmaxlength" id="all_buffer_bufferkmaxlength">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buffer_kmaxlength"></a></h4>
<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="#all_buffer_bufferconstantsmax_length"><code>buffer.constants.MAX_LENGTH</code></a>.</p>
<h4><code>buffer.kStringMaxLength</code><span><a class="mark" href="#all_buffer_bufferkstringmaxlength" id="all_buffer_bufferkstringmaxlength">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buffer_kstringmaxlength"></a></h4>
<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 length allowed for a single <code>string</code> instance.</li>
</ul>
<p>An alias for <a href="#all_buffer_bufferconstantsmax_string_length"><code>buffer.constants.MAX_STRING_LENGTH</code></a>.</p>
<h4><code>buffer.resolveObjectURL(id)</code><span><a class="mark" href="#all_buffer_bufferresolveobjecturlid" id="all_buffer_bufferresolveobjecturlid">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buffer_resolveobjecturl_id"></a></h4>
<div class="api_metadata">
<span>Added in: v16.7.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<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 <code>'blob:nodedata:...</code> URL string returned by a prior call to
<code>URL.createObjectURL()</code>.</li>
<li>Returns: <a href="#all_buffer_class-blob" class="type">&#x3C;Blob></a></li>
</ul>
<p>Resolves a <code>'blob:nodedata:...'</code> an associated <a href="#all_buffer_class-blob" class="type">&#x3C;Blob></a> object registered using
a prior call to <code>URL.createObjectURL()</code>.</p>
<h4><code>buffer.transcode(source, fromEnc, toEnc)</code><span><a class="mark" href="#all_buffer_buffertranscodesource-fromenc-toenc" id="all_buffer_buffertranscodesource-fromenc-toenc">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buffer_transcode_source_fromenc_toenc"></a></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>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="#all_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="#all_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 class="with-53-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span>, transcode } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> newBuf = <span class="hljs-title function_">transcode</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'€'</span>), <span class="hljs-string">'utf8'</span>, <span class="hljs-string">'ascii'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(newBuf.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'ascii'</span>));
<span class="hljs-comment">// Prints: '?'</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span>, transcode } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> newBuf = <span class="hljs-title function_">transcode</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'€'</span>), <span class="hljs-string">'utf8'</span>, <span class="hljs-string">'ascii'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(newBuf.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'ascii'</span>));
<span class="hljs-comment">// Prints: '?'</span></code><button class="copy-button">copy</button></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>
<h4>Class: <code>SlowBuffer</code><span><a class="mark" href="#all_buffer_class-slowbuffer" id="all_buffer_class-slowbuffer">#</a></span><a aria-hidden="true" class="legacy" id="buffer_class_slowbuffer"></a></h4>
<div class="api_metadata">
<span>Deprecated since: v6.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_buffer_static-method-bufferallocunsafeslowsize"><code>Buffer.allocUnsafeSlow()</code></a> instead.</div><p></p>
<p>See <a href="#all_buffer_static-method-bufferallocunsafeslowsize"><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>
<h5><code>new SlowBuffer(size)</code><span><a class="mark" href="#all_buffer_new-slowbuffersize" id="all_buffer_new-slowbuffersize">#</a></span><a aria-hidden="true" class="legacy" id="buffer_new_slowbuffer_size"></a></h5>
<div class="api_metadata">
<span>Deprecated since: v6.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_buffer_static-method-bufferallocunsafeslowsize"><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="#all_buffer_static-method-bufferallocunsafeslowsize"><code>Buffer.allocUnsafeSlow()</code></a>.</p>
<h4>Buffer constants<span><a class="mark" href="#all_buffer_buffer-constants" id="all_buffer_buffer-constants">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buffer_constants"></a></h4>
<div class="api_metadata">
<span>Added in: v8.2.0</span>
</div>
<h5><code>buffer.constants.MAX_LENGTH</code><span><a class="mark" href="#all_buffer_bufferconstantsmax_length" id="all_buffer_bufferconstantsmax_length">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buffer_constants_max_length"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>Value is changed to 2<sup>32</sup> on 64-bit architectures.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>Value is changed from 2<sup>31</sup> - 1 to 2<sup>32</sup> - 1 on 64-bit architectures.</p></td></tr>
<tr><td>v8.2.0</td>
<td><p><span>Added in: v8.2.0</span></p></td></tr>
</tbody></table>
</details>
</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 2<sup>30</sup> - 1 (about 1
GiB).</p>
<p>On 64-bit architectures, this value currently is 2<sup>32</sup> (about 4 GiB).</p>
<p>It reflects <a href="https://v8.github.io/api/head/classv8_1_1TypedArray.html#a54a48f4373da0850663c4393d843b9b0"><code>v8::TypedArray::kMaxLength</code></a> under the hood.</p>
<p>This value is also available as <a href="#all_buffer_bufferkmaxlength"><code>buffer.kMaxLength</code></a>.</p>
<h5><code>buffer.constants.MAX_STRING_LENGTH</code><span><a class="mark" href="#all_buffer_bufferconstantsmax_string_length" id="all_buffer_bufferconstantsmax_string_length">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buffer_constants_max_string_length"></a></h5>
<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>
</section><section><h3><code>Buffer.from()</code>, <code>Buffer.alloc()</code>, and <code>Buffer.allocUnsafe()</code><span><a class="mark" href="#all_buffer_bufferfrom-bufferalloc-and-bufferallocunsafe" id="all_buffer_bufferfrom-bufferalloc-and-bufferallocunsafe">#</a></span><a aria-hidden="true" class="legacy" id="buffer_buffer_from_buffer_alloc_and_buffer_allocunsafe"></a></h3>
<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="#all_buffer_buffillvalue-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="#all_buffer_static-method-bufferallocsize-fill-encoding"><code>Buffer.alloc()</code></a>, and
<a href="#all_buffer_static-method-bufferallocunsafesize"><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="#all_buffer_static-method-bufferfromarray"><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="#all_buffer_static-method-bufferfromarraybuffer-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="#all_buffer_static-method-bufferfrombuffer"><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="#all_buffer_static-method-bufferfromstring-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="#all_buffer_static-method-bufferallocsize-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="#all_buffer_static-method-bufferallocunsafesize"><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="#all_buffer_static-method-bufferallocunsafesize"><code>Buffer.allocUnsafe(size)</code></a> and
<a href="#all_buffer_static-method-bufferallocunsafeslowsize"><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="#all_buffer_static-method-bufferallocunsafesize"><code>Buffer.allocUnsafe()</code></a>, <a href="#all_buffer_static-method-bufferfromstring-encoding"><code>Buffer.from(string)</code></a>,
<a href="#all_buffer_static-method-bufferconcatlist-totallength"><code>Buffer.concat()</code></a> and <a href="#all_buffer_static-method-bufferfromarray"><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="#all_buffer_class-property-bufferpoolsize"><code>Buffer.poolSize</code></a>.
Instances returned by <a href="#all_buffer_static-method-bufferallocunsafeslowsize"><code>Buffer.allocUnsafeSlow()</code></a> <em>never</em> use the shared internal
memory pool.</p>
<h4>The <code>--zero-fill-buffers</code> command-line option<span><a class="mark" href="#all_buffer_the---zero-fill-buffers-command-line-option" id="all_buffer_the---zero-fill-buffers-command-line-option">#</a></span><a aria-hidden="true" class="legacy" id="buffer_the_zero_fill_buffers_command_line_option"></a></h4>
<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="#all_buffer_static-method-bufferallocunsafesize"><code>Buffer.allocUnsafe()</code></a>,
<a href="#all_buffer_static-method-bufferallocunsafeslowsize"><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"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node --zero-fill-buffers</span>
<span class="hljs-meta prompt_">> </span><span class="language-bash">Buffer.allocUnsafe(5);</span>
&#x3C;Buffer 00 00 00 00 00></code> <button class="copy-button">copy</button></pre>
<h4>What makes <code>Buffer.allocUnsafe()</code> and <code>Buffer.allocUnsafeSlow()</code> "unsafe"?<span><a class="mark" href="#all_buffer_what-makes-bufferallocunsafe-and-bufferallocunsafeslow-unsafe" id="all_buffer_what-makes-bufferallocunsafe-and-bufferallocunsafeslow-unsafe">#</a></span><a aria-hidden="true" class="legacy" id="buffer_what_makes_buffer_allocunsafe_and_buffer_allocunsafeslow_unsafe"></a></h4>
<p>When calling <a href="#all_buffer_static-method-bufferallocunsafesize"><code>Buffer.allocUnsafe()</code></a> and <a href="#all_buffer_static-method-bufferallocunsafeslowsize"><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="#all_buffer_static-method-bufferallocunsafesize"><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="#all_buffer_static-method-bufferallocunsafesize"><code>Buffer.allocUnsafe()</code></a>, extra care <em>must</em> be taken in order to avoid
introducing security vulnerabilities into an application.</p></section>
        </section>
<section><h2>C++ addons<span><a class="mark" href="#all_addons_c-addons" id="all_addons_c-addons">#</a></span><a aria-hidden="true" class="legacy" id="addons_c_addons"></a></h2>


<p><em>Addons</em> are dynamically-linked shared objects written in C++. The
<a href="#all_modules_requireid"><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: Node-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 Node-API, use Node-API.
Refer to <a href="n-api.html">C/C++ addons with Node-API</a> for more information on
Node-API.</p>
<p>When not using Node-API, implementing addons is complicated,
involving knowledge of several components and APIs:</p>
<ul>
<li>
<p><a href="https://v8.dev/">V8</a>: 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 file system, sockets, timers, and system events. libuv
also provides a threading abstraction similar to POSIX threads for
more sophisticated asynchronous addons that need to move beyond the
standard event loop. Addon authors should
avoid blocking the event loop with I/O or other time-intensive tasks by
offloading work via libuv to non-blocking system operations, worker threads,
or a custom use of libuv 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="#all_addons_linking-to-libraries-included-with-nodejs">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>
<section><h3>Hello world<span><a class="mark" href="#all_addons_hello-world" id="all_addons_hello-world">#</a></span><a aria-hidden="true" class="legacy" id="addons_hello_world"></a></h3>
<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"><span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span>.<span class="hljs-property">hello</span> = <span class="hljs-function">() =></span> <span class="hljs-string">'world'</span>;</code> <button class="copy-button">copy</button></pre>
<p>First, create the file <code>hello.cc</code>:</p>
<pre><code class="language-cpp"><span class="hljs-comment">// hello.cc</span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;node.h></span></span>

<span class="hljs-keyword">namespace</span> demo {

<span class="hljs-keyword">using</span> v8::FunctionCallbackInfo;
<span class="hljs-keyword">using</span> v8::Isolate;
<span class="hljs-keyword">using</span> v8::Local;
<span class="hljs-keyword">using</span> v8::Object;
<span class="hljs-keyword">using</span> v8::String;
<span class="hljs-keyword">using</span> v8::Value;

<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">Method</span><span class="hljs-params">(<span class="hljs-type">const</span> FunctionCallbackInfo&#x3C;Value>&#x26; args)</span> </span>{
  Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>();
  args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(String::<span class="hljs-built_in">NewFromUtf8</span>(
      isolate, <span class="hljs-string">"world"</span>).<span class="hljs-built_in">ToLocalChecked</span>());
}

<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">Initialize</span><span class="hljs-params">(Local&#x3C;Object> exports)</span> </span>{
  <span class="hljs-built_in">NODE_SET_METHOD</span>(exports, <span class="hljs-string">"hello"</span>, Method);
}

<span class="hljs-built_in">NODE_MODULE</span>(NODE_GYP_MODULE_NAME, Initialize)

}  <span class="hljs-comment">// namespace demo</span></code> <button class="copy-button">copy</button></pre>
<p>All Node.js addons must export an initialization function following
the pattern:</p>
<pre><code class="language-cpp"><span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">Initialize</span><span class="hljs-params">(Local&#x3C;Object> exports)</span></span>;
<span class="hljs-built_in">NODE_MODULE</span>(NODE_GYP_MODULE_NAME, Initialize)</code> <button class="copy-button">copy</button></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>
<p>Addons defined with <code>NODE_MODULE()</code> can not be loaded in multiple contexts or
multiple threads at the same time.</p>
<h4>Context-aware addons<span><a class="mark" href="#all_addons_context-aware-addons" id="all_addons_context-aware-addons">#</a></span><a aria-hidden="true" class="legacy" id="addons_context_aware_addons"></a></h4>
<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>. This means that the addon
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"><span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> v8;

<span class="hljs-keyword">extern</span> <span class="hljs-string">"C"</span> <span class="hljs-function">NODE_MODULE_EXPORT <span class="hljs-type">void</span>
<span class="hljs-title">NODE_MODULE_INITIALIZER</span><span class="hljs-params">(Local&#x3C;Object> exports,
                        Local&#x3C;Value> <span class="hljs-keyword">module</span>,
                        Local&#x3C;Context> context)</span> </span>{
  <span class="hljs-comment">/* Perform addon initialization steps here. */</span>
}</code> <button class="copy-button">copy</button></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>Define a class which will hold per-addon-instance data and which has a static
member of the form
<pre><code class="language-cpp"><span class="hljs-function"><span class="hljs-type">static</span> <span class="hljs-type">void</span> <span class="hljs-title">DeleteInstance</span><span class="hljs-params">(<span class="hljs-type">void</span>* data)</span> </span>{
  <span class="hljs-comment">// Cast `data` to an instance of the class and delete it.</span>
}</code> <button class="copy-button">copy</button></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"><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;node.h></span></span>

<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> v8;

<span class="hljs-keyword">class</span> <span class="hljs-title class_">AddonData</span> {
 <span class="hljs-keyword">public</span>:
  <span class="hljs-function"><span class="hljs-keyword">explicit</span> <span class="hljs-title">AddonData</span><span class="hljs-params">(Isolate* isolate)</span>:
      call_count(<span class="hljs-number">0</span>) {</span>
    <span class="hljs-comment">// Ensure this per-addon-instance data is deleted at environment cleanup.</span>
    node::<span class="hljs-built_in">AddEnvironmentCleanupHook</span>(isolate, DeleteInstance, <span class="hljs-keyword">this</span>);
  }

  <span class="hljs-comment">// Per-addon data.</span>
  <span class="hljs-type">int</span> call_count;

  <span class="hljs-function"><span class="hljs-type">static</span> <span class="hljs-type">void</span> <span class="hljs-title">DeleteInstance</span><span class="hljs-params">(<span class="hljs-type">void</span>* data)</span> </span>{
    <span class="hljs-keyword">delete</span> <span class="hljs-built_in">static_cast</span>&#x3C;AddonData*>(data);
  }
};

<span class="hljs-function"><span class="hljs-type">static</span> <span class="hljs-type">void</span> <span class="hljs-title">Method</span><span class="hljs-params">(<span class="hljs-type">const</span> v8::FunctionCallbackInfo&#x3C;v8::Value>&#x26; info)</span> </span>{
  <span class="hljs-comment">// Retrieve the per-addon-instance data.</span>
  AddonData* data =
      <span class="hljs-built_in">reinterpret_cast</span>&#x3C;AddonData*>(info.<span class="hljs-built_in">Data</span>().<span class="hljs-built_in">As</span>&#x3C;External>()-><span class="hljs-built_in">Value</span>());
  data->call_count++;
  info.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>((<span class="hljs-type">double</span>)data->call_count);
}

<span class="hljs-comment">// Initialize this addon to be context-aware.</span>
<span class="hljs-built_in">NODE_MODULE_INIT</span>(<span class="hljs-comment">/* exports, module, context */</span>) {
  Isolate* isolate = context-><span class="hljs-built_in">GetIsolate</span>();

  <span class="hljs-comment">// Create a new instance of `AddonData` for this instance of the addon and</span>
  <span class="hljs-comment">// tie its life cycle to that of the Node.js environment.</span>
  AddonData* data = <span class="hljs-keyword">new</span> <span class="hljs-built_in">AddonData</span>(isolate);

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

  <span class="hljs-comment">// Expose the method `Method` to JavaScript, and make sure it receives the</span>
  <span class="hljs-comment">// per-addon-instance data we created above by passing `external` as the</span>
  <span class="hljs-comment">// third parameter to the `FunctionTemplate` constructor.</span>
  exports-><span class="hljs-built_in">Set</span>(context,
               String::<span class="hljs-built_in">NewFromUtf8</span>(isolate, <span class="hljs-string">"method"</span>).<span class="hljs-built_in">ToLocalChecked</span>(),
               FunctionTemplate::<span class="hljs-built_in">New</span>(isolate, Method, external)
                  -><span class="hljs-built_in">GetFunction</span>(context).<span class="hljs-built_in">ToLocalChecked</span>()).<span class="hljs-built_in">FromJust</span>();
}</code> <button class="copy-button">copy</button></pre>
<h5>Worker support<span><a class="mark" href="#all_addons_worker-support" id="all_addons_worker-support">#</a></span><a aria-hidden="true" class="legacy" id="addons_worker_support"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.8.0, v12.19.0</td>
<td><p>Cleanup hooks may now be asynchronous.</p></td></tr>
</tbody></table>
</details>
</div>
<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 Node-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="#all_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"><span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">AddEnvironmentCleanupHook</span><span class="hljs-params">(v8::Isolate* isolate,
                               <span class="hljs-type">void</span> (*fun)(<span class="hljs-type">void</span>* arg),
                               <span class="hljs-type">void</span>* arg)</span></span>;</code> <button class="copy-button">copy</button></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 before they are run using
<code>RemoveEnvironmentCleanupHook()</code>, which has the same signature. Callbacks are
run in last-in first-out order.</p>
<p>If necessary, there is an additional pair of <code>AddEnvironmentCleanupHook()</code>
and <code>RemoveEnvironmentCleanupHook()</code> overloads, where the cleanup hook takes a
callback function. This can be used for shutting down asynchronous resources,
such as any libuv handles registered by the addon.</p>
<p>The following <code>addon.cc</code> uses <code>AddEnvironmentCleanupHook</code>:</p>
<pre><code class="language-cpp"><span class="hljs-comment">// addon.cc</span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;node.h></span></span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;assert.h></span></span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;stdlib.h></span></span>

<span class="hljs-keyword">using</span> node::AddEnvironmentCleanupHook;
<span class="hljs-keyword">using</span> v8::HandleScope;
<span class="hljs-keyword">using</span> v8::Isolate;
<span class="hljs-keyword">using</span> v8::Local;
<span class="hljs-keyword">using</span> v8::Object;

<span class="hljs-comment">// Note: In a real-world application, do not rely on static/global data.</span>
<span class="hljs-type">static</span> <span class="hljs-type">char</span> cookie[] = <span class="hljs-string">"yum yum"</span>;
<span class="hljs-type">static</span> <span class="hljs-type">int</span> cleanup_cb1_called = <span class="hljs-number">0</span>;
<span class="hljs-type">static</span> <span class="hljs-type">int</span> cleanup_cb2_called = <span class="hljs-number">0</span>;

<span class="hljs-function"><span class="hljs-type">static</span> <span class="hljs-type">void</span> <span class="hljs-title">cleanup_cb1</span><span class="hljs-params">(<span class="hljs-type">void</span>* arg)</span> </span>{
  Isolate* isolate = <span class="hljs-built_in">static_cast</span>&#x3C;Isolate*>(arg);
  <span class="hljs-function">HandleScope <span class="hljs-title">scope</span><span class="hljs-params">(isolate)</span></span>;
  Local&#x3C;Object> obj = Object::<span class="hljs-built_in">New</span>(isolate);
  <span class="hljs-built_in">assert</span>(!obj.<span class="hljs-built_in">IsEmpty</span>());  <span class="hljs-comment">// assert VM is still alive</span>
  <span class="hljs-built_in">assert</span>(obj-><span class="hljs-built_in">IsObject</span>());
  cleanup_cb1_called++;
}

<span class="hljs-function"><span class="hljs-type">static</span> <span class="hljs-type">void</span> <span class="hljs-title">cleanup_cb2</span><span class="hljs-params">(<span class="hljs-type">void</span>* arg)</span> </span>{
  <span class="hljs-built_in">assert</span>(arg == <span class="hljs-built_in">static_cast</span>&#x3C;<span class="hljs-type">void</span>*>(cookie));
  cleanup_cb2_called++;
}

<span class="hljs-function"><span class="hljs-type">static</span> <span class="hljs-type">void</span> <span class="hljs-title">sanity_check</span><span class="hljs-params">(<span class="hljs-type">void</span>*)</span> </span>{
  <span class="hljs-built_in">assert</span>(cleanup_cb1_called == <span class="hljs-number">1</span>);
  <span class="hljs-built_in">assert</span>(cleanup_cb2_called == <span class="hljs-number">1</span>);
}

<span class="hljs-comment">// Initialize this addon to be context-aware.</span>
<span class="hljs-built_in">NODE_MODULE_INIT</span>(<span class="hljs-comment">/* exports, module, context */</span>) {
  Isolate* isolate = context-><span class="hljs-built_in">GetIsolate</span>();

  <span class="hljs-built_in">AddEnvironmentCleanupHook</span>(isolate, sanity_check, <span class="hljs-literal">nullptr</span>);
  <span class="hljs-built_in">AddEnvironmentCleanupHook</span>(isolate, cleanup_cb2, cookie);
  <span class="hljs-built_in">AddEnvironmentCleanupHook</span>(isolate, cleanup_cb1, isolate);
}</code> <button class="copy-button">copy</button></pre>
<p>Test in JavaScript by running:</p>
<pre><code class="language-js"><span class="hljs-comment">// test.js</span>
<span class="hljs-built_in">require</span>(<span class="hljs-string">'./build/Release/addon'</span>);</code> <button class="copy-button">copy</button></pre>
<h4>Building<span><a class="mark" href="#all_addons_building" id="all_addons_building">#</a></span><a aria-hidden="true" class="legacy" id="addons_building"></a></h4>
<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"><span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"targets"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
    <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"target_name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"addon"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"sources"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span> <span class="hljs-string">"hello.cc"</span> <span class="hljs-punctuation">]</span>
    <span class="hljs-punctuation">}</span>
  <span class="hljs-punctuation">]</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></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="#all_modules_requireid"><code>require()</code></a> to the built <code>addon.node</code> module:</p>
<pre><code class="language-js"><span class="hljs-comment">// hello.js</span>
<span class="hljs-keyword">const</span> addon = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./build/Release/addon'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(addon.<span class="hljs-title function_">hello</span>());
<span class="hljs-comment">// Prints: 'world'</span></code> <button class="copy-button">copy</button></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"><span class="hljs-keyword">try</span> {
  <span class="hljs-keyword">return</span> <span class="hljs-built_in">require</span>(<span class="hljs-string">'./build/Release/addon.node'</span>);
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-keyword">return</span> <span class="hljs-built_in">require</span>(<span class="hljs-string">'./build/Debug/addon.node'</span>);
}</code> <button class="copy-button">copy</button></pre>
<h4>Linking to libraries included with Node.js<span><a class="mark" href="#all_addons_linking-to-libraries-included-with-nodejs" id="all_addons_linking-to-libraries-included-with-nodejs">#</a></span><a aria-hidden="true" class="legacy" id="addons_linking_to_libraries_included_with_node_js"></a></h4>
<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>
<h4>Loading addons using <code>require()</code><span><a class="mark" href="#all_addons_loading-addons-using-require" id="all_addons_loading-addons-using-require">#</a></span><a aria-hidden="true" class="legacy" id="addons_loading_addons_using_require"></a></h4>
<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="#all_modules_requireid"><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="#all_modules_requireid"><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="#all_modules_requireid"><code>require('addon')</code></a> will give precedence to the <code>addon.js</code> file
and load it instead.</p>
</section><section><h3>Native abstractions for Node.js<span><a class="mark" href="#all_addons_native-abstractions-for-nodejs" id="all_addons_native-abstractions-for-nodejs">#</a></span><a aria-hidden="true" class="legacy" id="addons_native_abstractions_for_node_js"></a></h3>
<p>Each of the examples illustrated in this document directly use 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/HEAD/examples/">examples</a> for an
illustration of how it can be used.</p>
</section><section><h3>Node-API<span><a class="mark" href="#all_addons_node-api" id="all_addons_node-api">#</a></span><a aria-hidden="true" class="legacy" id="addons_node_api"></a></h3>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p>Node-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 Node-API are used.</p>
<p>Creating and maintaining an addon that benefits from the ABI stability
provided by Node-API carries with it certain
<a href="#all_n-api_implications-of-abi-stability">implementation considerations</a>.</p>
<p>To use Node-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"><span class="hljs-comment">// hello.cc using Node-API</span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;node_api.h></span></span>

<span class="hljs-keyword">namespace</span> demo {

<span class="hljs-function">napi_value <span class="hljs-title">Method</span><span class="hljs-params">(napi_env env, napi_callback_info args)</span> </span>{
  napi_value greeting;
  napi_status status;

  status = <span class="hljs-built_in">napi_create_string_utf8</span>(env, <span class="hljs-string">"world"</span>, NAPI_AUTO_LENGTH, &#x26;greeting);
  <span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">nullptr</span>;
  <span class="hljs-keyword">return</span> greeting;
}

<span class="hljs-function">napi_value <span class="hljs-title">init</span><span class="hljs-params">(napi_env env, napi_value exports)</span> </span>{
  napi_status status;
  napi_value fn;

  status = <span class="hljs-built_in">napi_create_function</span>(env, <span class="hljs-literal">nullptr</span>, <span class="hljs-number">0</span>, Method, <span class="hljs-literal">nullptr</span>, &#x26;fn);
  <span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">nullptr</span>;

  status = <span class="hljs-built_in">napi_set_named_property</span>(env, exports, <span class="hljs-string">"hello"</span>, fn);
  <span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">nullptr</span>;
  <span class="hljs-keyword">return</span> exports;
}

<span class="hljs-built_in">NAPI_MODULE</span>(NODE_GYP_MODULE_NAME, init)

}  <span class="hljs-comment">// namespace demo</span></code> <button class="copy-button">copy</button></pre>
<p>The functions available and how to use them are documented in
<a href="n-api.html">C/C++ addons with Node-API</a>.</p>
</section><section><h3>Addon examples<span><a class="mark" href="#all_addons_addon-examples" id="all_addons_addon-examples">#</a></span><a aria-hidden="true" class="legacy" id="addons_addon_examples"></a></h3>
<p>Following are some example addons intended to help developers get started. The
examples use 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://v8.dev/docs/embed">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"><span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"targets"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
    <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"target_name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"addon"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"sources"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span> <span class="hljs-string">"addon.cc"</span> <span class="hljs-punctuation">]</span>
    <span class="hljs-punctuation">}</span>
  <span class="hljs-punctuation">]</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></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"><span class="hljs-attr">"sources"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span><span class="hljs-string">"addon.cc"</span><span class="hljs-punctuation">,</span> <span class="hljs-string">"myexample.cc"</span><span class="hljs-punctuation">]</span></code> <button class="copy-button">copy</button></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-bash">node-gyp configure build</code> <button class="copy-button">copy</button></pre>
<h4>Function arguments<span><a class="mark" href="#all_addons_function-arguments" id="all_addons_function-arguments">#</a></span><a aria-hidden="true" class="legacy" id="addons_function_arguments"></a></h4>
<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"><span class="hljs-comment">// addon.cc</span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;node.h></span></span>

<span class="hljs-keyword">namespace</span> demo {

<span class="hljs-keyword">using</span> v8::Exception;
<span class="hljs-keyword">using</span> v8::FunctionCallbackInfo;
<span class="hljs-keyword">using</span> v8::Isolate;
<span class="hljs-keyword">using</span> v8::Local;
<span class="hljs-keyword">using</span> v8::Number;
<span class="hljs-keyword">using</span> v8::Object;
<span class="hljs-keyword">using</span> v8::String;
<span class="hljs-keyword">using</span> v8::Value;

<span class="hljs-comment">// This is the implementation of the "add" method</span>
<span class="hljs-comment">// Input arguments are passed using the</span>
<span class="hljs-comment">// const FunctionCallbackInfo&#x3C;Value>&#x26; args struct</span>
<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">Add</span><span class="hljs-params">(<span class="hljs-type">const</span> FunctionCallbackInfo&#x3C;Value>&#x26; args)</span> </span>{
  Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>();

  <span class="hljs-comment">// Check the number of arguments passed.</span>
  <span class="hljs-keyword">if</span> (args.<span class="hljs-built_in">Length</span>() &#x3C; <span class="hljs-number">2</span>) {
    <span class="hljs-comment">// Throw an Error that is passed back to JavaScript</span>
    isolate-><span class="hljs-built_in">ThrowException</span>(Exception::<span class="hljs-built_in">TypeError</span>(
        String::<span class="hljs-built_in">NewFromUtf8</span>(isolate,
                            <span class="hljs-string">"Wrong number of arguments"</span>).<span class="hljs-built_in">ToLocalChecked</span>()));
    <span class="hljs-keyword">return</span>;
  }

  <span class="hljs-comment">// Check the argument types</span>
  <span class="hljs-keyword">if</span> (!args[<span class="hljs-number">0</span>]-><span class="hljs-built_in">IsNumber</span>() || !args[<span class="hljs-number">1</span>]-><span class="hljs-built_in">IsNumber</span>()) {
    isolate-><span class="hljs-built_in">ThrowException</span>(Exception::<span class="hljs-built_in">TypeError</span>(
        String::<span class="hljs-built_in">NewFromUtf8</span>(isolate,
                            <span class="hljs-string">"Wrong arguments"</span>).<span class="hljs-built_in">ToLocalChecked</span>()));
    <span class="hljs-keyword">return</span>;
  }

  <span class="hljs-comment">// Perform the operation</span>
  <span class="hljs-type">double</span> value =
      args[<span class="hljs-number">0</span>].<span class="hljs-built_in">As</span>&#x3C;Number>()-><span class="hljs-built_in">Value</span>() + args[<span class="hljs-number">1</span>].<span class="hljs-built_in">As</span>&#x3C;Number>()-><span class="hljs-built_in">Value</span>();
  Local&#x3C;Number> num = Number::<span class="hljs-built_in">New</span>(isolate, value);

  <span class="hljs-comment">// Set the return value (using the passed in</span>
  <span class="hljs-comment">// FunctionCallbackInfo&#x3C;Value>&#x26;)</span>
  args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(num);
}

<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">Init</span><span class="hljs-params">(Local&#x3C;Object> exports)</span> </span>{
  <span class="hljs-built_in">NODE_SET_METHOD</span>(exports, <span class="hljs-string">"add"</span>, Add);
}

<span class="hljs-built_in">NODE_MODULE</span>(NODE_GYP_MODULE_NAME, Init)

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

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'This should be eight:'</span>, addon.<span class="hljs-title function_">add</span>(<span class="hljs-number">3</span>, <span class="hljs-number">5</span>));</code> <button class="copy-button">copy</button></pre>
<h4>Callbacks<span><a class="mark" href="#all_addons_callbacks" id="all_addons_callbacks">#</a></span><a aria-hidden="true" class="legacy" id="addons_callbacks"></a></h4>
<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"><span class="hljs-comment">// addon.cc</span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;node.h></span></span>

<span class="hljs-keyword">namespace</span> demo {

<span class="hljs-keyword">using</span> v8::Context;
<span class="hljs-keyword">using</span> v8::Function;
<span class="hljs-keyword">using</span> v8::FunctionCallbackInfo;
<span class="hljs-keyword">using</span> v8::Isolate;
<span class="hljs-keyword">using</span> v8::Local;
<span class="hljs-keyword">using</span> v8::Null;
<span class="hljs-keyword">using</span> v8::Object;
<span class="hljs-keyword">using</span> v8::String;
<span class="hljs-keyword">using</span> v8::Value;

<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">RunCallback</span><span class="hljs-params">(<span class="hljs-type">const</span> FunctionCallbackInfo&#x3C;Value>&#x26; args)</span> </span>{
  Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>();
  Local&#x3C;Context> context = isolate-><span class="hljs-built_in">GetCurrentContext</span>();
  Local&#x3C;Function> cb = Local&#x3C;Function>::<span class="hljs-built_in">Cast</span>(args[<span class="hljs-number">0</span>]);
  <span class="hljs-type">const</span> <span class="hljs-type">unsigned</span> argc = <span class="hljs-number">1</span>;
  Local&#x3C;Value> argv[argc] = {
      String::<span class="hljs-built_in">NewFromUtf8</span>(isolate,
                          <span class="hljs-string">"hello world"</span>).<span class="hljs-built_in">ToLocalChecked</span>() };
  cb-><span class="hljs-built_in">Call</span>(context, <span class="hljs-built_in">Null</span>(isolate), argc, argv).<span class="hljs-built_in">ToLocalChecked</span>();
}

<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">Init</span><span class="hljs-params">(Local&#x3C;Object> exports, Local&#x3C;Object> <span class="hljs-keyword">module</span>)</span> </span>{
  <span class="hljs-built_in">NODE_SET_METHOD</span>(<span class="hljs-keyword">module</span>, <span class="hljs-string">"exports"</span>, RunCallback);
}

<span class="hljs-built_in">NODE_MODULE</span>(NODE_GYP_MODULE_NAME, Init)

}  <span class="hljs-comment">// namespace demo</span></code> <button class="copy-button">copy</button></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"><span class="hljs-comment">// test.js</span>
<span class="hljs-keyword">const</span> addon = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./build/Release/addon'</span>);

<span class="hljs-title function_">addon</span>(<span class="hljs-function">(<span class="hljs-params">msg</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(msg);
<span class="hljs-comment">// Prints: 'hello world'</span>
});</code> <button class="copy-button">copy</button></pre>
<p>In this example, the callback function is invoked synchronously.</p>
<h4>Object factory<span><a class="mark" href="#all_addons_object-factory" id="all_addons_object-factory">#</a></span><a aria-hidden="true" class="legacy" id="addons_object_factory"></a></h4>
<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"><span class="hljs-comment">// addon.cc</span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;node.h></span></span>

<span class="hljs-keyword">namespace</span> demo {

<span class="hljs-keyword">using</span> v8::Context;
<span class="hljs-keyword">using</span> v8::FunctionCallbackInfo;
<span class="hljs-keyword">using</span> v8::Isolate;
<span class="hljs-keyword">using</span> v8::Local;
<span class="hljs-keyword">using</span> v8::Object;
<span class="hljs-keyword">using</span> v8::String;
<span class="hljs-keyword">using</span> v8::Value;

<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">CreateObject</span><span class="hljs-params">(<span class="hljs-type">const</span> FunctionCallbackInfo&#x3C;Value>&#x26; args)</span> </span>{
  Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>();
  Local&#x3C;Context> context = isolate-><span class="hljs-built_in">GetCurrentContext</span>();

  Local&#x3C;Object> obj = Object::<span class="hljs-built_in">New</span>(isolate);
  obj-><span class="hljs-built_in">Set</span>(context,
           String::<span class="hljs-built_in">NewFromUtf8</span>(isolate,
                               <span class="hljs-string">"msg"</span>).<span class="hljs-built_in">ToLocalChecked</span>(),
                               args[<span class="hljs-number">0</span>]-><span class="hljs-built_in">ToString</span>(context).<span class="hljs-built_in">ToLocalChecked</span>())
           .<span class="hljs-built_in">FromJust</span>();

  args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(obj);
}

<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">Init</span><span class="hljs-params">(Local&#x3C;Object> exports, Local&#x3C;Object> <span class="hljs-keyword">module</span>)</span> </span>{
  <span class="hljs-built_in">NODE_SET_METHOD</span>(<span class="hljs-keyword">module</span>, <span class="hljs-string">"exports"</span>, CreateObject);
}

<span class="hljs-built_in">NODE_MODULE</span>(NODE_GYP_MODULE_NAME, Init)

}  <span class="hljs-comment">// namespace demo</span></code> <button class="copy-button">copy</button></pre>
<p>To test it in JavaScript:</p>
<pre><code class="language-js"><span class="hljs-comment">// test.js</span>
<span class="hljs-keyword">const</span> addon = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./build/Release/addon'</span>);

<span class="hljs-keyword">const</span> obj1 = <span class="hljs-title function_">addon</span>(<span class="hljs-string">'hello'</span>);
<span class="hljs-keyword">const</span> obj2 = <span class="hljs-title function_">addon</span>(<span class="hljs-string">'world'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(obj1.<span class="hljs-property">msg</span>, obj2.<span class="hljs-property">msg</span>);
<span class="hljs-comment">// Prints: 'hello world'</span></code> <button class="copy-button">copy</button></pre>
<h4>Function factory<span><a class="mark" href="#all_addons_function-factory" id="all_addons_function-factory">#</a></span><a aria-hidden="true" class="legacy" id="addons_function_factory"></a></h4>
<p>Another common scenario is creating JavaScript functions that wrap C++
functions and returning those back to JavaScript:</p>
<pre><code class="language-cpp"><span class="hljs-comment">// addon.cc</span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;node.h></span></span>

<span class="hljs-keyword">namespace</span> demo {

<span class="hljs-keyword">using</span> v8::Context;
<span class="hljs-keyword">using</span> v8::Function;
<span class="hljs-keyword">using</span> v8::FunctionCallbackInfo;
<span class="hljs-keyword">using</span> v8::FunctionTemplate;
<span class="hljs-keyword">using</span> v8::Isolate;
<span class="hljs-keyword">using</span> v8::Local;
<span class="hljs-keyword">using</span> v8::Object;
<span class="hljs-keyword">using</span> v8::String;
<span class="hljs-keyword">using</span> v8::Value;

<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">MyFunction</span><span class="hljs-params">(<span class="hljs-type">const</span> FunctionCallbackInfo&#x3C;Value>&#x26; args)</span> </span>{
  Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>();
  args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(String::<span class="hljs-built_in">NewFromUtf8</span>(
      isolate, <span class="hljs-string">"hello world"</span>).<span class="hljs-built_in">ToLocalChecked</span>());
}

<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">CreateFunction</span><span class="hljs-params">(<span class="hljs-type">const</span> FunctionCallbackInfo&#x3C;Value>&#x26; args)</span> </span>{
  Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>();

  Local&#x3C;Context> context = isolate-><span class="hljs-built_in">GetCurrentContext</span>();
  Local&#x3C;FunctionTemplate> tpl = FunctionTemplate::<span class="hljs-built_in">New</span>(isolate, MyFunction);
  Local&#x3C;Function> fn = tpl-><span class="hljs-built_in">GetFunction</span>(context).<span class="hljs-built_in">ToLocalChecked</span>();

  <span class="hljs-comment">// omit this to make it anonymous</span>
  fn-><span class="hljs-built_in">SetName</span>(String::<span class="hljs-built_in">NewFromUtf8</span>(
      isolate, <span class="hljs-string">"theFunction"</span>).<span class="hljs-built_in">ToLocalChecked</span>());

  args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(fn);
}

<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">Init</span><span class="hljs-params">(Local&#x3C;Object> exports, Local&#x3C;Object> <span class="hljs-keyword">module</span>)</span> </span>{
  <span class="hljs-built_in">NODE_SET_METHOD</span>(<span class="hljs-keyword">module</span>, <span class="hljs-string">"exports"</span>, CreateFunction);
}

<span class="hljs-built_in">NODE_MODULE</span>(NODE_GYP_MODULE_NAME, Init)

}  <span class="hljs-comment">// namespace demo</span></code> <button class="copy-button">copy</button></pre>
<p>To test:</p>
<pre><code class="language-js"><span class="hljs-comment">// test.js</span>
<span class="hljs-keyword">const</span> addon = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./build/Release/addon'</span>);

<span class="hljs-keyword">const</span> fn = <span class="hljs-title function_">addon</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">fn</span>());
<span class="hljs-comment">// Prints: 'hello world'</span></code> <button class="copy-button">copy</button></pre>
<h4>Wrapping C++ objects<span><a class="mark" href="#all_addons_wrapping-c-objects" id="all_addons_wrapping-c-objects">#</a></span><a aria-hidden="true" class="legacy" id="addons_wrapping_c_objects"></a></h4>
<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"><span class="hljs-comment">// addon.cc</span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;node.h></span></span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">"myobject.h"</span></span>

<span class="hljs-keyword">namespace</span> demo {

<span class="hljs-keyword">using</span> v8::Local;
<span class="hljs-keyword">using</span> v8::Object;

<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">InitAll</span><span class="hljs-params">(Local&#x3C;Object> exports)</span> </span>{
  MyObject::<span class="hljs-built_in">Init</span>(exports);
}

<span class="hljs-built_in">NODE_MODULE</span>(NODE_GYP_MODULE_NAME, InitAll)

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

<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;node.h></span></span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;node_object_wrap.h></span></span>

<span class="hljs-keyword">namespace</span> demo {

<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyObject</span> : <span class="hljs-keyword">public</span> node::ObjectWrap {
 <span class="hljs-keyword">public</span>:
  <span class="hljs-function"><span class="hljs-type">static</span> <span class="hljs-type">void</span> <span class="hljs-title">Init</span><span class="hljs-params">(v8::Local&#x3C;v8::Object> exports)</span></span>;

 <span class="hljs-keyword">private</span>:
  <span class="hljs-function"><span class="hljs-keyword">explicit</span> <span class="hljs-title">MyObject</span><span class="hljs-params">(<span class="hljs-type">double</span> value = <span class="hljs-number">0</span>)</span></span>;
  ~<span class="hljs-built_in">MyObject</span>();

  <span class="hljs-function"><span class="hljs-type">static</span> <span class="hljs-type">void</span> <span class="hljs-title">New</span><span class="hljs-params">(<span class="hljs-type">const</span> v8::FunctionCallbackInfo&#x3C;v8::Value>&#x26; args)</span></span>;
  <span class="hljs-function"><span class="hljs-type">static</span> <span class="hljs-type">void</span> <span class="hljs-title">PlusOne</span><span class="hljs-params">(<span class="hljs-type">const</span> v8::FunctionCallbackInfo&#x3C;v8::Value>&#x26; args)</span></span>;

  <span class="hljs-type">double</span> value_;
};

}  <span class="hljs-comment">// namespace demo</span>

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

<span class="hljs-keyword">namespace</span> demo {

<span class="hljs-keyword">using</span> v8::Context;
<span class="hljs-keyword">using</span> v8::Function;
<span class="hljs-keyword">using</span> v8::FunctionCallbackInfo;
<span class="hljs-keyword">using</span> v8::FunctionTemplate;
<span class="hljs-keyword">using</span> v8::Isolate;
<span class="hljs-keyword">using</span> v8::Local;
<span class="hljs-keyword">using</span> v8::Number;
<span class="hljs-keyword">using</span> v8::Object;
<span class="hljs-keyword">using</span> v8::ObjectTemplate;
<span class="hljs-keyword">using</span> v8::String;
<span class="hljs-keyword">using</span> v8::Value;

MyObject::<span class="hljs-built_in">MyObject</span>(<span class="hljs-type">double</span> value) : <span class="hljs-built_in">value_</span>(value) {
}

MyObject::~<span class="hljs-built_in">MyObject</span>() {
}

<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">MyObject::Init</span><span class="hljs-params">(Local&#x3C;Object> exports)</span> </span>{
  Isolate* isolate = exports-><span class="hljs-built_in">GetIsolate</span>();
  Local&#x3C;Context> context = isolate-><span class="hljs-built_in">GetCurrentContext</span>();

  Local&#x3C;ObjectTemplate> addon_data_tpl = ObjectTemplate::<span class="hljs-built_in">New</span>(isolate);
  addon_data_tpl-><span class="hljs-built_in">SetInternalFieldCount</span>(<span class="hljs-number">1</span>);  <span class="hljs-comment">// 1 field for the MyObject::New()</span>
  Local&#x3C;Object> addon_data =
      addon_data_tpl-><span class="hljs-built_in">NewInstance</span>(context).<span class="hljs-built_in">ToLocalChecked</span>();

  <span class="hljs-comment">// Prepare constructor template</span>
  Local&#x3C;FunctionTemplate> tpl = FunctionTemplate::<span class="hljs-built_in">New</span>(isolate, New, addon_data);
  tpl-><span class="hljs-built_in">SetClassName</span>(String::<span class="hljs-built_in">NewFromUtf8</span>(isolate, <span class="hljs-string">"MyObject"</span>).<span class="hljs-built_in">ToLocalChecked</span>());
  tpl-><span class="hljs-built_in">InstanceTemplate</span>()-><span class="hljs-built_in">SetInternalFieldCount</span>(<span class="hljs-number">1</span>);

  <span class="hljs-comment">// Prototype</span>
  <span class="hljs-built_in">NODE_SET_PROTOTYPE_METHOD</span>(tpl, <span class="hljs-string">"plusOne"</span>, PlusOne);

  Local&#x3C;Function> constructor = tpl-><span class="hljs-built_in">GetFunction</span>(context).<span class="hljs-built_in">ToLocalChecked</span>();
  addon_data-><span class="hljs-built_in">SetInternalField</span>(<span class="hljs-number">0</span>, constructor);
  exports-><span class="hljs-built_in">Set</span>(context, String::<span class="hljs-built_in">NewFromUtf8</span>(
      isolate, <span class="hljs-string">"MyObject"</span>).<span class="hljs-built_in">ToLocalChecked</span>(),
      constructor).<span class="hljs-built_in">FromJust</span>();
}

<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">MyObject::New</span><span class="hljs-params">(<span class="hljs-type">const</span> FunctionCallbackInfo&#x3C;Value>&#x26; args)</span> </span>{
  Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>();
  Local&#x3C;Context> context = isolate-><span class="hljs-built_in">GetCurrentContext</span>();

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

<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">MyObject::PlusOne</span><span class="hljs-params">(<span class="hljs-type">const</span> FunctionCallbackInfo&#x3C;Value>&#x26; args)</span> </span>{
  Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>();

  MyObject* obj = ObjectWrap::<span class="hljs-built_in">Unwrap</span>&#x3C;MyObject>(args.<span class="hljs-built_in">This</span>());
  obj->value_ += <span class="hljs-number">1</span>;

  args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(Number::<span class="hljs-built_in">New</span>(isolate, obj->value_));
}

}  <span class="hljs-comment">// namespace demo</span></code> <button class="copy-button">copy</button></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"><span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"targets"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
    <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"target_name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"addon"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"sources"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
        <span class="hljs-string">"addon.cc"</span><span class="hljs-punctuation">,</span>
        <span class="hljs-string">"myobject.cc"</span>
      <span class="hljs-punctuation">]</span>
    <span class="hljs-punctuation">}</span>
  <span class="hljs-punctuation">]</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>Test it with:</p>
<pre><code class="language-js"><span class="hljs-comment">// test.js</span>
<span class="hljs-keyword">const</span> addon = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./build/Release/addon'</span>);

<span class="hljs-keyword">const</span> obj = <span class="hljs-keyword">new</span> addon.<span class="hljs-title class_">MyObject</span>(<span class="hljs-number">10</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(obj.<span class="hljs-title function_">plusOne</span>());
<span class="hljs-comment">// Prints: 11</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(obj.<span class="hljs-title function_">plusOne</span>());
<span class="hljs-comment">// Prints: 12</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(obj.<span class="hljs-title function_">plusOne</span>());
<span class="hljs-comment">// Prints: 13</span></code> <button class="copy-button">copy</button></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>
<p>During shutdown of the process or worker threads destructors are not called
by the JS engine. Therefore it's the responsibility of the user to track
these objects and ensure proper destruction to avoid resource leaks.</p>
<h4>Factory of wrapped objects<span><a class="mark" href="#all_addons_factory-of-wrapped-objects" id="all_addons_factory-of-wrapped-objects">#</a></span><a aria-hidden="true" class="legacy" id="addons_factory_of_wrapped_objects"></a></h4>
<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"><span class="hljs-keyword">const</span> obj = addon.<span class="hljs-title function_">createObject</span>();
<span class="hljs-comment">// instead of:</span>
<span class="hljs-comment">// const obj = new addon.Object();</span></code> <button class="copy-button">copy</button></pre>
<p>First, the <code>createObject()</code> method is implemented in <code>addon.cc</code>:</p>
<pre><code class="language-cpp"><span class="hljs-comment">// addon.cc</span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;node.h></span></span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">"myobject.h"</span></span>

<span class="hljs-keyword">namespace</span> demo {

<span class="hljs-keyword">using</span> v8::FunctionCallbackInfo;
<span class="hljs-keyword">using</span> v8::Isolate;
<span class="hljs-keyword">using</span> v8::Local;
<span class="hljs-keyword">using</span> v8::Object;
<span class="hljs-keyword">using</span> v8::String;
<span class="hljs-keyword">using</span> v8::Value;

<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">CreateObject</span><span class="hljs-params">(<span class="hljs-type">const</span> FunctionCallbackInfo&#x3C;Value>&#x26; args)</span> </span>{
  MyObject::<span class="hljs-built_in">NewInstance</span>(args);
}

<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">InitAll</span><span class="hljs-params">(Local&#x3C;Object> exports, Local&#x3C;Object> <span class="hljs-keyword">module</span>)</span> </span>{
  MyObject::<span class="hljs-built_in">Init</span>(exports-><span class="hljs-built_in">GetIsolate</span>());

  <span class="hljs-built_in">NODE_SET_METHOD</span>(<span class="hljs-keyword">module</span>, <span class="hljs-string">"exports"</span>, CreateObject);
}

<span class="hljs-built_in">NODE_MODULE</span>(NODE_GYP_MODULE_NAME, InitAll)

}  <span class="hljs-comment">// namespace demo</span></code> <button class="copy-button">copy</button></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"><span class="hljs-comment">// myobject.h</span>
<span class="hljs-meta">#<span class="hljs-keyword">ifndef</span> MYOBJECT_H</span>
<span class="hljs-meta">#<span class="hljs-keyword">define</span> MYOBJECT_H</span>

<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;node.h></span></span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;node_object_wrap.h></span></span>

<span class="hljs-keyword">namespace</span> demo {

<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyObject</span> : <span class="hljs-keyword">public</span> node::ObjectWrap {
 <span class="hljs-keyword">public</span>:
  <span class="hljs-function"><span class="hljs-type">static</span> <span class="hljs-type">void</span> <span class="hljs-title">Init</span><span class="hljs-params">(v8::Isolate* isolate)</span></span>;
  <span class="hljs-function"><span class="hljs-type">static</span> <span class="hljs-type">void</span> <span class="hljs-title">NewInstance</span><span class="hljs-params">(<span class="hljs-type">const</span> v8::FunctionCallbackInfo&#x3C;v8::Value>&#x26; args)</span></span>;

 <span class="hljs-keyword">private</span>:
  <span class="hljs-function"><span class="hljs-keyword">explicit</span> <span class="hljs-title">MyObject</span><span class="hljs-params">(<span class="hljs-type">double</span> value = <span class="hljs-number">0</span>)</span></span>;
  ~<span class="hljs-built_in">MyObject</span>();

  <span class="hljs-function"><span class="hljs-type">static</span> <span class="hljs-type">void</span> <span class="hljs-title">New</span><span class="hljs-params">(<span class="hljs-type">const</span> v8::FunctionCallbackInfo&#x3C;v8::Value>&#x26; args)</span></span>;
  <span class="hljs-function"><span class="hljs-type">static</span> <span class="hljs-type">void</span> <span class="hljs-title">PlusOne</span><span class="hljs-params">(<span class="hljs-type">const</span> v8::FunctionCallbackInfo&#x3C;v8::Value>&#x26; args)</span></span>;
  <span class="hljs-type">static</span> v8::Global&#x3C;v8::Function> constructor;
  <span class="hljs-type">double</span> value_;
};

}  <span class="hljs-comment">// namespace demo</span>

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

<span class="hljs-keyword">namespace</span> demo {

<span class="hljs-keyword">using</span> node::AddEnvironmentCleanupHook;
<span class="hljs-keyword">using</span> v8::Context;
<span class="hljs-keyword">using</span> v8::Function;
<span class="hljs-keyword">using</span> v8::FunctionCallbackInfo;
<span class="hljs-keyword">using</span> v8::FunctionTemplate;
<span class="hljs-keyword">using</span> v8::Global;
<span class="hljs-keyword">using</span> v8::Isolate;
<span class="hljs-keyword">using</span> v8::Local;
<span class="hljs-keyword">using</span> v8::Number;
<span class="hljs-keyword">using</span> v8::Object;
<span class="hljs-keyword">using</span> v8::String;
<span class="hljs-keyword">using</span> v8::Value;

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

MyObject::<span class="hljs-built_in">MyObject</span>(<span class="hljs-type">double</span> value) : <span class="hljs-built_in">value_</span>(value) {
}

MyObject::~<span class="hljs-built_in">MyObject</span>() {
}

<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">MyObject::Init</span><span class="hljs-params">(Isolate* isolate)</span> </span>{
  <span class="hljs-comment">// Prepare constructor template</span>
  Local&#x3C;FunctionTemplate> tpl = FunctionTemplate::<span class="hljs-built_in">New</span>(isolate, New);
  tpl-><span class="hljs-built_in">SetClassName</span>(String::<span class="hljs-built_in">NewFromUtf8</span>(isolate, <span class="hljs-string">"MyObject"</span>).<span class="hljs-built_in">ToLocalChecked</span>());
  tpl-><span class="hljs-built_in">InstanceTemplate</span>()-><span class="hljs-built_in">SetInternalFieldCount</span>(<span class="hljs-number">1</span>);

  <span class="hljs-comment">// Prototype</span>
  <span class="hljs-built_in">NODE_SET_PROTOTYPE_METHOD</span>(tpl, <span class="hljs-string">"plusOne"</span>, PlusOne);

  Local&#x3C;Context> context = isolate-><span class="hljs-built_in">GetCurrentContext</span>();
  constructor.<span class="hljs-built_in">Reset</span>(isolate, tpl-><span class="hljs-built_in">GetFunction</span>(context).<span class="hljs-built_in">ToLocalChecked</span>());

  <span class="hljs-built_in">AddEnvironmentCleanupHook</span>(isolate, [](<span class="hljs-type">void</span>*) {
    constructor.<span class="hljs-built_in">Reset</span>();
  }, <span class="hljs-literal">nullptr</span>);
}

<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">MyObject::New</span><span class="hljs-params">(<span class="hljs-type">const</span> FunctionCallbackInfo&#x3C;Value>&#x26; args)</span> </span>{
  Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>();
  Local&#x3C;Context> context = isolate-><span class="hljs-built_in">GetCurrentContext</span>();

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

<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">MyObject::NewInstance</span><span class="hljs-params">(<span class="hljs-type">const</span> FunctionCallbackInfo&#x3C;Value>&#x26; args)</span> </span>{
  Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>();

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

  args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(instance);
}

<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">MyObject::PlusOne</span><span class="hljs-params">(<span class="hljs-type">const</span> FunctionCallbackInfo&#x3C;Value>&#x26; args)</span> </span>{
  Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>();

  MyObject* obj = ObjectWrap::<span class="hljs-built_in">Unwrap</span>&#x3C;MyObject>(args.<span class="hljs-built_in">This</span>());
  obj->value_ += <span class="hljs-number">1</span>;

  args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(Number::<span class="hljs-built_in">New</span>(isolate, obj->value_));
}

}  <span class="hljs-comment">// namespace demo</span></code> <button class="copy-button">copy</button></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"><span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"targets"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
    <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"target_name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"addon"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"sources"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
        <span class="hljs-string">"addon.cc"</span><span class="hljs-punctuation">,</span>
        <span class="hljs-string">"myobject.cc"</span>
      <span class="hljs-punctuation">]</span>
    <span class="hljs-punctuation">}</span>
  <span class="hljs-punctuation">]</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>Test it with:</p>
<pre><code class="language-js"><span class="hljs-comment">// test.js</span>
<span class="hljs-keyword">const</span> createObject = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./build/Release/addon'</span>);

<span class="hljs-keyword">const</span> obj = <span class="hljs-title function_">createObject</span>(<span class="hljs-number">10</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(obj.<span class="hljs-title function_">plusOne</span>());
<span class="hljs-comment">// Prints: 11</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(obj.<span class="hljs-title function_">plusOne</span>());
<span class="hljs-comment">// Prints: 12</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(obj.<span class="hljs-title function_">plusOne</span>());
<span class="hljs-comment">// Prints: 13</span>

<span class="hljs-keyword">const</span> obj2 = <span class="hljs-title function_">createObject</span>(<span class="hljs-number">20</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(obj2.<span class="hljs-title function_">plusOne</span>());
<span class="hljs-comment">// Prints: 21</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(obj2.<span class="hljs-title function_">plusOne</span>());
<span class="hljs-comment">// Prints: 22</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(obj2.<span class="hljs-title function_">plusOne</span>());
<span class="hljs-comment">// Prints: 23</span></code> <button class="copy-button">copy</button></pre>
<h4>Passing wrapped objects around<span><a class="mark" href="#all_addons_passing-wrapped-objects-around" id="all_addons_passing-wrapped-objects-around">#</a></span><a aria-hidden="true" class="legacy" id="addons_passing_wrapped_objects_around"></a></h4>
<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"><span class="hljs-comment">// addon.cc</span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;node.h></span></span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;node_object_wrap.h></span></span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">"myobject.h"</span></span>

<span class="hljs-keyword">namespace</span> demo {

<span class="hljs-keyword">using</span> v8::Context;
<span class="hljs-keyword">using</span> v8::FunctionCallbackInfo;
<span class="hljs-keyword">using</span> v8::Isolate;
<span class="hljs-keyword">using</span> v8::Local;
<span class="hljs-keyword">using</span> v8::Number;
<span class="hljs-keyword">using</span> v8::Object;
<span class="hljs-keyword">using</span> v8::String;
<span class="hljs-keyword">using</span> v8::Value;

<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">CreateObject</span><span class="hljs-params">(<span class="hljs-type">const</span> FunctionCallbackInfo&#x3C;Value>&#x26; args)</span> </span>{
  MyObject::<span class="hljs-built_in">NewInstance</span>(args);
}

<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">Add</span><span class="hljs-params">(<span class="hljs-type">const</span> FunctionCallbackInfo&#x3C;Value>&#x26; args)</span> </span>{
  Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>();
  Local&#x3C;Context> context = isolate-><span class="hljs-built_in">GetCurrentContext</span>();

  MyObject* obj1 = node::ObjectWrap::<span class="hljs-built_in">Unwrap</span>&#x3C;MyObject>(
      args[<span class="hljs-number">0</span>]-><span class="hljs-built_in">ToObject</span>(context).<span class="hljs-built_in">ToLocalChecked</span>());
  MyObject* obj2 = node::ObjectWrap::<span class="hljs-built_in">Unwrap</span>&#x3C;MyObject>(
      args[<span class="hljs-number">1</span>]-><span class="hljs-built_in">ToObject</span>(context).<span class="hljs-built_in">ToLocalChecked</span>());

  <span class="hljs-type">double</span> sum = obj1-><span class="hljs-built_in">value</span>() + obj2-><span class="hljs-built_in">value</span>();
  args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(Number::<span class="hljs-built_in">New</span>(isolate, sum));
}

<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">InitAll</span><span class="hljs-params">(Local&#x3C;Object> exports)</span> </span>{
  MyObject::<span class="hljs-built_in">Init</span>(exports-><span class="hljs-built_in">GetIsolate</span>());

  <span class="hljs-built_in">NODE_SET_METHOD</span>(exports, <span class="hljs-string">"createObject"</span>, CreateObject);
  <span class="hljs-built_in">NODE_SET_METHOD</span>(exports, <span class="hljs-string">"add"</span>, Add);
}

<span class="hljs-built_in">NODE_MODULE</span>(NODE_GYP_MODULE_NAME, InitAll)

}  <span class="hljs-comment">// namespace demo</span></code> <button class="copy-button">copy</button></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"><span class="hljs-comment">// myobject.h</span>
<span class="hljs-meta">#<span class="hljs-keyword">ifndef</span> MYOBJECT_H</span>
<span class="hljs-meta">#<span class="hljs-keyword">define</span> MYOBJECT_H</span>

<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;node.h></span></span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;node_object_wrap.h></span></span>

<span class="hljs-keyword">namespace</span> demo {

<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyObject</span> : <span class="hljs-keyword">public</span> node::ObjectWrap {
 <span class="hljs-keyword">public</span>:
  <span class="hljs-function"><span class="hljs-type">static</span> <span class="hljs-type">void</span> <span class="hljs-title">Init</span><span class="hljs-params">(v8::Isolate* isolate)</span></span>;
  <span class="hljs-function"><span class="hljs-type">static</span> <span class="hljs-type">void</span> <span class="hljs-title">NewInstance</span><span class="hljs-params">(<span class="hljs-type">const</span> v8::FunctionCallbackInfo&#x3C;v8::Value>&#x26; args)</span></span>;
  <span class="hljs-function"><span class="hljs-keyword">inline</span> <span class="hljs-type">double</span> <span class="hljs-title">value</span><span class="hljs-params">()</span> <span class="hljs-type">const</span> </span>{ <span class="hljs-keyword">return</span> value_; }

 <span class="hljs-keyword">private</span>:
  <span class="hljs-function"><span class="hljs-keyword">explicit</span> <span class="hljs-title">MyObject</span><span class="hljs-params">(<span class="hljs-type">double</span> value = <span class="hljs-number">0</span>)</span></span>;
  ~<span class="hljs-built_in">MyObject</span>();

  <span class="hljs-function"><span class="hljs-type">static</span> <span class="hljs-type">void</span> <span class="hljs-title">New</span><span class="hljs-params">(<span class="hljs-type">const</span> v8::FunctionCallbackInfo&#x3C;v8::Value>&#x26; args)</span></span>;
  <span class="hljs-type">static</span> v8::Global&#x3C;v8::Function> constructor;
  <span class="hljs-type">double</span> value_;
};

}  <span class="hljs-comment">// namespace demo</span>

<span class="hljs-meta">#<span class="hljs-keyword">endif</span></span></code> <button class="copy-button">copy</button></pre>
<p>The implementation of <code>myobject.cc</code> is similar to before:</p>
<pre><code class="language-cpp"><span class="hljs-comment">// myobject.cc</span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;node.h></span></span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">"myobject.h"</span></span>

<span class="hljs-keyword">namespace</span> demo {

<span class="hljs-keyword">using</span> node::AddEnvironmentCleanupHook;
<span class="hljs-keyword">using</span> v8::Context;
<span class="hljs-keyword">using</span> v8::Function;
<span class="hljs-keyword">using</span> v8::FunctionCallbackInfo;
<span class="hljs-keyword">using</span> v8::FunctionTemplate;
<span class="hljs-keyword">using</span> v8::Global;
<span class="hljs-keyword">using</span> v8::Isolate;
<span class="hljs-keyword">using</span> v8::Local;
<span class="hljs-keyword">using</span> v8::Object;
<span class="hljs-keyword">using</span> v8::String;
<span class="hljs-keyword">using</span> v8::Value;

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

MyObject::<span class="hljs-built_in">MyObject</span>(<span class="hljs-type">double</span> value) : <span class="hljs-built_in">value_</span>(value) {
}

MyObject::~<span class="hljs-built_in">MyObject</span>() {
}

<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">MyObject::Init</span><span class="hljs-params">(Isolate* isolate)</span> </span>{
  <span class="hljs-comment">// Prepare constructor template</span>
  Local&#x3C;FunctionTemplate> tpl = FunctionTemplate::<span class="hljs-built_in">New</span>(isolate, New);
  tpl-><span class="hljs-built_in">SetClassName</span>(String::<span class="hljs-built_in">NewFromUtf8</span>(isolate, <span class="hljs-string">"MyObject"</span>).<span class="hljs-built_in">ToLocalChecked</span>());
  tpl-><span class="hljs-built_in">InstanceTemplate</span>()-><span class="hljs-built_in">SetInternalFieldCount</span>(<span class="hljs-number">1</span>);

  Local&#x3C;Context> context = isolate-><span class="hljs-built_in">GetCurrentContext</span>();
  constructor.<span class="hljs-built_in">Reset</span>(isolate, tpl-><span class="hljs-built_in">GetFunction</span>(context).<span class="hljs-built_in">ToLocalChecked</span>());

  <span class="hljs-built_in">AddEnvironmentCleanupHook</span>(isolate, [](<span class="hljs-type">void</span>*) {
    constructor.<span class="hljs-built_in">Reset</span>();
  }, <span class="hljs-literal">nullptr</span>);
}

<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">MyObject::New</span><span class="hljs-params">(<span class="hljs-type">const</span> FunctionCallbackInfo&#x3C;Value>&#x26; args)</span> </span>{
  Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>();
  Local&#x3C;Context> context = isolate-><span class="hljs-built_in">GetCurrentContext</span>();

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

<span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">MyObject::NewInstance</span><span class="hljs-params">(<span class="hljs-type">const</span> FunctionCallbackInfo&#x3C;Value>&#x26; args)</span> </span>{
  Isolate* isolate = args.<span class="hljs-built_in">GetIsolate</span>();

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

  args.<span class="hljs-built_in">GetReturnValue</span>().<span class="hljs-built_in">Set</span>(instance);
}

}  <span class="hljs-comment">// namespace demo</span></code> <button class="copy-button">copy</button></pre>
<p>Test it with:</p>
<pre><code class="language-js"><span class="hljs-comment">// test.js</span>
<span class="hljs-keyword">const</span> addon = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./build/Release/addon'</span>);

<span class="hljs-keyword">const</span> obj1 = addon.<span class="hljs-title function_">createObject</span>(<span class="hljs-number">10</span>);
<span class="hljs-keyword">const</span> obj2 = addon.<span class="hljs-title function_">createObject</span>(<span class="hljs-number">20</span>);
<span class="hljs-keyword">const</span> result = addon.<span class="hljs-title function_">add</span>(obj1, obj2);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result);
<span class="hljs-comment">// Prints: 30</span></code> <button class="copy-button">copy</button></pre></section>
        </section>
<section><h2>Node-API<span><a class="mark" href="#all_n-api_node-api" id="all_n-api_node-api">#</a></span><a aria-hidden="true" class="legacy" id="n_api_node_api"></a></h2>


<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p>Node-API (formerly N-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 Node-API are used.</p>
<p>APIs exposed by Node-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 Node-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="#all_n-api_error-handling">Error handling</a>.</li>
</ul>
<p>Node-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"><code>node-addon-api</code></a>.
This wrapper provides an inlinable C++ API. Binaries built
with <code>node-addon-api</code> will depend on the symbols for the Node-API C-based
functions exported by Node.js. <code>node-addon-api</code> is a more
efficient way to write code that calls Node-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::<span class="hljs-built_in">New</span>(env);
obj[<span class="hljs-string">"foo"</span>] = String::<span class="hljs-built_in">New</span>(env, <span class="hljs-string">"bar"</span>);</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-cpp">napi_status status;
napi_value object, string;
status = <span class="hljs-built_in">napi_create_object</span>(env, &#x26;object);
<span class="hljs-keyword">if</span> (status != napi_ok) {
  <span class="hljs-built_in">napi_throw_error</span>(env, ...);
  <span class="hljs-keyword">return</span>;
}

status = <span class="hljs-built_in">napi_create_string_utf8</span>(env, <span class="hljs-string">"bar"</span>, NAPI_AUTO_LENGTH, &#x26;string);
<span class="hljs-keyword">if</span> (status != napi_ok) {
  <span class="hljs-built_in">napi_throw_error</span>(env, ...);
  <span class="hljs-keyword">return</span>;
}

status = <span class="hljs-built_in">napi_set_named_property</span>(env, object, <span class="hljs-string">"foo"</span>, string);
<span class="hljs-keyword">if</span> (status != napi_ok) {
  <span class="hljs-built_in">napi_throw_error</span>(env, ...);
  <span class="hljs-keyword">return</span>;
}</code> <button class="copy-button">copy</button></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>
<p>The <a href="https://nodejs.github.io/node-addon-examples/">Node-API Resource</a> offers
an excellent orientation and tips for developers just getting started with
Node-API and <code>node-addon-api</code>. Additional media resources can be found on the
<a href="https://github.com/nodejs/abi-stable-node/blob/HEAD/node-api-media.md">Node-API Media</a> page.</p>
<section><h3>Implications of ABI stability<span><a class="mark" href="#all_n-api_implications-of-abi-stability" id="all_n-api_implications-of-abi-stability">#</a></span><a aria-hidden="true" class="legacy" id="n_api_implications_of_abi_stability"></a></h3>
<p>Although Node-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"><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;node.h></span></span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;node_buffer.h></span></span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;node_version.h></span></span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;node_object_wrap.h></span></span></code> <button class="copy-button">copy</button></pre>
</li>
<li>
<p>the libuv APIs which are also included with Node.js and available via</p>
<pre><code class="language-cpp"><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;uv.h></span></span></code> <button class="copy-button">copy</button></pre>
</li>
<li>
<p>the V8 API available via</p>
<pre><code class="language-cpp"><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;v8.h></span></span></code> <button class="copy-button">copy</button></pre>
</li>
</ul>
<p>Thus, for an addon to remain ABI-compatible across Node.js major versions, it
must use Node-API exclusively by restricting itself to using</p>
<pre><code class="language-c"><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;node_api.h></span></span></code> <button class="copy-button">copy</button></pre>
<p>and by checking, for all external libraries that it uses, that the external
library makes ABI stability guarantees similar to Node-API.</p>
</section><section><h3>Building<span><a class="mark" href="#all_n-api_building" id="all_n-api_building">#</a></span><a aria-hidden="true" class="legacy" id="n_api_building"></a></h3>
<p>Unlike modules written in JavaScript, developing and deploying Node.js
native addons using Node-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 platforms. 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> <button class="copy-button">copy</button></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 windows-build-tools</code> <button class="copy-button">copy</button></pre>
<p>The sections below describe the additional tools available for developing
and deploying Node.js native addons.</p>
<h4>Build tools<span><a class="mark" href="#all_n-api_build-tools" id="all_n-api_build-tools">#</a></span><a aria-hidden="true" class="legacy" id="n_api_build_tools"></a></h4>
<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>
<h5>node-gyp<span><a class="mark" href="#all_n-api_node-gyp" id="all_n-api_node-gyp">#</a></span><a aria-hidden="true" class="legacy" id="n_api_node_gyp"></a></h5>
<p><a href="https://github.com/nodejs/node-gyp">node-gyp</a> is a build system based on the <a href="https://github.com/nodejs/gyp-next">gyp-next</a> fork of
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>
<h5>CMake.js<span><a class="mark" href="#all_n-api_cmakejs" id="all_n-api_cmakejs">#</a></span><a aria-hidden="true" class="legacy" id="n_api_cmake_js"></a></h5>
<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. <a href="https://github.com/nodejs/node-addon-examples/tree/main/src/8-tooling/build_with_cmake"><code>build_with_cmake</code></a> is an
example of a CMake-based native addon project.</p>
<h4>Uploading precompiled binaries<span><a class="mark" href="#all_n-api_uploading-precompiled-binaries" id="all_n-api_uploading-precompiled-binaries">#</a></span><a aria-hidden="true" class="legacy" id="n_api_uploading_precompiled_binaries"></a></h4>
<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>
<h5>node-pre-gyp<span><a class="mark" href="#all_n-api_node-pre-gyp" id="all_n-api_node-pre-gyp">#</a></span><a aria-hidden="true" class="legacy" id="n_api_node_pre_gyp"></a></h5>
<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>
<h5>prebuild<span><a class="mark" href="#all_n-api_prebuild" id="all_n-api_prebuild">#</a></span><a aria-hidden="true" class="legacy" id="n_api_prebuild"></a></h5>
<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>
<h5>prebuildify<span><a class="mark" href="#all_n-api_prebuildify" id="all_n-api_prebuildify">#</a></span><a aria-hidden="true" class="legacy" id="n_api_prebuildify"></a></h5>
<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 addon when it's
uploaded to npm. The binaries are downloaded from npm and are immediately
available to the module user when the native addon is installed.</p>
</section><section><h3>Usage<span><a class="mark" href="#all_n-api_usage" id="all_n-api_usage">#</a></span><a aria-hidden="true" class="legacy" id="n_api_usage"></a></h3>
<p>In order to use the Node-API functions, include the file <a href="https://github.com/nodejs/node/blob/HEAD/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"><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;node_api.h></span></span></code> <button class="copy-button">copy</button></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 Node-API, the version
can be specified explicitly when including the header:</p>
<pre><code class="language-c"><span class="hljs-meta">#<span class="hljs-keyword">define</span> NAPI_VERSION 3</span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;node_api.h></span></span></code> <button class="copy-button">copy</button></pre>
<p>This restricts the Node-API surface to just the functionality that was available
in the specified (and earlier) versions.</p>
<p>Some of the Node-API surface is experimental and requires explicit opt-in:</p>
<pre><code class="language-c"><span class="hljs-meta">#<span class="hljs-keyword">define</span> NAPI_EXPERIMENTAL</span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;node_api.h></span></span></code> <button class="copy-button">copy</button></pre>
<p>In this case the entire API surface, including any experimental APIs, will be
available to the module code.</p>
<p>Occasionally, experimental features are introduced that affect already-released
and stable APIs. These features can be disabled by an opt-out:</p>
<pre><code class="language-c"><span class="hljs-meta">#<span class="hljs-keyword">define</span> NAPI_EXPERIMENTAL</span>
<span class="hljs-meta">#<span class="hljs-keyword">define</span> NODE_API_EXPERIMENTAL_<span class="hljs-string">&#x3C;FEATURE_NAME></span>_OPT_OUT</span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;node_api.h></span></span></code> <button class="copy-button">copy</button></pre>
<p>where <code>&#x3C;FEATURE_NAME></code> is the name of an experimental feature that affects both
experimental and stable APIs.</p>
</section><section><h3>Node-API version matrix<span><a class="mark" href="#all_n-api_node-api-version-matrix" id="all_n-api_node-api-version-matrix">#</a></span><a aria-hidden="true" class="legacy" id="n_api_node_api_version_matrix"></a></h3>
<p>Up until version 9, Node-API versions were additive and versioned
independently from Node.js. This meant that any version was
an extension to the previous version in that it had all of
the APIs from the previous version with some additions. Each
Node.js version only supported a single Node-API version.
For example v18.15.0 supports only Node-API version 8. ABI stability was
achieved because 8 was a strict superset of all previous versions.</p>
<p>As of version 9, while Node-API versions continue to be versioned
independently an add-on that ran with Node-API version 9 may need
code updates to run with Node-API version 10. ABI stability
is maintained, however, because Node.js versions that support
Node-API versions higher than 8 will support all versions
between 8 and the highest version they support and will default
to providing the version 8 APIs unless an add-on opts into a
higher Node-API version. This approach provides the flexibility
of better optimizing existing Node-API functions while
maintaining ABI stability. Existing add-ons can continue to run without
recompilation using an earlier version of Node-API. If an add-on
needs functionality from a newer Node-API version, changes to existing
code and recompilation will be needed to use those new functions anyway.</p>
<p>In versions of Node.js that support Node-API version 9 and later, defining
<code>NAPI_VERSION=X</code> and using the existing add-on initialization macros
will bake in the requested Node-API version that will be used at runtime
into the add-on. If <code>NAPI_VERSION</code> is not set it will default to 8.</p>
<p>This table may not be up to date in older streams, the most up to date
information is in the latest API documentation in:
<a href="https://nodejs.org/docs/latest/api/n-api.html#node-api-version-matrix">Node-API version matrix</a></p>
<!-- For accessibility purposes, this table needs row headers. That means we
     can't do it in markdown. Hence, the raw HTML. -->
<table>
  <tbody><tr>
    <th>Node-API version</th>
    <th scope="col">Supported In</th>
  </tr>
  <tr>
    <th scope="row">9</th>
    <td>v18.17.0+, 20.3.0+, 21.0.0 and all later versions</td>
  </tr>
  <tr>
    <th scope="row">8</th>
    <td>v12.22.0+, v14.17.0+, v15.12.0+, 16.0.0 and all later versions</td>
  </tr>
  <tr>
    <th scope="row">7</th>
    <td>v10.23.0+, v12.19.0+, v14.12.0+, 15.0.0 and all later versions</td>
  </tr>
  <tr>
    <th scope="row">6</th>
    <td>v10.20.0+, v12.17.0+, 14.0.0 and all later versions</td>
  </tr>
  <tr>
    <th scope="row">5</th>
    <td>v10.17.0+, v12.11.0+, 13.0.0 and all later versions</td>
  </tr>
  <tr>
    <th scope="row">4</th>
    <td>v10.16.0+, v11.8.0+, 12.0.0 and all later versions</td>
  </tr>
  
    <tr>
    <th scope="row">3</th>
    <td>v6.14.2*, 8.11.2+, v9.11.0+*, 10.0.0 and all later versions</td>
  </tr>
  <tr>
    <th scope="row">2</th>
    <td>v8.10.0+*, v9.3.0+*, 10.0.0 and all later versions</td>
  </tr>
  <tr>
    <th scope="row">1</th>
    <td>v8.6.0+**, v9.0.0+*, 10.0.0 and all later versions</td>
  </tr>
</tbody></table>
<p>* Node-API was experimental.</p>
<p>** Node.js 8.0.0 included Node-API as experimental. It was released as
Node-API version 1 but continued to evolve until Node.js 8.6.0. The API is
different in versions prior to Node.js 8.6.0. We recommend Node-API version 3 or
later.</p>
<p>Each API documented for Node-API will have a header named <code>added in:</code>, and APIs
which are stable will have the additional header <code>Node-API version:</code>.
APIs are directly usable when using a Node.js version which supports
the Node-API version shown in <code>Node-API version:</code> or higher.
When using a Node.js version that does not support the
<code>Node-API version:</code> listed or if there is no <code>Node-API version:</code> listed,
then the API will only be available if
<code>#define NAPI_EXPERIMENTAL</code> precedes the inclusion of <code>node_api.h</code>
or <code>js_native_api.h</code>. If an API appears not to be available on
a version of Node.js which is later than the one shown in <code>added in:</code> then
this is most likely the reason for the apparent absence.</p>
<p>The Node-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 Node-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 Node-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 Node-API or any implementation of Node-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"><span class="hljs-comment">// addon.h</span>
<span class="hljs-meta">#<span class="hljs-keyword">ifndef</span> _ADDON_H_</span>
<span class="hljs-meta">#<span class="hljs-keyword">define</span> _ADDON_H_</span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;js_native_api.h></span></span>
napi_value <span class="hljs-title function_">create_addon</span><span class="hljs-params">(napi_env env)</span>;
<span class="hljs-meta">#<span class="hljs-keyword">endif</span>  <span class="hljs-comment">// _ADDON_H_</span></span></code> <button class="copy-button">copy</button></pre>
<pre><code class="language-c"><span class="hljs-comment">// addon.c</span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">"addon.h"</span></span>

<span class="hljs-meta">#<span class="hljs-keyword">define</span> NODE_API_CALL(env, call)                                  \
  do {                                                            \
    napi_status status = (call);                                  \
    <span class="hljs-keyword">if</span> (status != napi_ok) {                                      \
      const napi_extended_error_info* error_info = NULL;          \
      napi_get_last_error_info((env), &#x26;error_info);               \
      const char* err_message = error_info->error_message;        \
      bool is_pending;                                            \
      napi_is_exception_pending((env), &#x26;is_pending);              \
      <span class="hljs-comment">/* If an exception is already pending, don't rethrow it */</span>  \
      <span class="hljs-keyword">if</span> (!is_pending) {                                          \
        const char* message = (err_message == NULL)               \
            ? <span class="hljs-string">"empty error message"</span>                               \
            : err_message;                                        \
        napi_throw_error((env), NULL, message);                   \
      }                                                           \
      return NULL;                                                \
    }                                                             \
  } while(0)</span>

<span class="hljs-type">static</span> napi_value
<span class="hljs-title function_">DoSomethingUseful</span><span class="hljs-params">(napi_env env, napi_callback_info info)</span> {
  <span class="hljs-comment">// Do something useful.</span>
  <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
}

napi_value <span class="hljs-title function_">create_addon</span><span class="hljs-params">(napi_env env)</span> {
  napi_value result;
  NODE_API_CALL(env, napi_create_object(env, &#x26;result));

  napi_value exported_function;
  NODE_API_CALL(env, napi_create_function(env,
                                          <span class="hljs-string">"doSomethingUseful"</span>,
                                          NAPI_AUTO_LENGTH,
                                          DoSomethingUseful,
                                          <span class="hljs-literal">NULL</span>,
                                          &#x26;exported_function));

  NODE_API_CALL(env, napi_set_named_property(env,
                                             result,
                                             <span class="hljs-string">"doSomethingUseful"</span>,
                                             exported_function));

  <span class="hljs-keyword">return</span> result;
}</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-c"><span class="hljs-comment">// addon_node.c</span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;node_api.h></span></span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">"addon.h"</span></span>

NAPI_MODULE_INIT(<span class="hljs-comment">/* napi_env env, napi_value exports */</span>) {
  <span class="hljs-comment">// This function body is expected to return a `napi_value`.</span>
  <span class="hljs-comment">// The variables `napi_env env` and `napi_value exports` may be used within</span>
  <span class="hljs-comment">// the body, as they are provided by the definition of `NAPI_MODULE_INIT()`.</span>
  <span class="hljs-keyword">return</span> create_addon(env);
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Environment life cycle APIs<span><a class="mark" href="#all_n-api_environment-life-cycle-apis" id="all_n-api_environment-life-cycle-apis">#</a></span><a aria-hidden="true" class="legacy" id="n_api_environment_life_cycle_apis"></a></h3>
<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 which they use during
their life cycle of an Node.js environment such that the state can be
unique to each instance of the addon.</p>
<p>To this end, Node-API provides a way to associate data such that its life cycle
is tied to the life cycle of a Node.js environment.</p>
<h4><code>napi_set_instance_data</code><span><a class="mark" href="#all_n-api_napi_set_instance_data" id="all_n-api_napi_set_instance_data">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_set_instance_data"></a></h4>
<div class="api_metadata">
<span>Added in: v12.8.0, v10.20.0</span>
<span>N-API version: 6</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_set_instance_data</span><span class="hljs-params">(node_api_basic_env env,
                                   <span class="hljs-type">void</span>* data,
                                   napi_finalize finalize_cb,
                                   <span class="hljs-type">void</span>* finalize_hint)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the Node-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.
<a href="#all_n-api_napi_finalize"><code>napi_finalize</code></a> provides more details.</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 Node.js environment. <code>data</code>
can later be retrieved using <code>napi_get_instance_data()</code>. Any existing data
associated with the currently running Node.js environment 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>
<h4><code>napi_get_instance_data</code><span><a class="mark" href="#all_n-api_napi_get_instance_data" id="all_n-api_napi_get_instance_data">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_instance_data"></a></h4>
<div class="api_metadata">
<span>Added in: v12.8.0, v10.20.0</span>
<span>N-API version: 6</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_instance_data</span><span class="hljs-params">(node_api_basic_env env,
                                   <span class="hljs-type">void</span>** data)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
<li><code>[out] data</code>: The data item that was previously associated with the currently
running Node.js environment 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 Node.js environment 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>
</section><section><h3>Basic Node-API data types<span><a class="mark" href="#all_n-api_basic-node-api-data-types" id="all_n-api_basic-node-api-data-types">#</a></span><a aria-hidden="true" class="legacy" id="n_api_basic_node_api_data_types"></a></h3>
<p>Node-API exposes the following fundamental data types as abstractions that are
consumed by the various APIs. These APIs should be treated as opaque,
introspectable only with other Node-API calls.</p>
<h4><code>napi_status</code><span><a class="mark" href="#all_n-api_napi_status" id="all_n-api_napi_status">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_status"></a></h4>
<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 Node-API call.
Currently, the following status codes are supported.</p>
<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> {</span>
  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_would_deadlock,  <span class="hljs-comment">/* unused */</span>
  napi_no_external_buffers_allowed,
  napi_cannot_run_js
} napi_status;</code> <button class="copy-button">copy</button></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>
<h4><code>napi_extended_error_info</code><span><a class="mark" href="#all_n-api_napi_extended_error_info" id="all_n-api_napi_extended_error_info">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_extended_error_info"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> {</span>
  <span class="hljs-type">const</span> <span class="hljs-type">char</span>* error_message;
  <span class="hljs-type">void</span>* engine_reserved;
  <span class="hljs-type">uint32_t</span> engine_error_code;
  napi_status error_code;
} napi_extended_error_info;</code> <button class="copy-button">copy</button></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 Node-API status code that originated with the last error.</li>
</ul>
<p>See the <a href="#all_n-api_error-handling">Error handling</a> section for additional information.</p>
<h4><code>napi_env</code><span><a class="mark" href="#all_n-api_napi_env" id="all_n-api_napi_env">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_env"></a></h4>
<p><code>napi_env</code> is used to represent a context that the underlying Node-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 Node-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 Node-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="#all_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="#all_n-api_napi_add_env_cleanup_hook"><code>napi_add_env_cleanup_hook</code></a> and
<a href="#all_n-api_napi_set_instance_data"><code>napi_set_instance_data</code></a>.</p>
<h4><code>node_api_basic_env</code><span><a class="mark" href="#all_n-api_node_api_basic_env" id="all_n-api_node_api_basic_env">#</a></span><a aria-hidden="true" class="legacy" id="n_api_node_api_basic_env"></a></h4>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>This variant of <code>napi_env</code> is passed to synchronous finalizers
(<a href="#all_n-api_node_api_basic_finalize"><code>node_api_basic_finalize</code></a>). There is a subset of Node-APIs which accept
a parameter of type <code>node_api_basic_env</code> as their first argument. These APIs do
not access the state of the JavaScript engine and are thus safe to call from
synchronous finalizers. Passing a parameter of type <code>napi_env</code> to these APIs is
allowed, however, passing a parameter of type <code>node_api_basic_env</code> to APIs that
access the JavaScript engine state is not allowed. Attempting to do so without
a cast will produce a compiler warning or an error when add-ons are compiled
with flags which cause them to emit warnings and/or errors when incorrect
pointer types are passed into a function. Calling such APIs from a synchronous
finalizer will ultimately result in the termination of the application.</p>
<h4><code>napi_value</code><span><a class="mark" href="#all_n-api_napi_value" id="all_n-api_napi_value">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_value"></a></h4>
<p>This is an opaque pointer that is used to represent a JavaScript value.</p>
<h4><code>napi_threadsafe_function</code><span><a class="mark" href="#all_n-api_napi_threadsafe_function" id="all_n-api_napi_threadsafe_function">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_threadsafe_function"></a></h4>
<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>
<h4><code>napi_threadsafe_function_release_mode</code><span><a class="mark" href="#all_n-api_napi_threadsafe_function_release_mode" id="all_n-api_napi_threadsafe_function_release_mode">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_threadsafe_function_release_mode"></a></h4>
<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"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> {</span>
  napi_tsfn_release,
  napi_tsfn_abort
} napi_threadsafe_function_release_mode;</code> <button class="copy-button">copy</button></pre>
<h4><code>napi_threadsafe_function_call_mode</code><span><a class="mark" href="#all_n-api_napi_threadsafe_function_call_mode" id="all_n-api_napi_threadsafe_function_call_mode">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_threadsafe_function_call_mode"></a></h4>
<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"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> {</span>
  napi_tsfn_nonblocking,
  napi_tsfn_blocking
} napi_threadsafe_function_call_mode;</code> <button class="copy-button">copy</button></pre>
<h4>Node-API memory management types<span><a class="mark" href="#all_n-api_node-api-memory-management-types" id="all_n-api_node-api-memory-management-types">#</a></span><a aria-hidden="true" class="legacy" id="n_api_node_api_memory_management_types"></a></h4>
<h5><code>napi_handle_scope</code><span><a class="mark" href="#all_n-api_napi_handle_scope" id="all_n-api_napi_handle_scope">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_handle_scope"></a></h5>
<p>This is an abstraction used to control and modify the lifetime of objects
created within a particular scope. In general, Node-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, Node-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="#all_n-api_napi_open_handle_scope"><code>napi_open_handle_scope</code></a> and are destroyed
using <a href="#all_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="#all_n-api_object-lifetime-management">Object lifetime management</a>.</p>
<h5><code>napi_escapable_handle_scope</code><span><a class="mark" href="#all_n-api_napi_escapable_handle_scope" id="all_n-api_napi_escapable_handle_scope">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_escapable_handle_scope"></a></h5>
<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>
<h5><code>napi_ref</code><span><a class="mark" href="#all_n-api_napi_ref" id="all_n-api_napi_ref">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_ref"></a></h5>
<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="#all_n-api_object-lifetime-management">Object lifetime management</a>.</p>
<h5><code>napi_type_tag</code><span><a class="mark" href="#all_n-api_napi_type_tag" id="all_n-api_napi_type_tag">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_type_tag"></a></h5>
<div class="api_metadata">
<span>Added in: v14.8.0, v12.19.0</span>
<span>N-API version: 8</span>
</div>
<p>A 128-bit value stored as two unsigned 64-bit integers. It serves as a UUID
with which JavaScript objects or <a href="#all_n-api_napi_create_external">externals</a> can be "tagged" in order to
ensure that they are of a certain type. This is a stronger check than
<a href="#all_n-api_napi_instanceof"><code>napi_instanceof</code></a>, because the latter can report a false positive if the
object's prototype has been manipulated. Type-tagging is most useful in
conjunction with <a href="#all_n-api_napi_wrap"><code>napi_wrap</code></a> because it ensures that the pointer retrieved
from a wrapped object can be safely cast to the native type corresponding to the
type tag that had been previously applied to the JavaScript object.</p>
<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> {</span>
  <span class="hljs-type">uint64_t</span> lower;
  <span class="hljs-type">uint64_t</span> upper;
} napi_type_tag;</code> <button class="copy-button">copy</button></pre>
<h5><code>napi_async_cleanup_hook_handle</code><span><a class="mark" href="#all_n-api_napi_async_cleanup_hook_handle" id="all_n-api_napi_async_cleanup_hook_handle">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_async_cleanup_hook_handle"></a></h5>
<div class="api_metadata">
<span>Added in: v14.10.0, v12.19.0</span>
</div>
<p>An opaque value returned by <a href="#all_n-api_napi_add_async_cleanup_hook"><code>napi_add_async_cleanup_hook</code></a>. It must be passed
to <a href="#all_n-api_napi_remove_async_cleanup_hook"><code>napi_remove_async_cleanup_hook</code></a> when the chain of asynchronous cleanup
events completes.</p>
<h4>Node-API callback types<span><a class="mark" href="#all_n-api_node-api-callback-types" id="all_n-api_node-api-callback-types">#</a></span><a aria-hidden="true" class="legacy" id="n_api_node_api_callback_types"></a></h4>
<h5><code>napi_callback_info</code><span><a class="mark" href="#all_n-api_napi_callback_info" id="all_n-api_napi_callback_info">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_callback_info"></a></h5>
<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>
<h5><code>napi_callback</code><span><a class="mark" href="#all_n-api_napi_callback" id="all_n-api_napi_callback">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_callback"></a></h5>
<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 Node-API. Callback functions should satisfy the
following signature:</p>
<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-title function_">napi_value</span> <span class="hljs-params">(*napi_callback)</span><span class="hljs-params">(napi_env, napi_callback_info)</span>;</code> <button class="copy-button">copy</button></pre>
<p>Unless for reasons discussed in <a href="#all_n-api_object-lifetime-management">Object Lifetime Management</a>, creating a
handle and/or callback scope inside a <code>napi_callback</code> is not necessary.</p>
<h5><code>node_api_basic_finalize</code><span><a class="mark" href="#all_n-api_node_api_basic_finalize" id="all_n-api_node_api_basic_finalize">#</a></span><a aria-hidden="true" class="legacy" id="n_api_node_api_basic_finalize"></a></h5>
<div class="api_metadata">
<span>Added in: v20.12.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<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 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>node_api_basic_finalize</code> can be used for
finding out when objects that have external data are collected.</p>
<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-title function_">void</span> <span class="hljs-params">(*node_api_basic_finalize)</span><span class="hljs-params">(node_api_basic_env env,
                                      <span class="hljs-type">void</span>* finalize_data,
                                      <span class="hljs-type">void</span>* finalize_hint)</span>;</code> <button class="copy-button">copy</button></pre>
<p>Unless for reasons discussed in <a href="#all_n-api_object-lifetime-management">Object Lifetime Management</a>, creating a
handle and/or callback scope inside the function body is not necessary.</p>
<p>Since these functions may be called while the JavaScript engine is in a state
where it cannot execute JavaScript code, only Node-APIs which accept a
<code>node_api_basic_env</code> as their first parameter may be called.
<a href="#all_n-api_node_api_post_finalizer"><code>node_api_post_finalizer</code></a> can be used to schedule Node-API calls that
require access to the JavaScript engine's state to run after the current
garbage collection cycle has completed.</p>
<p>In the case of <a href="#all_n-api_node_api_create_external_string_latin1"><code>node_api_create_external_string_latin1</code></a> and
<a href="#all_n-api_node_api_create_external_string_utf16"><code>node_api_create_external_string_utf16</code></a> the <code>env</code> parameter may be null,
because external strings can be collected during the latter part of environment
shutdown.</p>
<p>Change History:</p>
<ul>
<li>
<p>experimental (<code>NAPI_EXPERIMENTAL</code>):</p>
<p>Only Node-API calls that accept a <code>node_api_basic_env</code> as their first
parameter may be called, otherwise the application will be terminated with an
appropriate error message. This feature can be turned off by defining
<code>NODE_API_EXPERIMENTAL_BASIC_ENV_OPT_OUT</code>.</p>
</li>
</ul>
<h5><code>napi_finalize</code><span><a class="mark" href="#all_n-api_napi_finalize" id="all_n-api_napi_finalize">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_finalize"></a></h5>
<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 function that allow the user to
schedule a group of calls to Node-APIs in response to a garbage collection
event, after the garbage collection cycle has completed. These function
pointers can be used with <a href="#all_n-api_node_api_post_finalizer"><code>node_api_post_finalizer</code></a>.</p>
<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-title function_">void</span> <span class="hljs-params">(*napi_finalize)</span><span class="hljs-params">(napi_env env,
                              <span class="hljs-type">void</span>* finalize_data,
                              <span class="hljs-type">void</span>* finalize_hint)</span>;</code> <button class="copy-button">copy</button></pre>
<p>Change History:</p>
<ul>
<li>
<p>experimental (<code>NAPI_EXPERIMENTAL</code> is defined):</p>
<p>A function of this type may no longer be used as a finalizer, except with
<a href="#all_n-api_node_api_post_finalizer"><code>node_api_post_finalizer</code></a>. <a href="#all_n-api_node_api_basic_finalize"><code>node_api_basic_finalize</code></a> must be used
instead. This feature can be turned off by defining
<code>NODE_API_EXPERIMENTAL_BASIC_ENV_OPT_OUT</code>.</p>
</li>
</ul>
<h5><code>napi_async_execute_callback</code><span><a class="mark" href="#all_n-api_napi_async_execute_callback" id="all_n-api_napi_async_execute_callback">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_async_execute_callback"></a></h5>
<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"><span class="hljs-keyword">typedef</span> <span class="hljs-title function_">void</span> <span class="hljs-params">(*napi_async_execute_callback)</span><span class="hljs-params">(napi_env env, <span class="hljs-type">void</span>* data)</span>;</code> <button class="copy-button">copy</button></pre>
<p>Implementations of this function must avoid making Node-API calls that execute
JavaScript or interact with JavaScript objects. Node-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>
<h5><code>napi_async_complete_callback</code><span><a class="mark" href="#all_n-api_napi_async_complete_callback" id="all_n-api_napi_async_complete_callback">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_async_complete_callback"></a></h5>
<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"><span class="hljs-keyword">typedef</span> <span class="hljs-title function_">void</span> <span class="hljs-params">(*napi_async_complete_callback)</span><span class="hljs-params">(napi_env env,
                                             napi_status status,
                                             <span class="hljs-type">void</span>* data)</span>;</code> <button class="copy-button">copy</button></pre>
<p>Unless for reasons discussed in <a href="#all_n-api_object-lifetime-management">Object Lifetime Management</a>, creating a
handle and/or callback scope inside the function body is not necessary.</p>
<h5><code>napi_threadsafe_function_call_js</code><span><a class="mark" href="#all_n-api_napi_threadsafe_function_call_js" id="all_n-api_napi_threadsafe_function_call_js">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_threadsafe_function_call_js"></a></h5>
<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>Node-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"><span class="hljs-keyword">typedef</span> <span class="hljs-title function_">void</span> <span class="hljs-params">(*napi_threadsafe_function_call_js)</span><span class="hljs-params">(napi_env env,
                                                 napi_value js_callback,
                                                 <span class="hljs-type">void</span>* context,
                                                 <span class="hljs-type">void</span>* data)</span>;</code> <button class="copy-button">copy</button></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 Node-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>
<p>Unless for reasons discussed in <a href="#all_n-api_object-lifetime-management">Object Lifetime Management</a>, creating a
handle and/or callback scope inside the function body is not necessary.</p>
<h5><code>napi_cleanup_hook</code><span><a class="mark" href="#all_n-api_napi_cleanup_hook" id="all_n-api_napi_cleanup_hook">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_cleanup_hook"></a></h5>
<div class="api_metadata">
<span>Added in: v19.2.0, v18.13.0</span>
<span>N-API version: 3</span>
</div>
<p>Function pointer used with <a href="#all_n-api_napi_add_env_cleanup_hook"><code>napi_add_env_cleanup_hook</code></a>. It will be called
when the environment is being torn down.</p>
<p>Callback functions must satisfy the following signature:</p>
<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-title function_">void</span> <span class="hljs-params">(*napi_cleanup_hook)</span><span class="hljs-params">(<span class="hljs-type">void</span>* data)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] data</code>: The data that was passed to <a href="#all_n-api_napi_add_env_cleanup_hook"><code>napi_add_env_cleanup_hook</code></a>.</li>
</ul>
<h5><code>napi_async_cleanup_hook</code><span><a class="mark" href="#all_n-api_napi_async_cleanup_hook" id="all_n-api_napi_async_cleanup_hook">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_async_cleanup_hook"></a></h5>
<div class="api_metadata">
<span>Added in: v14.10.0, v12.19.0</span>
</div>
<p>Function pointer used with <a href="#all_n-api_napi_add_async_cleanup_hook"><code>napi_add_async_cleanup_hook</code></a>. It will be called
when the environment is being torn down.</p>
<p>Callback functions must satisfy the following signature:</p>
<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-title function_">void</span> <span class="hljs-params">(*napi_async_cleanup_hook)</span><span class="hljs-params">(napi_async_cleanup_hook_handle handle,
                                        <span class="hljs-type">void</span>* data)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] handle</code>: The handle that must be passed to
<a href="#all_n-api_napi_remove_async_cleanup_hook"><code>napi_remove_async_cleanup_hook</code></a> after completion of the asynchronous
cleanup.</li>
<li><code>[in] data</code>: The data that was passed to <a href="#all_n-api_napi_add_async_cleanup_hook"><code>napi_add_async_cleanup_hook</code></a>.</li>
</ul>
<p>The body of the function should initiate the asynchronous cleanup actions at the
end of which <code>handle</code> must be passed in a call to
<a href="#all_n-api_napi_remove_async_cleanup_hook"><code>napi_remove_async_cleanup_hook</code></a>.</p>
</section><section><h3>Error handling<span><a class="mark" href="#all_n-api_error-handling" id="all_n-api_error-handling">#</a></span><a aria-hidden="true" class="legacy" id="n_api_error_handling"></a></h3>
<p>Node-API uses both return values and JavaScript exceptions for error handling.
The following sections explain the approach for each case.</p>
<h4>Return values<span><a class="mark" href="#all_n-api_return-values" id="all_n-api_return-values">#</a></span><a aria-hidden="true" class="legacy" id="n_api_return_values"></a></h4>
<p>All of the Node-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="#all_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="#all_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"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">napi_extended_error_info</span> {</span>
  <span class="hljs-type">const</span> <span class="hljs-type">char</span>* error_message;
  <span class="hljs-type">void</span>* engine_reserved;
  <span class="hljs-type">uint32_t</span> engine_error_code;
  napi_status error_code;
};</code> <button class="copy-button">copy</button></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>: Node-API status code for the last error.</li>
</ul>
<p><a href="#all_n-api_napi_get_last_error_info"><code>napi_get_last_error_info</code></a> returns the information for the last
Node-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>
<h5><code>napi_get_last_error_info</code><span><a class="mark" href="#all_n-api_napi_get_last_error_info" id="all_n-api_napi_get_last_error_info">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_last_error_info"></a></h5>
<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
<span class="hljs-title function_">napi_get_last_error_info</span><span class="hljs-params">(node_api_basic_env env,
                         <span class="hljs-type">const</span> napi_extended_error_info** result)</span>;</code> <button class="copy-button">copy</button></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
a Node-API function is called on the same <code>env</code>. This includes a call to
<code>napi_is_exception_pending</code> so it may often be necessary to make a copy
of the information so that it can be used later. The pointer returned
in <code>error_message</code> points to a statically-defined string so it is safe to use
that pointer if you have copied it out of the <code>error_message</code> field (which will
be overwritten) before another Node-API function was called.</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>
<h4>Exceptions<span><a class="mark" href="#all_n-api_exceptions" id="all_n-api_exceptions">#</a></span><a aria-hidden="true" class="legacy" id="n_api_exceptions"></a></h4>
<p>Any Node-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="#all_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 a Node-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. Node-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 Node-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="#all_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="#all_n-api_napi_throw"><code>napi_throw</code></a> where error is the
JavaScript value 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="#all_n-api_napi_throw_error"><code>napi_throw_error</code></a>,
<a href="#all_n-api_napi_throw_type_error"><code>napi_throw_type_error</code></a>, <a href="#all_n-api_napi_throw_range_error"><code>napi_throw_range_error</code></a>, <a href="#all_n-api_node_api_throw_syntax_error"><code>node_api_throw_syntax_error</code></a> and <a href="#all_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="#all_n-api_napi_create_error"><code>napi_create_error</code></a>,
<a href="#all_n-api_napi_create_type_error"><code>napi_create_type_error</code></a>, <a href="#all_n-api_napi_create_range_error"><code>napi_create_range_error</code></a> and <a href="#all_n-api_node_api_create_syntax_error"><code>node_api_create_syntax_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 Node-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> <button class="copy-button">copy</button></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> <button class="copy-button">copy</button></pre>
<h5><code>napi_throw</code><span><a class="mark" href="#all_n-api_napi_throw" id="all_n-api_napi_throw">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_throw"></a></h5>
<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 <span class="hljs-title function_">napi_throw</span><span class="hljs-params">(napi_env env, napi_value error)</span>;</code> <button class="copy-button">copy</button></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>
<h5><code>napi_throw_error</code><span><a class="mark" href="#all_n-api_napi_throw_error" id="all_n-api_napi_throw_error">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_throw_error"></a></h5>
<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 <span class="hljs-title function_">napi_throw_error</span><span class="hljs-params">(napi_env env,
                                         <span class="hljs-type">const</span> <span class="hljs-type">char</span>* code,
                                         <span class="hljs-type">const</span> <span class="hljs-type">char</span>* msg)</span>;</code> <button class="copy-button">copy</button></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>
<h5><code>napi_throw_type_error</code><span><a class="mark" href="#all_n-api_napi_throw_type_error" id="all_n-api_napi_throw_type_error">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_throw_type_error"></a></h5>
<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 <span class="hljs-title function_">napi_throw_type_error</span><span class="hljs-params">(napi_env env,
                                              <span class="hljs-type">const</span> <span class="hljs-type">char</span>* code,
                                              <span class="hljs-type">const</span> <span class="hljs-type">char</span>* msg)</span>;</code> <button class="copy-button">copy</button></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>
<h5><code>napi_throw_range_error</code><span><a class="mark" href="#all_n-api_napi_throw_range_error" id="all_n-api_napi_throw_range_error">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_throw_range_error"></a></h5>
<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 <span class="hljs-title function_">napi_throw_range_error</span><span class="hljs-params">(napi_env env,
                                               <span class="hljs-type">const</span> <span class="hljs-type">char</span>* code,
                                               <span class="hljs-type">const</span> <span class="hljs-type">char</span>* msg)</span>;</code> <button class="copy-button">copy</button></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>
<h5><code>node_api_throw_syntax_error</code><span><a class="mark" href="#all_n-api_node_api_throw_syntax_error" id="all_n-api_node_api_throw_syntax_error">#</a></span><a aria-hidden="true" class="legacy" id="n_api_node_api_throw_syntax_error"></a></h5>
<div class="api_metadata">
<span>Added in: v17.2.0, v16.14.0</span>
<span>N-API version: 9</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">node_api_throw_syntax_error</span><span class="hljs-params">(napi_env env,
                                                    <span class="hljs-type">const</span> <span class="hljs-type">char</span>* code,
                                                    <span class="hljs-type">const</span> <span class="hljs-type">char</span>* msg)</span>;</code> <button class="copy-button">copy</button></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>SyntaxError</code> with the text provided.</p>
<h5><code>napi_is_error</code><span><a class="mark" href="#all_n-api_napi_is_error" id="all_n-api_napi_is_error">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_is_error"></a></h5>
<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 <span class="hljs-title function_">napi_is_error</span><span class="hljs-params">(napi_env env,
                                      napi_value value,
                                      <span class="hljs-type">bool</span>* result)</span>;</code> <button class="copy-button">copy</button></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>
<h5><code>napi_create_error</code><span><a class="mark" href="#all_n-api_napi_create_error" id="all_n-api_napi_create_error">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_error"></a></h5>
<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 <span class="hljs-title function_">napi_create_error</span><span class="hljs-params">(napi_env env,
                                          napi_value code,
                                          napi_value msg,
                                          napi_value* result)</span>;</code> <button class="copy-button">copy</button></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>
<h5><code>napi_create_type_error</code><span><a class="mark" href="#all_n-api_napi_create_type_error" id="all_n-api_napi_create_type_error">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_type_error"></a></h5>
<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 <span class="hljs-title function_">napi_create_type_error</span><span class="hljs-params">(napi_env env,
                                               napi_value code,
                                               napi_value msg,
                                               napi_value* result)</span>;</code> <button class="copy-button">copy</button></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>
<h5><code>napi_create_range_error</code><span><a class="mark" href="#all_n-api_napi_create_range_error" id="all_n-api_napi_create_range_error">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_range_error"></a></h5>
<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 <span class="hljs-title function_">napi_create_range_error</span><span class="hljs-params">(napi_env env,
                                                napi_value code,
                                                napi_value msg,
                                                napi_value* result)</span>;</code> <button class="copy-button">copy</button></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>
<h5><code>node_api_create_syntax_error</code><span><a class="mark" href="#all_n-api_node_api_create_syntax_error" id="all_n-api_node_api_create_syntax_error">#</a></span><a aria-hidden="true" class="legacy" id="n_api_node_api_create_syntax_error"></a></h5>
<div class="api_metadata">
<span>Added in: v17.2.0, v16.14.0</span>
<span>N-API version: 9</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">node_api_create_syntax_error</span><span class="hljs-params">(napi_env env,
                                                     napi_value code,
                                                     napi_value msg,
                                                     napi_value* result)</span>;</code> <button class="copy-button">copy</button></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>SyntaxError</code> with the text provided.</p>
<h5><code>napi_get_and_clear_last_exception</code><span><a class="mark" href="#all_n-api_napi_get_and_clear_last_exception" id="all_n-api_napi_get_and_clear_last_exception">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_and_clear_last_exception"></a></h5>
<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 <span class="hljs-title function_">napi_get_and_clear_last_exception</span><span class="hljs-params">(napi_env env,
                                              napi_value* result)</span>;</code> <button class="copy-button">copy</button></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>
<h5><code>napi_is_exception_pending</code><span><a class="mark" href="#all_n-api_napi_is_exception_pending" id="all_n-api_napi_is_exception_pending">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_is_exception_pending"></a></h5>
<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 <span class="hljs-title function_">napi_is_exception_pending</span><span class="hljs-params">(napi_env env, <span class="hljs-type">bool</span>* result)</span>;</code> <button class="copy-button">copy</button></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>
<h5><code>napi_fatal_exception</code><span><a class="mark" href="#all_n-api_napi_fatal_exception" id="all_n-api_napi_fatal_exception">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_fatal_exception"></a></h5>
<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 <span class="hljs-title function_">napi_fatal_exception</span><span class="hljs-params">(napi_env env, napi_value err)</span>;</code> <button class="copy-button">copy</button></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>
<h4>Fatal errors<span><a class="mark" href="#all_n-api_fatal-errors" id="all_n-api_fatal-errors">#</a></span><a aria-hidden="true" class="legacy" id="n_api_fatal_errors"></a></h4>
<p>In the event of an unrecoverable error in a native addon, a fatal error can be
thrown to immediately terminate the process.</p>
<h5><code>napi_fatal_error</code><span><a class="mark" href="#all_n-api_napi_fatal_error" id="all_n-api_napi_fatal_error">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_fatal_error"></a></h5>
<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 <span class="hljs-type">void</span> <span class="hljs-title function_">napi_fatal_error</span><span class="hljs-params">(<span class="hljs-type">const</span> <span class="hljs-type">char</span>* location,
                                     <span class="hljs-type">size_t</span> location_len,
                                     <span class="hljs-type">const</span> <span class="hljs-type">char</span>* message,
                                     <span class="hljs-type">size_t</span> message_len)</span>;</code> <button class="copy-button">copy</button></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>
</section><section><h3>Object lifetime management<span><a class="mark" href="#all_n-api_object-lifetime-management" id="all_n-api_object-lifetime-management">#</a></span><a aria-hidden="true" class="legacy" id="n_api_object_lifetime_management"></a></h3>
<p>As Node-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 Node-API functions that can be used
to change the handle lifespan from the default.</p>
<h4>Making handle lifespan shorter than that of the native method<span><a class="mark" href="#all_n-api_making-handle-lifespan-shorter-than-that-of-the-native-method" id="all_n-api_making-handle-lifespan-shorter-than-that-of-the-native-method">#</a></span><a aria-hidden="true" class="legacy" id="n_api_making_handle_lifespan_shorter_than_that_of_the_native_method"></a></h4>
<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"><span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> i = <span class="hljs-number">0</span>; i &#x3C; <span class="hljs-number">1000000</span>; i++) {
  napi_value result;
  napi_status status = napi_get_element(env, object, i, &#x26;result);
  <span class="hljs-keyword">if</span> (status != napi_ok) {
    <span class="hljs-keyword">break</span>;
  }
  <span class="hljs-comment">// do something with element</span>
}</code> <button class="copy-button">copy</button></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, Node-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="#all_n-api_napi_open_handle_scope"><code>napi_open_handle_scope</code></a> and <a href="#all_n-api_napi_close_handle_scope"><code>napi_close_handle_scope</code></a>.</p>
<p>Node-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="#all_n-api_napi_open_handle_scope"><code>napi_open_handle_scope</code></a> and
<a href="#all_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"><span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> i = <span class="hljs-number">0</span>; i &#x3C; <span class="hljs-number">1000000</span>; i++) {
  napi_handle_scope scope;
  napi_status status = napi_open_handle_scope(env, &#x26;scope);
  <span class="hljs-keyword">if</span> (status != napi_ok) {
    <span class="hljs-keyword">break</span>;
  }
  napi_value result;
  status = napi_get_element(env, object, i, &#x26;result);
  <span class="hljs-keyword">if</span> (status != napi_ok) {
    <span class="hljs-keyword">break</span>;
  }
  <span class="hljs-comment">// do something with element</span>
  status = napi_close_handle_scope(env, scope);
  <span class="hljs-keyword">if</span> (status != napi_ok) {
    <span class="hljs-keyword">break</span>;
  }
}</code> <button class="copy-button">copy</button></pre>
<p>When nesting scopes, there are cases where a handle from an
inner scope needs to live beyond the lifespan of that scope. Node-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="#all_n-api_napi_open_escapable_handle_scope"><code>napi_open_escapable_handle_scope</code></a> and
<a href="#all_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="#all_n-api_napi_escape_handle"><code>napi_escape_handle</code></a> which
can only be called once.</p>
<h5><code>napi_open_handle_scope</code><span><a class="mark" href="#all_n-api_napi_open_handle_scope" id="all_n-api_napi_open_handle_scope">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_open_handle_scope"></a></h5>
<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 <span class="hljs-title function_">napi_open_handle_scope</span><span class="hljs-params">(napi_env env,
                                               napi_handle_scope* result)</span>;</code> <button class="copy-button">copy</button></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>
<h5><code>napi_close_handle_scope</code><span><a class="mark" href="#all_n-api_napi_close_handle_scope" id="all_n-api_napi_close_handle_scope">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_close_handle_scope"></a></h5>
<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 <span class="hljs-title function_">napi_close_handle_scope</span><span class="hljs-params">(napi_env env,
                                                napi_handle_scope scope)</span>;</code> <button class="copy-button">copy</button></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>
<h5><code>napi_open_escapable_handle_scope</code><span><a class="mark" href="#all_n-api_napi_open_escapable_handle_scope" id="all_n-api_napi_open_escapable_handle_scope">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_open_escapable_handle_scope"></a></h5>
<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
    <span class="hljs-title function_">napi_open_escapable_handle_scope</span><span class="hljs-params">(napi_env env,
                                     napi_handle_scope* result)</span>;</code> <button class="copy-button">copy</button></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>
<h5><code>napi_close_escapable_handle_scope</code><span><a class="mark" href="#all_n-api_napi_close_escapable_handle_scope" id="all_n-api_napi_close_escapable_handle_scope">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_close_escapable_handle_scope"></a></h5>
<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
    <span class="hljs-title function_">napi_close_escapable_handle_scope</span><span class="hljs-params">(napi_env env,
                                      napi_handle_scope scope)</span>;</code> <button class="copy-button">copy</button></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>
<h5><code>napi_escape_handle</code><span><a class="mark" href="#all_n-api_napi_escape_handle" id="all_n-api_napi_escape_handle">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_escape_handle"></a></h5>
<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 <span class="hljs-title function_">napi_escape_handle</span><span class="hljs-params">(napi_env env,
                               napi_escapable_handle_scope scope,
                               napi_value escapee,
                               napi_value* result)</span>;</code> <button class="copy-button">copy</button></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>
<h4>References to values with a lifespan longer than that of the native method<span><a class="mark" href="#all_n-api_references-to-values-with-a-lifespan-longer-than-that-of-the-native-method" id="all_n-api_references-to-values-with-a-lifespan-longer-than-that-of-the-native-method">#</a></span><a aria-hidden="true" class="legacy" id="n_api_references_to_values_with_a_lifespan_longer_than_that_of_the_native_method"></a></h4>
<p>In some cases, an addon will need to be able to create and reference values
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 create 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>Node-API provides methods for creating persistent references to values.
Currently Node-API only allows references to be created for a
limited set of value types, including object, external, function, and symbol.</p>
<p>Each reference has an associated count with a value of 0 or higher,
which determines whether the reference will keep the corresponding value alive.
References with a count of 0 do not prevent values from being collected.
Values of object (object, function, external) and symbol types are becoming
'weak' references and can still be accessed while they are not collected.
Any count greater than 0 will prevent the values from being collected.</p>
<p>Symbol values have different flavors. The true weak reference behavior is
only supported by local symbols created with the <code>napi_create_symbol</code> function
or the JavaScript <code>Symbol()</code> constructor calls. Globally registered symbols
created with the <code>node_api_symbol_for</code> function or JavaScript <code>Symbol.for()</code>
function calls remain always strong references because the garbage collector
does not collect them. The same is true for well-known symbols such as
<code>Symbol.iterator</code>. They are also never collected by the garbage collector.</p>
<p>References can be created with an initial reference count. The count can
then be modified through <a href="#all_n-api_napi_reference_ref"><code>napi_reference_ref</code></a> and
<a href="#all_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="#all_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="#all_n-api_napi_reference_ref"><code>napi_reference_ref</code></a> for a reference whose object has been collected
results 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 results 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. Multiple persistent references to the same object
can result in unexpectedly keeping alive native memory. The native structures
for a persistent reference must be kept alive until finalizers for the
referenced object are executed. If a new persistent reference is created
for the same object, the finalizers for that object will not be
run and the native memory pointed by the earlier persistent reference
will not be freed. This can be avoided by calling
<code>napi_delete_reference</code> in addition to <code>napi_reference_unref</code> when possible.</p>
<p><strong>Change History:</strong></p>
<ul>
<li>
<p>Experimental (<code>NAPI_EXPERIMENTAL</code> is defined):</p>
<p>References can be created for all value types. The new supported value
types do not support weak reference semantic and the values of these types
are released when the reference count becomes 0 and cannot be accessed from
the reference anymore.</p>
</li>
</ul>
<h5><code>napi_create_reference</code><span><a class="mark" href="#all_n-api_napi_create_reference" id="all_n-api_napi_create_reference">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_reference"></a></h5>
<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 <span class="hljs-title function_">napi_create_reference</span><span class="hljs-params">(napi_env env,
                                              napi_value value,
                                              <span class="hljs-type">uint32_t</span> initial_refcount,
                                              napi_ref* result)</span>;</code> <button class="copy-button">copy</button></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> for which a reference is being created.</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 creates a new reference with the specified reference count
to the value passed in.</p>
<h5><code>napi_delete_reference</code><span><a class="mark" href="#all_n-api_napi_delete_reference" id="all_n-api_napi_delete_reference">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_delete_reference"></a></h5>
<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 <span class="hljs-title function_">napi_delete_reference</span><span class="hljs-params">(napi_env env, napi_ref ref)</span>;</code> <button class="copy-button">copy</button></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>
<h5><code>napi_reference_ref</code><span><a class="mark" href="#all_n-api_napi_reference_ref" id="all_n-api_napi_reference_ref">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_reference_ref"></a></h5>
<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 <span class="hljs-title function_">napi_reference_ref</span><span class="hljs-params">(napi_env env,
                                           napi_ref ref,
                                           <span class="hljs-type">uint32_t</span>* result)</span>;</code> <button class="copy-button">copy</button></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>
<h5><code>napi_reference_unref</code><span><a class="mark" href="#all_n-api_napi_reference_unref" id="all_n-api_napi_reference_unref">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_reference_unref"></a></h5>
<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 <span class="hljs-title function_">napi_reference_unref</span><span class="hljs-params">(napi_env env,
                                             napi_ref ref,
                                             <span class="hljs-type">uint32_t</span>* result)</span>;</code> <button class="copy-button">copy</button></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>
<h5><code>napi_get_reference_value</code><span><a class="mark" href="#all_n-api_napi_get_reference_value" id="all_n-api_napi_get_reference_value">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_reference_value"></a></h5>
<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 <span class="hljs-title function_">napi_get_reference_value</span><span class="hljs-params">(napi_env env,
                                                 napi_ref ref,
                                                 napi_value* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] ref</code>: The <code>napi_ref</code> for which the corresponding value is
being requested.</li>
<li><code>[out] result</code>: The <code>napi_value</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 value associated with the <code>napi_ref</code>. Otherwise, result
will be <code>NULL</code>.</p>
<h4>Cleanup on exit of the current Node.js environment<span><a class="mark" href="#all_n-api_cleanup-on-exit-of-the-current-nodejs-environment" id="all_n-api_cleanup-on-exit-of-the-current-nodejs-environment">#</a></span><a aria-hidden="true" class="legacy" id="n_api_cleanup_on_exit_of_the_current_node_js_environment"></a></h4>
<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 environment exits.</p>
<p>Node-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>
<h5><code>napi_add_env_cleanup_hook</code><span><a class="mark" href="#all_n-api_napi_add_env_cleanup_hook" id="all_n-api_napi_add_env_cleanup_hook">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_add_env_cleanup_hook"></a></h5>
<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 <span class="hljs-title function_">napi_add_env_cleanup_hook</span><span class="hljs-params">(node_api_basic_env env,
                                                  napi_cleanup_hook fun,
                                                  <span class="hljs-type">void</span>* arg)</span>;</code> <button class="copy-button">copy</button></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 <a href="#all_n-api_napi_remove_env_cleanup_hook"><code>napi_remove_env_cleanup_hook</code></a>.
Typically, that happens when the resource for which this hook was added
is being torn down anyway.</p>
<p>For asynchronous cleanup, <a href="#all_n-api_napi_add_async_cleanup_hook"><code>napi_add_async_cleanup_hook</code></a> is available.</p>
<h5><code>napi_remove_env_cleanup_hook</code><span><a class="mark" href="#all_n-api_napi_remove_env_cleanup_hook" id="all_n-api_napi_remove_env_cleanup_hook">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_remove_env_cleanup_hook"></a></h5>
<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 <span class="hljs-title function_">napi_remove_env_cleanup_hook</span><span class="hljs-params">(node_api_basic_env env,
                                                     <span class="hljs-type">void</span> (*fun)(<span class="hljs-type">void</span>* arg),
                                                     <span class="hljs-type">void</span>* arg)</span>;</code> <button class="copy-button">copy</button></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>
<h5><code>napi_add_async_cleanup_hook</code><span><a class="mark" href="#all_n-api_napi_add_async_cleanup_hook" id="all_n-api_napi_add_async_cleanup_hook">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_add_async_cleanup_hook"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.10.0, v12.19.0</td>
<td><p>Changed signature of the <code>hook</code> callback.</p></td></tr>
<tr><td>v14.8.0, v12.19.0</td>
<td><p><span>Added in: v14.8.0, v12.19.0</span></p></td></tr>
</tbody></table>
</details>
<span>N-API version: 8</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_add_async_cleanup_hook</span><span class="hljs-params">(
    node_api_basic_env env,
    napi_async_cleanup_hook hook,
    <span class="hljs-type">void</span>* arg,
    napi_async_cleanup_hook_handle* remove_handle)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] hook</code>: The function pointer to call at environment teardown.</li>
<li><code>[in] arg</code>: The pointer to pass to <code>hook</code> when it gets called.</li>
<li><code>[out] remove_handle</code>: Optional handle that refers to the asynchronous cleanup
hook.</li>
</ul>
<p>Registers <code>hook</code>, which is a function of type <a href="#all_n-api_napi_async_cleanup_hook"><code>napi_async_cleanup_hook</code></a>, as
a function to be run with the <code>remove_handle</code> and <code>arg</code> parameters once the
current Node.js environment exits.</p>
<p>Unlike <a href="#all_n-api_napi_add_env_cleanup_hook"><code>napi_add_env_cleanup_hook</code></a>, the hook is allowed to be asynchronous.</p>
<p>Otherwise, behavior generally matches that of <a href="#all_n-api_napi_add_env_cleanup_hook"><code>napi_add_env_cleanup_hook</code></a>.</p>
<p>If <code>remove_handle</code> is not <code>NULL</code>, an opaque value will be stored in it
that must later be passed to <a href="#all_n-api_napi_remove_async_cleanup_hook"><code>napi_remove_async_cleanup_hook</code></a>,
regardless of whether the hook has already been invoked.
Typically, that happens when the resource for which this hook was added
is being torn down anyway.</p>
<h5><code>napi_remove_async_cleanup_hook</code><span><a class="mark" href="#all_n-api_napi_remove_async_cleanup_hook" id="all_n-api_napi_remove_async_cleanup_hook">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_remove_async_cleanup_hook"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.10.0, v12.19.0</td>
<td><p>Removed <code>env</code> parameter.</p></td></tr>
<tr><td>v14.8.0, v12.19.0</td>
<td><p><span>Added in: v14.8.0, v12.19.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_remove_async_cleanup_hook</span><span class="hljs-params">(
    napi_async_cleanup_hook_handle remove_handle)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] remove_handle</code>: The handle to an asynchronous cleanup hook that was
created with <a href="#all_n-api_napi_add_async_cleanup_hook"><code>napi_add_async_cleanup_hook</code></a>.</li>
</ul>
<p>Unregisters the cleanup hook corresponding to <code>remove_handle</code>. This will prevent
the hook from being executed, unless it has already started executing.
This must be called on any <code>napi_async_cleanup_hook_handle</code> value obtained
from <a href="#all_n-api_napi_add_async_cleanup_hook"><code>napi_add_async_cleanup_hook</code></a>.</p>
<h4>Finalization on the exit of the Node.js environment<span><a class="mark" href="#all_n-api_finalization-on-the-exit-of-the-nodejs-environment" id="all_n-api_finalization-on-the-exit-of-the-nodejs-environment">#</a></span><a aria-hidden="true" class="legacy" id="n_api_finalization_on_the_exit_of_the_node_js_environment"></a></h4>
<p>The Node.js environment may be torn down at an arbitrary time as soon as
possible with JavaScript execution disallowed, like on the request of
<a href="#all_worker_threads_workerterminate"><code>worker.terminate()</code></a>. When the environment is being torn down, the
registered <code>napi_finalize</code> callbacks of JavaScript objects, thread-safe
functions and environment instance data are invoked immediately and
independently.</p>
<p>The invocation of <code>napi_finalize</code> callbacks is scheduled after the manually
registered cleanup hooks. In order to ensure a proper order of addon
finalization during environment shutdown to avoid use-after-free in the
<code>napi_finalize</code> callback, addons should register a cleanup hook with
<code>napi_add_env_cleanup_hook</code> and <code>napi_add_async_cleanup_hook</code> to manually
release the allocated resource in a proper order.</p>
</section><section><h3>Module registration<span><a class="mark" href="#all_n-api_module-registration" id="all_n-api_module-registration">#</a></span><a aria-hidden="true" class="legacy" id="n_api_module_registration"></a></h3>
<p>Node-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> <button class="copy-button">copy</button></pre>
<p>The next difference is the signature for the <code>Init</code> method. For a Node-API
module it is as follows:</p>
<pre><code class="language-c">napi_value <span class="hljs-title function_">Init</span><span class="hljs-params">(napi_env env, napi_value exports)</span>;</code> <button class="copy-button">copy</button></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. Node-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 <span class="hljs-title function_">Init</span><span class="hljs-params">(napi_env env, napi_value exports)</span> {
  napi_status status;
  napi_property_descriptor desc = {
    <span class="hljs-string">"hello"</span>,
    <span class="hljs-literal">NULL</span>,
    Method,
    <span class="hljs-literal">NULL</span>,
    <span class="hljs-literal">NULL</span>,
    <span class="hljs-literal">NULL</span>,
    napi_writable | napi_enumerable | napi_configurable,
    <span class="hljs-literal">NULL</span>
  };
  status = napi_define_properties(env, exports, <span class="hljs-number">1</span>, &#x26;desc);
  <span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
  <span class="hljs-keyword">return</span> exports;
}</code> <button class="copy-button">copy</button></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 <span class="hljs-title function_">Init</span><span class="hljs-params">(napi_env env, napi_value exports)</span> {
  napi_value method;
  napi_status status;
  status = napi_create_function(env, <span class="hljs-string">"exports"</span>, NAPI_AUTO_LENGTH, Method, <span class="hljs-literal">NULL</span>, &#x26;method);
  <span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
  <span class="hljs-keyword">return</span> method;
}</code> <button class="copy-button">copy</button></pre>
<p>To define a class so that new instances can be created (often used with
<a href="#all_n-api_object-wrap">Object wrap</a>):</p>
<pre><code class="language-c"><span class="hljs-comment">// <span class="hljs-doctag">NOTE:</span> partial example, not all referenced code is included</span>
napi_value <span class="hljs-title function_">Init</span><span class="hljs-params">(napi_env env, napi_value exports)</span> {
  napi_status status;
  napi_property_descriptor properties[] = {
    { <span class="hljs-string">"value"</span>, <span class="hljs-literal">NULL</span>, <span class="hljs-literal">NULL</span>, GetValue, SetValue, <span class="hljs-literal">NULL</span>, napi_writable | napi_configurable, <span class="hljs-literal">NULL</span> },
    DECLARE_NAPI_METHOD(<span class="hljs-string">"plusOne"</span>, PlusOne),
    DECLARE_NAPI_METHOD(<span class="hljs-string">"multiply"</span>, Multiply),
  };

  napi_value cons;
  status =
      napi_define_class(env, <span class="hljs-string">"MyObject"</span>, New, <span class="hljs-literal">NULL</span>, <span class="hljs-number">3</span>, properties, &#x26;cons);
  <span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;

  status = napi_create_reference(env, cons, <span class="hljs-number">1</span>, &#x26;constructor);
  <span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;

  status = napi_set_named_property(env, exports, <span class="hljs-string">"MyObject"</span>, cons);
  <span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;

  <span class="hljs-keyword">return</span> exports;
}</code> <button class="copy-button">copy</button></pre>
<p>You can also use the <code>NAPI_MODULE_INIT</code> macro, which acts as a shorthand
for <code>NAPI_MODULE</code> and defining an <code>Init</code> function:</p>
<pre><code class="language-c">NAPI_MODULE_INIT(<span class="hljs-comment">/* napi_env env, napi_value exports */</span>) {
  napi_value answer;
  napi_status result;

  status = napi_create_int64(env, <span class="hljs-number">42</span>, &#x26;answer);
  <span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;

  status = napi_set_named_property(env, exports, <span class="hljs-string">"answer"</span>, answer);
  <span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;

  <span class="hljs-keyword">return</span> exports;
}</code> <button class="copy-button">copy</button></pre>
<p>The parameters <code>env</code> and <code>exports</code> are provided to the body of the
<code>NAPI_MODULE_INIT</code> macro.</p>
<p>All Node-API addons are context-aware, meaning they may be loaded multiple
times. There are a few design considerations when declaring such a module.
The documentation on <a href="#all_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="#all_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>
</section><section><h3>Working with JavaScript values<span><a class="mark" href="#all_n-api_working-with-javascript-values" id="all_n-api_working-with-javascript-values">#</a></span><a aria-hidden="true" class="legacy" id="n_api_working_with_javascript_values"></a></h3>
<p>Node-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 a Node-API value</li>
<li>Convert from Node-API value to a primitive C type</li>
<li>Get global instances including <code>undefined</code> and <code>null</code></li>
</ol>
<p>Node-API values are represented by the type <code>napi_value</code>.
Any Node-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>
<h4>Enum types<span><a class="mark" href="#all_n-api_enum-types" id="all_n-api_enum-types">#</a></span><a aria-hidden="true" class="legacy" id="n_api_enum_types"></a></h4>
<h5><code>napi_key_collection_mode</code><span><a class="mark" href="#all_n-api_napi_key_collection_mode" id="all_n-api_napi_key_collection_mode">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_key_collection_mode"></a></h5>
<div class="api_metadata">
<span>Added in: v13.7.0, v12.17.0, v10.20.0</span>
<span>N-API version: 6</span>
</div>
<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> {</span>
  napi_key_include_prototypes,
  napi_key_own_only
} napi_key_collection_mode;</code> <button class="copy-button">copy</button></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>
<h5><code>napi_key_filter</code><span><a class="mark" href="#all_n-api_napi_key_filter" id="all_n-api_napi_key_filter">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_key_filter"></a></h5>
<div class="api_metadata">
<span>Added in: v13.7.0, v12.17.0, v10.20.0</span>
<span>N-API version: 6</span>
</div>
<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> {</span>
  napi_key_all_properties = <span class="hljs-number">0</span>,
  napi_key_writable = <span class="hljs-number">1</span>,
  napi_key_enumerable = <span class="hljs-number">1</span> &#x3C;&#x3C; <span class="hljs-number">1</span>,
  napi_key_configurable = <span class="hljs-number">1</span> &#x3C;&#x3C; <span class="hljs-number">2</span>,
  napi_key_skip_strings = <span class="hljs-number">1</span> &#x3C;&#x3C; <span class="hljs-number">3</span>,
  napi_key_skip_symbols = <span class="hljs-number">1</span> &#x3C;&#x3C; <span class="hljs-number">4</span>
} napi_key_filter;</code> <button class="copy-button">copy</button></pre>
<p>Property filter bits. They can be or'ed to build a composite filter.</p>
<h5><code>napi_key_conversion</code><span><a class="mark" href="#all_n-api_napi_key_conversion" id="all_n-api_napi_key_conversion">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_key_conversion"></a></h5>
<div class="api_metadata">
<span>Added in: v13.7.0, v12.17.0, v10.20.0</span>
<span>N-API version: 6</span>
</div>
<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> {</span>
  napi_key_keep_numbers,
  napi_key_numbers_to_strings
} napi_key_conversion;</code> <button class="copy-button">copy</button></pre>
<p><code>napi_key_numbers_to_strings</code> will convert integer indexes to
strings. <code>napi_key_keep_numbers</code> will return numbers for integer
indexes.</p>
<h5><code>napi_valuetype</code><span><a class="mark" href="#all_n-api_napi_valuetype" id="all_n-api_napi_valuetype">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_valuetype"></a></h5>
<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> {</span>
  <span class="hljs-comment">// ES6 types (corresponds to typeof)</span>
  napi_undefined,
  napi_null,
  napi_boolean,
  napi_number,
  napi_string,
  napi_symbol,
  napi_object,
  napi_function,
  napi_external,
  napi_bigint,
} napi_valuetype;</code> <button class="copy-button">copy</button></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>
<h5><code>napi_typedarray_type</code><span><a class="mark" href="#all_n-api_napi_typedarray_type" id="all_n-api_napi_typedarray_type">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_typedarray_type"></a></h5>
<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> {</span>
  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> <button class="copy-button">copy</button></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>
<h4>Object creation functions<span><a class="mark" href="#all_n-api_object-creation-functions" id="all_n-api_object-creation-functions">#</a></span><a aria-hidden="true" class="legacy" id="n_api_object_creation_functions"></a></h4>
<h5><code>napi_create_array</code><span><a class="mark" href="#all_n-api_napi_create_array" id="all_n-api_napi_create_array">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_array"></a></h5>
<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 <span class="hljs-title function_">napi_create_array</span><span class="hljs-params">(napi_env env, napi_value* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the Node-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 a Node-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>
<h5><code>napi_create_array_with_length</code><span><a class="mark" href="#all_n-api_napi_create_array_with_length" id="all_n-api_napi_create_array_with_length">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_array_with_length"></a></h5>
<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 <span class="hljs-title function_">napi_create_array_with_length</span><span class="hljs-params">(napi_env env,
                                          <span class="hljs-type">size_t</span> length,
                                          napi_value* result)</span></code> <button class="copy-button">copy</button></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 a Node-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="#all_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>
<h5><code>napi_create_arraybuffer</code><span><a class="mark" href="#all_n-api_napi_create_arraybuffer" id="all_n-api_napi_create_arraybuffer">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_arraybuffer"></a></h5>
<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 <span class="hljs-title function_">napi_create_arraybuffer</span><span class="hljs-params">(napi_env env,
                                    <span class="hljs-type">size_t</span> byte_length,
                                    <span class="hljs-type">void</span>** data,
                                    napi_value* result)</span></code> <button class="copy-button">copy</button></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>.
<code>data</code> can optionally be ignored by passing <code>NULL</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 a Node-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>
<h5><code>napi_create_buffer</code><span><a class="mark" href="#all_n-api_napi_create_buffer" id="all_n-api_napi_create_buffer">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_buffer"></a></h5>
<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 <span class="hljs-title function_">napi_create_buffer</span><span class="hljs-params">(napi_env env,
                               <span class="hljs-type">size_t</span> size,
                               <span class="hljs-type">void</span>** data,
                               napi_value* result)</span></code> <button class="copy-button">copy</button></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.
<code>data</code> can optionally be ignored by passing <code>NULL</code>.</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>
<h5><code>napi_create_buffer_copy</code><span><a class="mark" href="#all_n-api_napi_create_buffer_copy" id="all_n-api_napi_create_buffer_copy">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_buffer_copy"></a></h5>
<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 <span class="hljs-title function_">napi_create_buffer_copy</span><span class="hljs-params">(napi_env env,
                                    <span class="hljs-type">size_t</span> length,
                                    <span class="hljs-type">const</span> <span class="hljs-type">void</span>* data,
                                    <span class="hljs-type">void</span>** result_data,
                                    napi_value* result)</span></code> <button class="copy-button">copy</button></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.
<code>result_data</code> can optionally be ignored by passing <code>NULL</code>.</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>
<h5><code>napi_create_date</code><span><a class="mark" href="#all_n-api_napi_create_date" id="all_n-api_napi_create_date">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_date"></a></h5>
<div class="api_metadata">
<span>Added in: v11.11.0, v10.17.0</span>
<span>N-API version: 5</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_create_date</span><span class="hljs-params">(napi_env env,
                             <span class="hljs-type">double</span> time,
                             napi_value* result)</span>;</code> <button class="copy-button">copy</button></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>
<h5><code>napi_create_external</code><span><a class="mark" href="#all_n-api_napi_create_external" id="all_n-api_napi_create_external">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_external"></a></h5>
<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 <span class="hljs-title function_">napi_create_external</span><span class="hljs-params">(napi_env env,
                                 <span class="hljs-type">void</span>* data,
                                 napi_finalize finalize_cb,
                                 <span class="hljs-type">void</span>* finalize_hint,
                                 napi_value* result)</span></code> <button class="copy-button">copy</button></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. <a href="#all_n-api_napi_finalize"><code>napi_finalize</code></a> provides more details.</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="#all_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 has been garbage collected.</p>
<p>The created value is not an object, and therefore does not support additional
properties. It is considered a distinct value type: calling <code>napi_typeof()</code> with
an external value yields <code>napi_external</code>.</p>
<h5><code>napi_create_external_arraybuffer</code><span><a class="mark" href="#all_n-api_napi_create_external_arraybuffer" id="all_n-api_napi_create_external_arraybuffer">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_external_arraybuffer"></a></h5>
<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
<span class="hljs-title function_">napi_create_external_arraybuffer</span><span class="hljs-params">(napi_env env,
                                 <span class="hljs-type">void</span>* external_data,
                                 <span class="hljs-type">size_t</span> byte_length,
                                 napi_finalize finalize_cb,
                                 <span class="hljs-type">void</span>* finalize_hint,
                                 napi_value* result)</span></code> <button class="copy-button">copy</button></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. <a href="#all_n-api_napi_finalize"><code>napi_finalize</code></a> provides more details.</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><strong>Some runtimes other than Node.js have dropped support for external buffers</strong>.
On runtimes other than Node.js this method may return
<code>napi_no_external_buffers_allowed</code> to indicate that external
buffers are not supported. One such runtime is Electron as
described in this issue
<a href="https://github.com/electron/electron/issues/35801">electron/issues/35801</a>.</p>
<p>In order to maintain broadest compatibility with all runtimes
you may define <code>NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED</code> in your addon before
includes for the node-api headers. Doing so will hide the 2 functions
that create external buffers. This will ensure a compilation error
occurs if you accidentally use one of these methods.</p>
<p>This API returns a Node-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 has been garbage collected.</p>
<p>JavaScript <code>ArrayBuffer</code>s are described in
<a href="https://tc39.github.io/ecma262/#sec-arraybuffer-objects">Section 24.1</a> of the ECMAScript Language Specification.</p>
<h5><code>napi_create_external_buffer</code><span><a class="mark" href="#all_n-api_napi_create_external_buffer" id="all_n-api_napi_create_external_buffer">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_external_buffer"></a></h5>
<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 <span class="hljs-title function_">napi_create_external_buffer</span><span class="hljs-params">(napi_env env,
                                        <span class="hljs-type">size_t</span> length,
                                        <span class="hljs-type">void</span>* data,
                                        napi_finalize finalize_cb,
                                        <span class="hljs-type">void</span>* finalize_hint,
                                        napi_value* result)</span></code> <button class="copy-button">copy</button></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 expose to JavaScript.</li>
<li><code>[in] finalize_cb</code>: Optional callback to call when the <code>ArrayBuffer</code> is being
collected. <a href="#all_n-api_napi_finalize"><code>napi_finalize</code></a> provides more details.</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><strong>Some runtimes other than Node.js have dropped support for external buffers</strong>.
On runtimes other than Node.js this method may return
<code>napi_no_external_buffers_allowed</code> to indicate that external
buffers are not supported. One such runtime is Electron as
described in this issue
<a href="https://github.com/electron/electron/issues/35801">electron/issues/35801</a>.</p>
<p>In order to maintain broadest compatibility with all runtimes
you may define <code>NODE_API_NO_EXTERNAL_BUFFERS_ALLOWED</code> in your addon before
includes for the node-api headers. Doing so will hide the 2 functions
that create external buffers. This will ensure a compilation error
occurs if you accidentally use one of these methods.</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 has been garbage collected.</p>
<p>For Node.js >=4 <code>Buffers</code> are <code>Uint8Array</code>s.</p>
<h5><code>napi_create_object</code><span><a class="mark" href="#all_n-api_napi_create_object" id="all_n-api_napi_create_object">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_object"></a></h5>
<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 <span class="hljs-title function_">napi_create_object</span><span class="hljs-params">(napi_env env, napi_value* result)</span></code> <button class="copy-button">copy</button></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>
<h5><code>napi_create_symbol</code><span><a class="mark" href="#all_n-api_napi_create_symbol" id="all_n-api_napi_create_symbol">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_symbol"></a></h5>
<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 <span class="hljs-title function_">napi_create_symbol</span><span class="hljs-params">(napi_env env,
                               napi_value description,
                               napi_value* result)</span></code> <button class="copy-button">copy</button></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> value 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>
<h5><code>node_api_symbol_for</code><span><a class="mark" href="#all_n-api_node_api_symbol_for" id="all_n-api_node_api_symbol_for">#</a></span><a aria-hidden="true" class="legacy" id="n_api_node_api_symbol_for"></a></h5>
<div class="api_metadata">
<span>Added in: v17.5.0, v16.15.0</span>
<span>N-API version: 9</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">node_api_symbol_for</span><span class="hljs-params">(napi_env env,
                                <span class="hljs-type">const</span> <span class="hljs-type">char</span>* utf8description,
                                <span class="hljs-type">size_t</span> length,
                                napi_value* result)</span></code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] utf8description</code>: UTF-8 C string representing the text to be used as the
description for the symbol.</li>
<li><code>[in] length</code>: The length of the description 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>symbol</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API searches in the global registry for an existing symbol with the given
description. If the symbol already exists it will be returned, otherwise a new
symbol will be created in the registry.</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>
<h5><code>napi_create_typedarray</code><span><a class="mark" href="#all_n-api_napi_create_typedarray" id="all_n-api_napi_create_typedarray">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_typedarray"></a></h5>
<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 <span class="hljs-title function_">napi_create_typedarray</span><span class="hljs-params">(napi_env env,
                                   napi_typedarray_type type,
                                   <span class="hljs-type">size_t</span> length,
                                   napi_value arraybuffer,
                                   <span class="hljs-type">size_t</span> byte_offset,
                                   napi_value* result)</span></code> <button class="copy-button">copy</button></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>
<h5><code>napi_create_dataview</code><span><a class="mark" href="#all_n-api_napi_create_dataview" id="all_n-api_napi_create_dataview">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_dataview"></a></h5>
<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 <span class="hljs-title function_">napi_create_dataview</span><span class="hljs-params">(napi_env env,
                                 <span class="hljs-type">size_t</span> byte_length,
                                 napi_value arraybuffer,
                                 <span class="hljs-type">size_t</span> byte_offset,
                                 napi_value* result)</span></code> <button class="copy-button">copy</button></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>
<h4>Functions to convert from C types to Node-API<span><a class="mark" href="#all_n-api_functions-to-convert-from-c-types-to-node-api" id="all_n-api_functions-to-convert-from-c-types-to-node-api">#</a></span><a aria-hidden="true" class="legacy" id="n_api_functions_to_convert_from_c_types_to_node_api"></a></h4>
<h5><code>napi_create_int32</code><span><a class="mark" href="#all_n-api_napi_create_int32" id="all_n-api_napi_create_int32">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_int32"></a></h5>
<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 <span class="hljs-title function_">napi_create_int32</span><span class="hljs-params">(napi_env env, <span class="hljs-type">int32_t</span> value, napi_value* result)</span></code> <button class="copy-button">copy</button></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>
<h5><code>napi_create_uint32</code><span><a class="mark" href="#all_n-api_napi_create_uint32" id="all_n-api_napi_create_uint32">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_uint32"></a></h5>
<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 <span class="hljs-title function_">napi_create_uint32</span><span class="hljs-params">(napi_env env, <span class="hljs-type">uint32_t</span> value, napi_value* result)</span></code> <button class="copy-button">copy</button></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>
<h5><code>napi_create_int64</code><span><a class="mark" href="#all_n-api_napi_create_int64" id="all_n-api_napi_create_int64">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_int64"></a></h5>
<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 <span class="hljs-title function_">napi_create_int64</span><span class="hljs-params">(napi_env env, <span class="hljs-type">int64_t</span> value, napi_value* result)</span></code> <button class="copy-button">copy</button></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>
<h5><code>napi_create_double</code><span><a class="mark" href="#all_n-api_napi_create_double" id="all_n-api_napi_create_double">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_double"></a></h5>
<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 <span class="hljs-title function_">napi_create_double</span><span class="hljs-params">(napi_env env, <span class="hljs-type">double</span> value, napi_value* result)</span></code> <button class="copy-button">copy</button></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>
<h5><code>napi_create_bigint_int64</code><span><a class="mark" href="#all_n-api_napi_create_bigint_int64" id="all_n-api_napi_create_bigint_int64">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_bigint_int64"></a></h5>
<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 <span class="hljs-title function_">napi_create_bigint_int64</span><span class="hljs-params">(napi_env env,
                                     <span class="hljs-type">int64_t</span> value,
                                     napi_value* result)</span>;</code> <button class="copy-button">copy</button></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>
<h5><code>napi_create_bigint_uint64</code><span><a class="mark" href="#all_n-api_napi_create_bigint_uint64" id="all_n-api_napi_create_bigint_uint64">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_bigint_uint64"></a></h5>
<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 <span class="hljs-title function_">napi_create_bigint_uint64</span><span class="hljs-params">(napi_env env,
                                      <span class="hljs-type">uint64_t</span> value,
                                      napi_value* result)</span>;</code> <button class="copy-button">copy</button></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>
<h5><code>napi_create_bigint_words</code><span><a class="mark" href="#all_n-api_napi_create_bigint_words" id="all_n-api_napi_create_bigint_words">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_bigint_words"></a></h5>
<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 <span class="hljs-title function_">napi_create_bigint_words</span><span class="hljs-params">(napi_env env,
                                     <span class="hljs-type">int</span> sign_bit,
                                     <span class="hljs-type">size_t</span> word_count,
                                     <span class="hljs-type">const</span> <span class="hljs-type">uint64_t</span>* words,
                                     napi_value* result)</span>;</code> <button class="copy-button">copy</button></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>
<h5><code>napi_create_string_latin1</code><span><a class="mark" href="#all_n-api_napi_create_string_latin1" id="all_n-api_napi_create_string_latin1">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_string_latin1"></a></h5>
<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 <span class="hljs-title function_">napi_create_string_latin1</span><span class="hljs-params">(napi_env env,
                                      <span class="hljs-type">const</span> <span class="hljs-type">char</span>* str,
                                      <span class="hljs-type">size_t</span> length,
                                      napi_value* result)</span>;</code> <button class="copy-button">copy</button></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> value 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>
<h5><code>node_api_create_external_string_latin1</code><span><a class="mark" href="#all_n-api_node_api_create_external_string_latin1" id="all_n-api_node_api_create_external_string_latin1">#</a></span><a aria-hidden="true" class="legacy" id="n_api_node_api_create_external_string_latin1"></a></h5>
<div class="api_metadata">
<span>Added in: v20.4.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<pre><code class="language-c">napi_status
<span class="hljs-title function_">node_api_create_external_string_latin1</span><span class="hljs-params">(napi_env env,
                                       <span class="hljs-type">char</span>* str,
                                       <span class="hljs-type">size_t</span> length,
                                       napi_finalize finalize_callback,
                                       <span class="hljs-type">void</span>* finalize_hint,
                                       napi_value* result,
                                       <span class="hljs-type">bool</span>* copied)</span>;</code> <button class="copy-button">copy</button></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>[in] finalize_callback</code>: The function to call when the string is being
collected. The function will be called with the following parameters:
<ul>
<li><code>[in] env</code>: The environment in which the add-on is running. This value
may be null if the string is being collected as part of the termination
of the worker or the main Node.js instance.</li>
<li><code>[in] data</code>: This is the value <code>str</code> as a <code>void*</code> pointer.</li>
<li><code>[in] finalize_hint</code>: This is the value <code>finalize_hint</code> that was given
to the API.
<a href="#all_n-api_napi_finalize"><code>napi_finalize</code></a> provides more details.
This parameter is optional. Passing a null value means that the add-on
doesn't need to be notified when the corresponding JavaScript string is
collected.</li>
</ul>
</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>string</code>.</li>
<li><code>[out] copied</code>: Whether the string was copied. If it was, the finalizer will
already have been invoked to destroy <code>str</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API creates a JavaScript <code>string</code> value from an ISO-8859-1-encoded C
string. The native string may not be copied and must thus exist for the entire
life cycle of the JavaScript value.</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>
<h5><code>napi_create_string_utf16</code><span><a class="mark" href="#all_n-api_napi_create_string_utf16" id="all_n-api_napi_create_string_utf16">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_string_utf16"></a></h5>
<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 <span class="hljs-title function_">napi_create_string_utf16</span><span class="hljs-params">(napi_env env,
                                     <span class="hljs-type">const</span> <span class="hljs-type">char16_t</span>* str,
                                     <span class="hljs-type">size_t</span> length,
                                     napi_value* result)</span></code> <button class="copy-button">copy</button></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> value 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>
<h5><code>node_api_create_external_string_utf16</code><span><a class="mark" href="#all_n-api_node_api_create_external_string_utf16" id="all_n-api_node_api_create_external_string_utf16">#</a></span><a aria-hidden="true" class="legacy" id="n_api_node_api_create_external_string_utf16"></a></h5>
<div class="api_metadata">
<span>Added in: v20.4.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<pre><code class="language-c">napi_status
<span class="hljs-title function_">node_api_create_external_string_utf16</span><span class="hljs-params">(napi_env env,
                                      <span class="hljs-type">char16_t</span>* str,
                                      <span class="hljs-type">size_t</span> length,
                                      napi_finalize finalize_callback,
                                      <span class="hljs-type">void</span>* finalize_hint,
                                      napi_value* result,
                                      <span class="hljs-type">bool</span>* copied)</span>;</code> <button class="copy-button">copy</button></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>[in] finalize_callback</code>: The function to call when the string is being
collected. The function will be called with the following parameters:
<ul>
<li><code>[in] env</code>: The environment in which the add-on is running. This value
may be null if the string is being collected as part of the termination
of the worker or the main Node.js instance.</li>
<li><code>[in] data</code>: This is the value <code>str</code> as a <code>void*</code> pointer.</li>
<li><code>[in] finalize_hint</code>: This is the value <code>finalize_hint</code> that was given
to the API.
<a href="#all_n-api_napi_finalize"><code>napi_finalize</code></a> provides more details.
This parameter is optional. Passing a null value means that the add-on
doesn't need to be notified when the corresponding JavaScript string is
collected.</li>
</ul>
</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>string</code>.</li>
<li><code>[out] copied</code>: Whether the string was copied. If it was, the finalizer will
already have been invoked to destroy <code>str</code>.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API creates a JavaScript <code>string</code> value from a UTF16-LE-encoded C string.
The native string may not be copied and must thus exist for the entire life
cycle of the JavaScript value.</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>
<h5><code>napi_create_string_utf8</code><span><a class="mark" href="#all_n-api_napi_create_string_utf8" id="all_n-api_napi_create_string_utf8">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_string_utf8"></a></h5>
<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 <span class="hljs-title function_">napi_create_string_utf8</span><span class="hljs-params">(napi_env env,
                                    <span class="hljs-type">const</span> <span class="hljs-type">char</span>* str,
                                    <span class="hljs-type">size_t</span> length,
                                    napi_value* result)</span></code> <button class="copy-button">copy</button></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> value 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>
<h4>Functions to create optimized property keys<span><a class="mark" href="#all_n-api_functions-to-create-optimized-property-keys" id="all_n-api_functions-to-create-optimized-property-keys">#</a></span><a aria-hidden="true" class="legacy" id="n_api_functions_to_create_optimized_property_keys"></a></h4>
<p>Many JavaScript engines including V8 use internalized strings as keys
to set and get property values. They typically use a hash table to create
and lookup such strings. While it adds some cost per key creation, it improves
the performance after that by enabling comparison of string pointers instead
of the whole strings.</p>
<p>If a new JavaScript string is intended to be used as a property key, then for
some JavaScript engines it will be more efficient to use the functions in this
section. Otherwise, use the <code>napi_create_string_utf8</code> or
<code>node_api_create_external_string_utf8</code> series functions as there may be
additional overhead in creating/storing strings with the property key
creation methods.</p>
<h5><code>node_api_create_property_key_latin1</code><span><a class="mark" href="#all_n-api_node_api_create_property_key_latin1" id="all_n-api_node_api_create_property_key_latin1">#</a></span><a aria-hidden="true" class="legacy" id="n_api_node_api_create_property_key_latin1"></a></h5>
<div class="api_metadata">
<span>Added in: v20.18.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<pre><code class="language-c">napi_status NAPI_CDECL <span class="hljs-title function_">node_api_create_property_key_latin1</span><span class="hljs-params">(napi_env env,
                                                           <span class="hljs-type">const</span> <span class="hljs-type">char</span>* str,
                                                           <span class="hljs-type">size_t</span> length,
                                                           napi_value* result)</span>;</code> <button class="copy-button">copy</button></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 an optimized JavaScript <code>string</code>
to be used as a property key for objects.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API creates an optimized JavaScript <code>string</code> value from
an ISO-8859-1-encoded C string to be used as a property key for objects.
The native string is copied. In contrast with <code>napi_create_string_latin1</code>,
subsequent calls to this function with the same <code>str</code> pointer may benefit from a speedup
in the creation of the requested <code>napi_value</code>, depending on the engine.</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>
<h5><code>node_api_create_property_key_utf16</code><span><a class="mark" href="#all_n-api_node_api_create_property_key_utf16" id="all_n-api_node_api_create_property_key_utf16">#</a></span><a aria-hidden="true" class="legacy" id="n_api_node_api_create_property_key_utf16"></a></h5>
<div class="api_metadata">
<span>Added in: v20.12.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<pre><code class="language-c">napi_status NAPI_CDECL <span class="hljs-title function_">node_api_create_property_key_utf16</span><span class="hljs-params">(napi_env env,
                                                          <span class="hljs-type">const</span> <span class="hljs-type">char16_t</span>* str,
                                                          <span class="hljs-type">size_t</span> length,
                                                          napi_value* result)</span>;</code> <button class="copy-button">copy</button></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 an optimized JavaScript <code>string</code>
to be used as a property key for objects.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API creates an optimized JavaScript <code>string</code> value from
a UTF16-LE-encoded C string to be used as a property key for objects.
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>
<h5><code>node_api_create_property_key_utf8</code><span><a class="mark" href="#all_n-api_node_api_create_property_key_utf8" id="all_n-api_node_api_create_property_key_utf8">#</a></span><a aria-hidden="true" class="legacy" id="n_api_node_api_create_property_key_utf8"></a></h5>
<div class="api_metadata">
<span>Added in: v20.18.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<pre><code class="language-c">napi_status NAPI_CDECL <span class="hljs-title function_">node_api_create_property_key_utf8</span><span class="hljs-params">(napi_env env,
                                                         <span class="hljs-type">const</span> <span class="hljs-type">char</span>* str,
                                                         <span class="hljs-type">size_t</span> length,
                                                         napi_value* result)</span>;</code> <button class="copy-button">copy</button></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 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 an optimized JavaScript <code>string</code>
to be used as a property key for objects.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API creates an optimized JavaScript <code>string</code> value from
a UTF8-encoded C string to be used as a property key for objects.
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>Functions to convert from Node-API to C types<span><a class="mark" href="#all_n-api_functions-to-convert-from-node-api-to-c-types" id="all_n-api_functions-to-convert-from-node-api-to-c-types">#</a></span><a aria-hidden="true" class="legacy" id="n_api_functions_to_convert_from_node_api_to_c_types"></a></h4>
<h5><code>napi_get_array_length</code><span><a class="mark" href="#all_n-api_napi_get_array_length" id="all_n-api_napi_get_array_length">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_array_length"></a></h5>
<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 <span class="hljs-title function_">napi_get_array_length</span><span class="hljs-params">(napi_env env,
                                  napi_value value,
                                  <span class="hljs-type">uint32_t</span>* result)</span></code> <button class="copy-button">copy</button></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>
<h5><code>napi_get_arraybuffer_info</code><span><a class="mark" href="#all_n-api_napi_get_arraybuffer_info" id="all_n-api_napi_get_arraybuffer_info">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_arraybuffer_info"></a></h5>
<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 <span class="hljs-title function_">napi_get_arraybuffer_info</span><span class="hljs-params">(napi_env env,
                                      napi_value arraybuffer,
                                      <span class="hljs-type">void</span>** data,
                                      <span class="hljs-type">size_t</span>* byte_length)</span></code> <button class="copy-button">copy</button></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="#all_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>
<h5><code>napi_get_buffer_info</code><span><a class="mark" href="#all_n-api_napi_get_buffer_info" id="all_n-api_napi_get_buffer_info">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_buffer_info"></a></h5>
<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 <span class="hljs-title function_">napi_get_buffer_info</span><span class="hljs-params">(napi_env env,
                                 napi_value value,
                                 <span class="hljs-type">void</span>** data,
                                 <span class="hljs-type">size_t</span>* length)</span></code> <button class="copy-button">copy</button></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> or <code>Uint8Array</code>
being queried.</li>
<li><code>[out] data</code>: The underlying data buffer of the <code>node::Buffer</code> or
<code>Uint8Array</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 method returns the identical <code>data</code> and <code>byte_length</code> as
<a href="#all_n-api_napi_get_typedarray_info"><code>napi_get_typedarray_info</code></a>. And <code>napi_get_typedarray_info</code> accepts a
<code>node::Buffer</code> (a Uint8Array) as the value too.</p>
<p>This API is used to retrieve the underlying data buffer of a <code>node::Buffer</code>
and its 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>
<h5><code>napi_get_prototype</code><span><a class="mark" href="#all_n-api_napi_get_prototype" id="all_n-api_napi_get_prototype">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_prototype"></a></h5>
<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 <span class="hljs-title function_">napi_get_prototype</span><span class="hljs-params">(napi_env env,
                               napi_value object,
                               napi_value* result)</span></code> <button class="copy-button">copy</button></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>
<h5><code>napi_get_typedarray_info</code><span><a class="mark" href="#all_n-api_napi_get_typedarray_info" id="all_n-api_napi_get_typedarray_info">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_typedarray_info"></a></h5>
<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 <span class="hljs-title function_">napi_get_typedarray_info</span><span class="hljs-params">(napi_env env,
                                     napi_value typedarray,
                                     napi_typedarray_type* type,
                                     <span class="hljs-type">size_t</span>* length,
                                     <span class="hljs-type">void</span>** data,
                                     napi_value* arraybuffer,
                                     <span class="hljs-type">size_t</span>* byte_offset)</span></code> <button class="copy-button">copy</button></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>Any of the out parameters may be <code>NULL</code> if that property is unneeded.</p>
<p><em>Warning</em>: Use caution while using this API since the underlying data buffer
is managed by the VM.</p>
<h5><code>napi_get_dataview_info</code><span><a class="mark" href="#all_n-api_napi_get_dataview_info" id="all_n-api_napi_get_dataview_info">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_dataview_info"></a></h5>
<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 <span class="hljs-title function_">napi_get_dataview_info</span><span class="hljs-params">(napi_env env,
                                   napi_value dataview,
                                   <span class="hljs-type">size_t</span>* byte_length,
                                   <span class="hljs-type">void</span>** data,
                                   napi_value* arraybuffer,
                                   <span class="hljs-type">size_t</span>* byte_offset)</span></code> <button class="copy-button">copy</button></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>: Number 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>Any of the out parameters may be <code>NULL</code> if that property is unneeded.</p>
<p>This API returns various properties of a <code>DataView</code>.</p>
<h5><code>napi_get_date_value</code><span><a class="mark" href="#all_n-api_napi_get_date_value" id="all_n-api_napi_get_date_value">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_date_value"></a></h5>
<div class="api_metadata">
<span>Added in: v11.11.0, v10.17.0</span>
<span>N-API version: 5</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_get_date_value</span><span class="hljs-params">(napi_env env,
                                napi_value value,
                                <span class="hljs-type">double</span>* result)</span></code> <button class="copy-button">copy</button></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>
<h5><code>napi_get_value_bool</code><span><a class="mark" href="#all_n-api_napi_get_value_bool" id="all_n-api_napi_get_value_bool">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_value_bool"></a></h5>
<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 <span class="hljs-title function_">napi_get_value_bool</span><span class="hljs-params">(napi_env env, napi_value value, <span class="hljs-type">bool</span>* result)</span></code> <button class="copy-button">copy</button></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>
<h5><code>napi_get_value_double</code><span><a class="mark" href="#all_n-api_napi_get_value_double" id="all_n-api_napi_get_value_double">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_value_double"></a></h5>
<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 <span class="hljs-title function_">napi_get_value_double</span><span class="hljs-params">(napi_env env,
                                  napi_value value,
                                  <span class="hljs-type">double</span>* result)</span></code> <button class="copy-button">copy</button></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>
<h5><code>napi_get_value_bigint_int64</code><span><a class="mark" href="#all_n-api_napi_get_value_bigint_int64" id="all_n-api_napi_get_value_bigint_int64">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_value_bigint_int64"></a></h5>
<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 <span class="hljs-title function_">napi_get_value_bigint_int64</span><span class="hljs-params">(napi_env env,
                                        napi_value value,
                                        <span class="hljs-type">int64_t</span>* result,
                                        <span class="hljs-type">bool</span>* lossless)</span>;</code> <button class="copy-button">copy</button></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>
<h5><code>napi_get_value_bigint_uint64</code><span><a class="mark" href="#all_n-api_napi_get_value_bigint_uint64" id="all_n-api_napi_get_value_bigint_uint64">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_value_bigint_uint64"></a></h5>
<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 <span class="hljs-title function_">napi_get_value_bigint_uint64</span><span class="hljs-params">(napi_env env,
                                        napi_value value,
                                        <span class="hljs-type">uint64_t</span>* result,
                                        <span class="hljs-type">bool</span>* lossless)</span>;</code> <button class="copy-button">copy</button></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>
<h5><code>napi_get_value_bigint_words</code><span><a class="mark" href="#all_n-api_napi_get_value_bigint_words" id="all_n-api_napi_get_value_bigint_words">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_value_bigint_words"></a></h5>
<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 <span class="hljs-title function_">napi_get_value_bigint_words</span><span class="hljs-params">(napi_env env,
                                        napi_value value,
                                        <span class="hljs-type">int</span>* sign_bit,
                                        <span class="hljs-type">size_t</span>* word_count,
                                        <span class="hljs-type">uint64_t</span>* words)</span>;</code> <button class="copy-button">copy</button></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>
<h5><code>napi_get_value_external</code><span><a class="mark" href="#all_n-api_napi_get_value_external" id="all_n-api_napi_get_value_external">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_value_external"></a></h5>
<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 <span class="hljs-title function_">napi_get_value_external</span><span class="hljs-params">(napi_env env,
                                    napi_value value,
                                    <span class="hljs-type">void</span>** result)</span></code> <button class="copy-button">copy</button></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>
<h5><code>napi_get_value_int32</code><span><a class="mark" href="#all_n-api_napi_get_value_int32" id="all_n-api_napi_get_value_int32">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_value_int32"></a></h5>
<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 <span class="hljs-title function_">napi_get_value_int32</span><span class="hljs-params">(napi_env env,
                                 napi_value value,
                                 <span class="hljs-type">int32_t</span>* result)</span></code> <button class="copy-button">copy</button></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<sup>31</sup> - 1.</p>
<p>Non-finite number values (<code>NaN</code>, <code>+Infinity</code>, or <code>-Infinity</code>) set the
result to zero.</p>
<h5><code>napi_get_value_int64</code><span><a class="mark" href="#all_n-api_napi_get_value_int64" id="all_n-api_napi_get_value_int64">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_value_int64"></a></h5>
<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 <span class="hljs-title function_">napi_get_value_int64</span><span class="hljs-params">(napi_env env,
                                 napi_value value,
                                 <span class="hljs-type">int64_t</span>* result)</span></code> <button class="copy-button">copy</button></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>
<h5><code>napi_get_value_string_latin1</code><span><a class="mark" href="#all_n-api_napi_get_value_string_latin1" id="all_n-api_napi_get_value_string_latin1">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_value_string_latin1"></a></h5>
<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 <span class="hljs-title function_">napi_get_value_string_latin1</span><span class="hljs-params">(napi_env env,
                                         napi_value value,
                                         <span class="hljs-type">char</span>* buf,
                                         <span class="hljs-type">size_t</span> bufsize,
                                         <span class="hljs-type">size_t</span>* result)</span></code> <button class="copy-button">copy</button></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 and excluding the null terminator
is returned in <code>result</code>.</li>
<li><code>[in] bufsize</code>: Size of the destination buffer. When this value is
insufficient, the returned string is truncated and null-terminated.</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>
<h5><code>napi_get_value_string_utf8</code><span><a class="mark" href="#all_n-api_napi_get_value_string_utf8" id="all_n-api_napi_get_value_string_utf8">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_value_string_utf8"></a></h5>
<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 <span class="hljs-title function_">napi_get_value_string_utf8</span><span class="hljs-params">(napi_env env,
                                       napi_value value,
                                       <span class="hljs-type">char</span>* buf,
                                       <span class="hljs-type">size_t</span> bufsize,
                                       <span class="hljs-type">size_t</span>* result)</span></code> <button class="copy-button">copy</button></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 and excluding the null terminator is
returned in <code>result</code>.</li>
<li><code>[in] bufsize</code>: Size of the destination buffer. When this value is
insufficient, the returned string is truncated and null-terminated.</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>
<h5><code>napi_get_value_string_utf16</code><span><a class="mark" href="#all_n-api_napi_get_value_string_utf16" id="all_n-api_napi_get_value_string_utf16">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_value_string_utf16"></a></h5>
<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 <span class="hljs-title function_">napi_get_value_string_utf16</span><span class="hljs-params">(napi_env env,
                                        napi_value value,
                                        <span class="hljs-type">char16_t</span>* buf,
                                        <span class="hljs-type">size_t</span> bufsize,
                                        <span class="hljs-type">size_t</span>* result)</span></code> <button class="copy-button">copy</button></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 and excluding the
null terminator is returned.</li>
<li><code>[in] bufsize</code>: Size of the destination buffer. When this value is
insufficient, the returned string is truncated and null-terminated.</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>
<h5><code>napi_get_value_uint32</code><span><a class="mark" href="#all_n-api_napi_get_value_uint32" id="all_n-api_napi_get_value_uint32">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_value_uint32"></a></h5>
<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 <span class="hljs-title function_">napi_get_value_uint32</span><span class="hljs-params">(napi_env env,
                                  napi_value value,
                                  <span class="hljs-type">uint32_t</span>* result)</span></code> <button class="copy-button">copy</button></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>
<h4>Functions to get global instances<span><a class="mark" href="#all_n-api_functions-to-get-global-instances" id="all_n-api_functions-to-get-global-instances">#</a></span><a aria-hidden="true" class="legacy" id="n_api_functions_to_get_global_instances"></a></h4>
<h5><code>napi_get_boolean</code><span><a class="mark" href="#all_n-api_napi_get_boolean" id="all_n-api_napi_get_boolean">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_boolean"></a></h5>
<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 <span class="hljs-title function_">napi_get_boolean</span><span class="hljs-params">(napi_env env, <span class="hljs-type">bool</span> value, napi_value* result)</span></code> <button class="copy-button">copy</button></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>
<h5><code>napi_get_global</code><span><a class="mark" href="#all_n-api_napi_get_global" id="all_n-api_napi_get_global">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_global"></a></h5>
<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 <span class="hljs-title function_">napi_get_global</span><span class="hljs-params">(napi_env env, napi_value* result)</span></code> <button class="copy-button">copy</button></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>
<h5><code>napi_get_null</code><span><a class="mark" href="#all_n-api_napi_get_null" id="all_n-api_napi_get_null">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_null"></a></h5>
<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 <span class="hljs-title function_">napi_get_null</span><span class="hljs-params">(napi_env env, napi_value* result)</span></code> <button class="copy-button">copy</button></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>
<h5><code>napi_get_undefined</code><span><a class="mark" href="#all_n-api_napi_get_undefined" id="all_n-api_napi_get_undefined">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_undefined"></a></h5>
<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 <span class="hljs-title function_">napi_get_undefined</span><span class="hljs-params">(napi_env env, napi_value* result)</span></code> <button class="copy-button">copy</button></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>
</section><section><h3>Working with JavaScript values and abstract operations<span><a class="mark" href="#all_n-api_working-with-javascript-values-and-abstract-operations" id="all_n-api_working-with-javascript-values-and-abstract-operations">#</a></span><a aria-hidden="true" class="legacy" id="n_api_working_with_javascript_values_and_abstract_operations"></a></h3>
<p>Node-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>
<h4><code>napi_coerce_to_bool</code><span><a class="mark" href="#all_n-api_napi_coerce_to_bool" id="all_n-api_napi_coerce_to_bool">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_coerce_to_bool"></a></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 <span class="hljs-title function_">napi_coerce_to_bool</span><span class="hljs-params">(napi_env env,
                                napi_value value,
                                napi_value* result)</span></code> <button class="copy-button">copy</button></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.</p>
<h4><code>napi_coerce_to_number</code><span><a class="mark" href="#all_n-api_napi_coerce_to_number" id="all_n-api_napi_coerce_to_number">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_coerce_to_number"></a></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 <span class="hljs-title function_">napi_coerce_to_number</span><span class="hljs-params">(napi_env env,
                                  napi_value value,
                                  napi_value* result)</span></code> <button class="copy-button">copy</button></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 function potentially runs JS code if the passed-in value is an
object.</p>
<h4><code>napi_coerce_to_object</code><span><a class="mark" href="#all_n-api_napi_coerce_to_object" id="all_n-api_napi_coerce_to_object">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_coerce_to_object"></a></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 <span class="hljs-title function_">napi_coerce_to_object</span><span class="hljs-params">(napi_env env,
                                  napi_value value,
                                  napi_value* result)</span></code> <button class="copy-button">copy</button></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.</p>
<h4><code>napi_coerce_to_string</code><span><a class="mark" href="#all_n-api_napi_coerce_to_string" id="all_n-api_napi_coerce_to_string">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_coerce_to_string"></a></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 <span class="hljs-title function_">napi_coerce_to_string</span><span class="hljs-params">(napi_env env,
                                  napi_value value,
                                  napi_value* result)</span></code> <button class="copy-button">copy</button></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 function potentially runs JS code if the passed-in value is an
object.</p>
<h4><code>napi_typeof</code><span><a class="mark" href="#all_n-api_napi_typeof" id="all_n-api_napi_typeof">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_typeof"></a></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 <span class="hljs-title function_">napi_typeof</span><span class="hljs-params">(napi_env env, napi_value value, napi_valuetype* result)</span></code> <button class="copy-button">copy</button></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, there are some differences:</p>
<ol>
<li>It has support for detecting an External value.</li>
<li>It detects <code>null</code> as a separate type, while ECMAScript <code>typeof</code> would detect
<code>object</code>.</li>
</ol>
<p>If <code>value</code> has a type that is invalid, an error is returned.</p>
<h4><code>napi_instanceof</code><span><a class="mark" href="#all_n-api_napi_instanceof" id="all_n-api_napi_instanceof">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_instanceof"></a></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 <span class="hljs-title function_">napi_instanceof</span><span class="hljs-params">(napi_env env,
                            napi_value object,
                            napi_value constructor,
                            <span class="hljs-type">bool</span>* result)</span></code> <button class="copy-button">copy</button></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>
<h4><code>napi_is_array</code><span><a class="mark" href="#all_n-api_napi_is_array" id="all_n-api_napi_is_array">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_is_array"></a></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 <span class="hljs-title function_">napi_is_array</span><span class="hljs-params">(napi_env env, napi_value value, <span class="hljs-type">bool</span>* result)</span></code> <button class="copy-button">copy</button></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>
<h4><code>napi_is_arraybuffer</code><span><a class="mark" href="#all_n-api_napi_is_arraybuffer" id="all_n-api_napi_is_arraybuffer">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_is_arraybuffer"></a></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 <span class="hljs-title function_">napi_is_arraybuffer</span><span class="hljs-params">(napi_env env, napi_value value, <span class="hljs-type">bool</span>* result)</span></code> <button class="copy-button">copy</button></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>
<h4><code>napi_is_buffer</code><span><a class="mark" href="#all_n-api_napi_is_buffer" id="all_n-api_napi_is_buffer">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_is_buffer"></a></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 <span class="hljs-title function_">napi_is_buffer</span><span class="hljs-params">(napi_env env, napi_value value, <span class="hljs-type">bool</span>* result)</span></code> <button class="copy-button">copy</button></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> or
<code>Uint8Array</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 or Uint8Array.
<a href="#all_n-api_napi_is_typedarray"><code>napi_is_typedarray</code></a> should be preferred if the caller needs to check if the
value is a Uint8Array.</p>
<h4><code>napi_is_date</code><span><a class="mark" href="#all_n-api_napi_is_date" id="all_n-api_napi_is_date">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_is_date"></a></h4>
<div class="api_metadata">
<span>Added in: v11.11.0, v10.17.0</span>
<span>N-API version: 5</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_is_date</span><span class="hljs-params">(napi_env env, napi_value value, <span class="hljs-type">bool</span>* result)</span></code> <button class="copy-button">copy</button></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>
<h4><code>napi_is_error</code><span><a class="mark" href="#all_n-api_napi_is_error_1" id="all_n-api_napi_is_error_1">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_is_error_1"></a></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 <span class="hljs-title function_">napi_is_error</span><span class="hljs-params">(napi_env env, napi_value value, <span class="hljs-type">bool</span>* result)</span></code> <button class="copy-button">copy</button></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>
<h4><code>napi_is_typedarray</code><span><a class="mark" href="#all_n-api_napi_is_typedarray" id="all_n-api_napi_is_typedarray">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_is_typedarray"></a></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 <span class="hljs-title function_">napi_is_typedarray</span><span class="hljs-params">(napi_env env, napi_value value, <span class="hljs-type">bool</span>* result)</span></code> <button class="copy-button">copy</button></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>
<h4><code>napi_is_dataview</code><span><a class="mark" href="#all_n-api_napi_is_dataview" id="all_n-api_napi_is_dataview">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_is_dataview"></a></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 <span class="hljs-title function_">napi_is_dataview</span><span class="hljs-params">(napi_env env, napi_value value, <span class="hljs-type">bool</span>* result)</span></code> <button class="copy-button">copy</button></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>
<h4><code>napi_strict_equals</code><span><a class="mark" href="#all_n-api_napi_strict_equals" id="all_n-api_napi_strict_equals">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_strict_equals"></a></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 <span class="hljs-title function_">napi_strict_equals</span><span class="hljs-params">(napi_env env,
                               napi_value lhs,
                               napi_value rhs,
                               <span class="hljs-type">bool</span>* result)</span></code> <button class="copy-button">copy</button></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>
<h4><code>napi_detach_arraybuffer</code><span><a class="mark" href="#all_n-api_napi_detach_arraybuffer" id="all_n-api_napi_detach_arraybuffer">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_detach_arraybuffer"></a></h4>
<div class="api_metadata">
<span>Added in: v13.0.0, v12.16.0, v10.22.0</span>
<span>N-API version: 7</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_detach_arraybuffer</span><span class="hljs-params">(napi_env env,
                                    napi_value arraybuffer)</span></code> <button class="copy-button">copy</button></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="#all_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>
<h4><code>napi_is_detached_arraybuffer</code><span><a class="mark" href="#all_n-api_napi_is_detached_arraybuffer" id="all_n-api_napi_is_detached_arraybuffer">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_is_detached_arraybuffer"></a></h4>
<div class="api_metadata">
<span>Added in: v13.3.0, v12.16.0, v10.22.0</span>
<span>N-API version: 7</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_is_detached_arraybuffer</span><span class="hljs-params">(napi_env env,
                                         napi_value arraybuffer,
                                         <span class="hljs-type">bool</span>* result)</span></code> <button class="copy-button">copy</button></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>
</section><section><h3>Working with JavaScript properties<span><a class="mark" href="#all_n-api_working-with-javascript-properties" id="all_n-api_working-with-javascript-properties">#</a></span><a aria-hidden="true" class="legacy" id="n_api_working_with_javascript_properties"></a></h3>
<p>Node-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 Node-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 Node-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>Node-API values are represented by the type <code>napi_value</code>.
Any Node-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"><span class="hljs-keyword">const</span> obj = {};
obj.<span class="hljs-property">myProp</span> = <span class="hljs-number">123</span>;</code> <button class="copy-button">copy</button></pre>
<p>The equivalent can be done using Node-API values with the following snippet:</p>
<pre><code class="language-c">napi_status status = napi_generic_failure;

<span class="hljs-comment">// const obj = {}</span>
napi_value obj, value;
status = napi_create_object(env, &#x26;obj);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> status;

<span class="hljs-comment">// Create a napi_value for 123</span>
status = napi_create_int32(env, <span class="hljs-number">123</span>, &#x26;value);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> status;

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

<span class="hljs-comment">// const arr = [];</span>
napi_value arr, value;
status = napi_create_array(env, &#x26;arr);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> status;

<span class="hljs-comment">// Create a napi_value for 'hello'</span>
status = napi_create_string_utf8(env, <span class="hljs-string">"hello"</span>, NAPI_AUTO_LENGTH, &#x26;value);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> status;

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

<span class="hljs-comment">// const arr = []</span>
napi_value arr, value;
status = napi_create_array(env, &#x26;arr);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> status;

<span class="hljs-comment">// const value = arr[123]</span>
status = napi_get_element(env, arr, <span class="hljs-number">123</span>, &#x26;value);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> status;</code> <button class="copy-button">copy</button></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"><span class="hljs-keyword">const</span> obj = {};
<span class="hljs-title class_">Object</span>.<span class="hljs-title function_">defineProperties</span>(obj, {
  <span class="hljs-string">'foo'</span>: { <span class="hljs-attr">value</span>: <span class="hljs-number">123</span>, <span class="hljs-attr">writable</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">configurable</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">enumerable</span>: <span class="hljs-literal">true</span> },
  <span class="hljs-string">'bar'</span>: { <span class="hljs-attr">value</span>: <span class="hljs-number">456</span>, <span class="hljs-attr">writable</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">configurable</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">enumerable</span>: <span class="hljs-literal">true</span> },
});</code> <button class="copy-button">copy</button></pre>
<p>The following is the approximate equivalent of the Node-API counterpart:</p>
<pre><code class="language-c">napi_status status = napi_status_generic_failure;

<span class="hljs-comment">// const obj = {};</span>
napi_value obj;
status = napi_create_object(env, &#x26;obj);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> status;

<span class="hljs-comment">// Create napi_values for 123 and 456</span>
napi_value fooValue, barValue;
status = napi_create_int32(env, <span class="hljs-number">123</span>, &#x26;fooValue);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> status;
status = napi_create_int32(env, <span class="hljs-number">456</span>, &#x26;barValue);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> status;

<span class="hljs-comment">// Set the properties</span>
napi_property_descriptor descriptors[] = {
  { <span class="hljs-string">"foo"</span>, <span class="hljs-literal">NULL</span>, <span class="hljs-literal">NULL</span>, <span class="hljs-literal">NULL</span>, <span class="hljs-literal">NULL</span>, fooValue, napi_writable | napi_configurable, <span class="hljs-literal">NULL</span> },
  { <span class="hljs-string">"bar"</span>, <span class="hljs-literal">NULL</span>, <span class="hljs-literal">NULL</span>, <span class="hljs-literal">NULL</span>, <span class="hljs-literal">NULL</span>, barValue, napi_writable | napi_configurable, <span class="hljs-literal">NULL</span> }
}
status = napi_define_properties(env,
                                obj,
                                <span class="hljs-keyword">sizeof</span>(descriptors) / <span class="hljs-keyword">sizeof</span>(descriptors[<span class="hljs-number">0</span>]),
                                descriptors);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> status;</code> <button class="copy-button">copy</button></pre>
<h4>Structures<span><a class="mark" href="#all_n-api_structures" id="all_n-api_structures">#</a></span><a aria-hidden="true" class="legacy" id="n_api_structures"></a></h4>
<h5><code>napi_property_attributes</code><span><a class="mark" href="#all_n-api_napi_property_attributes" id="all_n-api_napi_property_attributes">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_property_attributes"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.12.0</td>
<td><p>added <code>napi_default_method</code> and <code>napi_default_property</code>.</p></td></tr>
</tbody></table>
</details>
</div>
<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> {</span>
  napi_default = <span class="hljs-number">0</span>,
  napi_writable = <span class="hljs-number">1</span> &#x3C;&#x3C; <span class="hljs-number">0</span>,
  napi_enumerable = <span class="hljs-number">1</span> &#x3C;&#x3C; <span class="hljs-number">1</span>,
  napi_configurable = <span class="hljs-number">1</span> &#x3C;&#x3C; <span class="hljs-number">2</span>,

  <span class="hljs-comment">// Used with napi_define_class to distinguish static properties</span>
  <span class="hljs-comment">// from instance properties. Ignored by napi_define_properties.</span>
  napi_static = <span class="hljs-number">1</span> &#x3C;&#x3C; <span class="hljs-number">10</span>,

  <span class="hljs-comment">// Default for class methods.</span>
  napi_default_method = napi_writable | napi_configurable,

  <span class="hljs-comment">// Default for object properties, like in JS obj[prop].</span>
  napi_default_jsproperty = napi_writable |
                          napi_enumerable |
                          napi_configurable,
} napi_property_attributes;</code> <button class="copy-button">copy</button></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="#all_n-api_napi_define_class"><code>napi_define_class</code></a>. It is ignored by <code>napi_define_properties</code>.</li>
<li><code>napi_default_method</code>: Like a method in a JS class, the property is
configurable and writeable, but not enumerable.</li>
<li><code>napi_default_jsproperty</code>: Like a property set via assignment in JavaScript,
the property is writable, enumerable, and configurable.</li>
</ul>
<h5><code>napi_property_descriptor</code><span><a class="mark" href="#all_n-api_napi_property_descriptor" id="all_n-api_napi_property_descriptor">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_property_descriptor"></a></h5>
<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> {</span>
  <span class="hljs-comment">// One of utf8name or name should be NULL.</span>
  <span class="hljs-type">const</span> <span class="hljs-type">char</span>* utf8name;
  napi_value name;

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

  napi_property_attributes attributes;
  <span class="hljs-type">void</span>* data;
} napi_property_descriptor;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>utf8name</code>: Optional string describing the key for the property,
encoded as UTF8. One of <code>utf8name</code> or <code>name</code> must be provided for the
property.</li>
<li><code>name</code>: Optional <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 Node-API call). <a href="#all_n-api_napi_callback"><code>napi_callback</code></a> provides more details.</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 Node-API call). <a href="#all_n-api_napi_callback"><code>napi_callback</code></a> provides more details.</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). <a href="#all_n-api_napi_callback"><code>napi_callback</code></a> provides more details.</li>
<li><code>attributes</code>: The attributes associated with the particular property. See
<a href="#all_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>
<h4>Functions<span><a class="mark" href="#all_n-api_functions" id="all_n-api_functions">#</a></span><a aria-hidden="true" class="legacy" id="n_api_functions"></a></h4>
<h5><code>napi_get_property_names</code><span><a class="mark" href="#all_n-api_napi_get_property_names" id="all_n-api_napi_get_property_names">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_property_names"></a></h5>
<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 <span class="hljs-title function_">napi_get_property_names</span><span class="hljs-params">(napi_env env,
                                    napi_value object,
                                    napi_value* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the Node-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="#all_n-api_napi_get_array_length"><code>napi_get_array_length</code></a>
and <a href="#all_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>
<h5><code>napi_get_all_property_names</code><span><a class="mark" href="#all_n-api_napi_get_all_property_names" id="all_n-api_napi_get_all_property_names">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_all_property_names"></a></h5>
<div class="api_metadata">
<span>Added in: v13.7.0, v12.17.0, v10.20.0</span>
<span>N-API version: 6</span>
</div>
<pre><code class="language-c">napi_get_all_property_names(napi_env env,
                            napi_value object,
                            napi_key_collection_mode key_mode,
                            napi_key_filter key_filter,
                            napi_key_conversion key_conversion,
                            napi_value* result);</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the Node-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="#all_n-api_napi_get_array_length"><code>napi_get_array_length</code></a>
and <a href="#all_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>
<h5><code>napi_set_property</code><span><a class="mark" href="#all_n-api_napi_set_property" id="all_n-api_napi_set_property">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_set_property"></a></h5>
<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 <span class="hljs-title function_">napi_set_property</span><span class="hljs-params">(napi_env env,
                              napi_value object,
                              napi_value key,
                              napi_value value)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the Node-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>
<h5><code>napi_get_property</code><span><a class="mark" href="#all_n-api_napi_get_property" id="all_n-api_napi_get_property">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_property"></a></h5>
<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 <span class="hljs-title function_">napi_get_property</span><span class="hljs-params">(napi_env env,
                              napi_value object,
                              napi_value key,
                              napi_value* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the Node-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>
<h5><code>napi_has_property</code><span><a class="mark" href="#all_n-api_napi_has_property" id="all_n-api_napi_has_property">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_has_property"></a></h5>
<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 <span class="hljs-title function_">napi_has_property</span><span class="hljs-params">(napi_env env,
                              napi_value object,
                              napi_value key,
                              <span class="hljs-type">bool</span>* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the Node-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>
<h5><code>napi_delete_property</code><span><a class="mark" href="#all_n-api_napi_delete_property" id="all_n-api_napi_delete_property">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_delete_property"></a></h5>
<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 <span class="hljs-title function_">napi_delete_property</span><span class="hljs-params">(napi_env env,
                                 napi_value object,
                                 napi_value key,
                                 <span class="hljs-type">bool</span>* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the Node-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>
<h5><code>napi_has_own_property</code><span><a class="mark" href="#all_n-api_napi_has_own_property" id="all_n-api_napi_has_own_property">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_has_own_property"></a></h5>
<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 <span class="hljs-title function_">napi_has_own_property</span><span class="hljs-params">(napi_env env,
                                  napi_value object,
                                  napi_value key,
                                  <span class="hljs-type">bool</span>* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the Node-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 <code>string</code> or a <code>symbol</code>, or an error will be thrown. Node-API will not
perform any conversion between data types.</p>
<h5><code>napi_set_named_property</code><span><a class="mark" href="#all_n-api_napi_set_named_property" id="all_n-api_napi_set_named_property">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_set_named_property"></a></h5>
<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 <span class="hljs-title function_">napi_set_named_property</span><span class="hljs-params">(napi_env env,
                                    napi_value object,
                                    <span class="hljs-type">const</span> <span class="hljs-type">char</span>* utf8Name,
                                    napi_value value)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the Node-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="#all_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>
<h5><code>napi_get_named_property</code><span><a class="mark" href="#all_n-api_napi_get_named_property" id="all_n-api_napi_get_named_property">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_named_property"></a></h5>
<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 <span class="hljs-title function_">napi_get_named_property</span><span class="hljs-params">(napi_env env,
                                    napi_value object,
                                    <span class="hljs-type">const</span> <span class="hljs-type">char</span>* utf8Name,
                                    napi_value* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the Node-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="#all_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>
<h5><code>napi_has_named_property</code><span><a class="mark" href="#all_n-api_napi_has_named_property" id="all_n-api_napi_has_named_property">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_has_named_property"></a></h5>
<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 <span class="hljs-title function_">napi_has_named_property</span><span class="hljs-params">(napi_env env,
                                    napi_value object,
                                    <span class="hljs-type">const</span> <span class="hljs-type">char</span>* utf8Name,
                                    <span class="hljs-type">bool</span>* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the Node-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="#all_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>
<h5><code>napi_set_element</code><span><a class="mark" href="#all_n-api_napi_set_element" id="all_n-api_napi_set_element">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_set_element"></a></h5>
<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 <span class="hljs-title function_">napi_set_element</span><span class="hljs-params">(napi_env env,
                             napi_value object,
                             <span class="hljs-type">uint32_t</span> index,
                             napi_value value)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the Node-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 an element on the <code>Object</code> passed in.</p>
<h5><code>napi_get_element</code><span><a class="mark" href="#all_n-api_napi_get_element" id="all_n-api_napi_get_element">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_element"></a></h5>
<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 <span class="hljs-title function_">napi_get_element</span><span class="hljs-params">(napi_env env,
                             napi_value object,
                             <span class="hljs-type">uint32_t</span> index,
                             napi_value* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the Node-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>
<h5><code>napi_has_element</code><span><a class="mark" href="#all_n-api_napi_has_element" id="all_n-api_napi_has_element">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_has_element"></a></h5>
<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 <span class="hljs-title function_">napi_has_element</span><span class="hljs-params">(napi_env env,
                             napi_value object,
                             <span class="hljs-type">uint32_t</span> index,
                             <span class="hljs-type">bool</span>* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the Node-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>
<h5><code>napi_delete_element</code><span><a class="mark" href="#all_n-api_napi_delete_element" id="all_n-api_napi_delete_element">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_delete_element"></a></h5>
<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 <span class="hljs-title function_">napi_delete_element</span><span class="hljs-params">(napi_env env,
                                napi_value object,
                                <span class="hljs-type">uint32_t</span> index,
                                <span class="hljs-type">bool</span>* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the Node-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>
<h5><code>napi_define_properties</code><span><a class="mark" href="#all_n-api_napi_define_properties" id="all_n-api_napi_define_properties">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_define_properties"></a></h5>
<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 <span class="hljs-title function_">napi_define_properties</span><span class="hljs-params">(napi_env env,
                                   napi_value object,
                                   <span class="hljs-type">size_t</span> property_count,
                                   <span class="hljs-type">const</span> napi_property_descriptor* properties)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the Node-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="#all_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>
<h5><code>napi_object_freeze</code><span><a class="mark" href="#all_n-api_napi_object_freeze" id="all_n-api_napi_object_freeze">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_object_freeze"></a></h5>
<div class="api_metadata">
<span>Added in: v14.14.0, v12.20.0</span>
<span>N-API version: 8</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_object_freeze</span><span class="hljs-params">(napi_env env,
                               napi_value object)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
<li><code>[in] object</code>: The object to freeze.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This method freezes a given object. This prevents new properties from
being added to it, existing properties from being removed, prevents
changing the enumerability, configurability, or writability of existing
properties, and prevents the values of existing properties from being changed.
It also prevents the object's prototype from being changed. This is described
in <a href="https://tc39.es/ecma262/#sec-object.freeze">Section 19.1.2.6</a> of the
ECMA-262 specification.</p>
<h5><code>napi_object_seal</code><span><a class="mark" href="#all_n-api_napi_object_seal" id="all_n-api_napi_object_seal">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_object_seal"></a></h5>
<div class="api_metadata">
<span>Added in: v14.14.0, v12.20.0</span>
<span>N-API version: 8</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_object_seal</span><span class="hljs-params">(napi_env env,
                             napi_value object)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the Node-API call is invoked under.</li>
<li><code>[in] object</code>: The object to seal.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This method seals a given object. This prevents new properties from being
added to it, as well as marking all existing properties as non-configurable.
This is described in <a href="https://tc39.es/ecma262/#sec-object.seal">Section 19.1.2.20</a>
of the ECMA-262 specification.</p>
</section><section><h3>Working with JavaScript functions<span><a class="mark" href="#all_n-api_working-with-javascript-functions" id="all_n-api_working-with-javascript-functions">#</a></span><a aria-hidden="true" class="legacy" id="n_api_working_with_javascript_functions"></a></h3>
<p>Node-API provides a set of APIs that allow JavaScript code to
call back into native code. Node-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, Node-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="#all_n-api_napi_add_finalizer"><code>napi_add_finalizer</code></a>.</p>
<h4><code>napi_call_function</code><span><a class="mark" href="#all_n-api_napi_call_function" id="all_n-api_napi_call_function">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_call_function"></a></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 <span class="hljs-title function_">napi_call_function</span><span class="hljs-params">(napi_env env,
                                           napi_value recv,
                                           napi_value func,
                                           <span class="hljs-type">size_t</span> argc,
                                           <span class="hljs-type">const</span> napi_value* argv,
                                           napi_value* result)</span>;</code> <button class="copy-button">copy</button></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> value 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="#all_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"><span class="hljs-keyword">function</span> <span class="hljs-title function_">AddTwo</span>(<span class="hljs-params">num</span>) {
  <span class="hljs-keyword">return</span> num + <span class="hljs-number">2</span>;
}
<span class="hljs-variable language_">global</span>.<span class="hljs-property">AddTwo</span> = <span class="hljs-title class_">AddTwo</span>;</code> <button class="copy-button">copy</button></pre>
<p>Then, the above function can be invoked from a native add-on using the
following code:</p>
<pre><code class="language-c"><span class="hljs-comment">// Get the function named "AddTwo" on the global object</span>
napi_value global, add_two, arg;
napi_status status = napi_get_global(env, &#x26;global);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span>;

status = napi_get_named_property(env, global, <span class="hljs-string">"AddTwo"</span>, &#x26;add_two);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span>;

<span class="hljs-comment">// const arg = 1337</span>
status = napi_create_int32(env, <span class="hljs-number">1337</span>, &#x26;arg);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span>;

napi_value* argv = &#x26;arg;
<span class="hljs-type">size_t</span> argc = <span class="hljs-number">1</span>;

<span class="hljs-comment">// AddTwo(arg);</span>
napi_value return_val;
status = napi_call_function(env, global, add_two, argc, argv, &#x26;return_val);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span>;

<span class="hljs-comment">// Convert the result back to a native type</span>
<span class="hljs-type">int32_t</span> result;
status = napi_get_value_int32(env, return_val, &#x26;result);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span>;</code> <button class="copy-button">copy</button></pre>
<h4><code>napi_create_function</code><span><a class="mark" href="#all_n-api_napi_create_function" id="all_n-api_napi_create_function">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_function"></a></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 <span class="hljs-title function_">napi_create_function</span><span class="hljs-params">(napi_env env,
                                 <span class="hljs-type">const</span> <span class="hljs-type">char</span>* utf8name,
                                 <span class="hljs-type">size_t</span> length,
                                 napi_callback cb,
                                 <span class="hljs-type">void</span>* data,
                                 napi_value* result)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] utf8Name</code>: Optional 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. <a href="#all_n-api_napi_callback"><code>napi_callback</code></a> provides more details.</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 <span class="hljs-title function_">SayHello</span><span class="hljs-params">(napi_env env, napi_callback_info info)</span> {
  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"Hello\n"</span>);
  <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
}

napi_value <span class="hljs-title function_">Init</span><span class="hljs-params">(napi_env env, napi_value exports)</span> {
  napi_status status;

  napi_value fn;
  status = napi_create_function(env, <span class="hljs-literal">NULL</span>, <span class="hljs-number">0</span>, SayHello, <span class="hljs-literal">NULL</span>, &#x26;fn);
  <span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;

  status = napi_set_named_property(env, exports, <span class="hljs-string">"sayHello"</span>, fn);
  <span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;

  <span class="hljs-keyword">return</span> exports;
}

NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)</code> <button class="copy-button">copy</button></pre>
<p>Given the above code, the add-on can be used from JavaScript as follows:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> myaddon = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./addon'</span>);
myaddon.<span class="hljs-title function_">sayHello</span>();</code> <button class="copy-button">copy</button></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="#all_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>
<h4><code>napi_get_cb_info</code><span><a class="mark" href="#all_n-api_napi_get_cb_info" id="all_n-api_napi_get_cb_info">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_cb_info"></a></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 <span class="hljs-title function_">napi_get_cb_info</span><span class="hljs-params">(napi_env env,
                             napi_callback_info cbinfo,
                             <span class="hljs-type">size_t</span>* argc,
                             napi_value* argv,
                             napi_value* thisArg,
                             <span class="hljs-type">void</span>** data)</span></code> <button class="copy-button">copy</button></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 length of the provided <code>argv</code> array and
receives the actual count of arguments. <code>argc</code> can
optionally be ignored by passing <code>NULL</code>.</li>
<li><code>[out] argv</code>: C array of <code>napi_value</code>s to which the arguments will be
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>. <code>argv</code> can optionally be ignored by
passing <code>NULL</code>.</li>
<li><code>[out] thisArg</code>: Receives the JavaScript <code>this</code> argument for the call.
<code>thisArg</code> can optionally be ignored by passing <code>NULL</code>.</li>
<li><code>[out] data</code>: Receives the data pointer for the callback. <code>data</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 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>
<h4><code>napi_get_new_target</code><span><a class="mark" href="#all_n-api_napi_get_new_target" id="all_n-api_napi_get_new_target">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_new_target"></a></h4>
<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 <span class="hljs-title function_">napi_get_new_target</span><span class="hljs-params">(napi_env env,
                                napi_callback_info cbinfo,
                                napi_value* result)</span></code> <button class="copy-button">copy</button></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>
<h4><code>napi_new_instance</code><span><a class="mark" href="#all_n-api_napi_new_instance" id="all_n-api_napi_new_instance">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_new_instance"></a></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 <span class="hljs-title function_">napi_new_instance</span><span class="hljs-params">(napi_env env,
                              napi_value cons,
                              <span class="hljs-type">size_t</span> argc,
                              napi_value* argv,
                              napi_value* result)</span></code> <button class="copy-button">copy</button></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. If <code>argc</code> is zero this parameter may be
omitted by passing in <code>NULL</code>.</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"><span class="hljs-keyword">function</span> <span class="hljs-title function_">MyObject</span>(<span class="hljs-params">param</span>) {
  <span class="hljs-variable language_">this</span>.<span class="hljs-property">param</span> = param;
}

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

status = napi_get_named_property(env, global, <span class="hljs-string">"MyObject"</span>, &#x26;constructor);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span>;

<span class="hljs-comment">// const arg = "hello"</span>
status = napi_create_string_utf8(env, <span class="hljs-string">"hello"</span>, NAPI_AUTO_LENGTH, &#x26;arg);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span>;

napi_value* argv = &#x26;arg;
<span class="hljs-type">size_t</span> argc = <span class="hljs-number">1</span>;

<span class="hljs-comment">// const value = new MyObject(arg)</span>
status = napi_new_instance(env, constructor, argc, argv, &#x26;value);</code> <button class="copy-button">copy</button></pre>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
</section><section><h3>Object wrap<span><a class="mark" href="#all_n-api_object-wrap" id="all_n-api_object-wrap">#</a></span><a aria-hidden="true" class="legacy" id="n_api_object_wrap"></a></h3>
<p>Node-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="#all_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="#all_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="#all_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 = <span class="hljs-literal">NULL</span>;
status = napi_get_reference_value(env, MyClass::es_constructor, &#x26;MyClass_constructor);
assert(napi_ok == status);
<span class="hljs-type">bool</span> is_instance = <span class="hljs-literal">false</span>;
status = napi_instanceof(env, es_this, MyClass_constructor, &#x26;is_instance);
assert(napi_ok == status);
<span class="hljs-keyword">if</span> (is_instance) {
  <span class="hljs-comment">// napi_unwrap() ...</span>
} <span class="hljs-keyword">else</span> {
  <span class="hljs-comment">// otherwise...</span>
}</code> <button class="copy-button">copy</button></pre>
<p>The reference must be freed once it is no longer needed.</p>
<p>There are occasions where <code>napi_instanceof()</code> is insufficient for ensuring that
a JavaScript object is a wrapper for a certain native type. This is the case
especially when wrapped JavaScript objects are passed back into the addon via
static methods rather than as the <code>this</code> value of prototype methods. In such
cases there is a chance that they may be unwrapped incorrectly.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> myAddon = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./build/Release/my_addon.node'</span>);

<span class="hljs-comment">// `openDatabase()` returns a JavaScript object that wraps a native database</span>
<span class="hljs-comment">// handle.</span>
<span class="hljs-keyword">const</span> dbHandle = myAddon.<span class="hljs-title function_">openDatabase</span>();

<span class="hljs-comment">// `query()` returns a JavaScript object that wraps a native query handle.</span>
<span class="hljs-keyword">const</span> queryHandle = myAddon.<span class="hljs-title function_">query</span>(dbHandle, <span class="hljs-string">'Gimme ALL the things!'</span>);

<span class="hljs-comment">// There is an accidental error in the line below. The first parameter to</span>
<span class="hljs-comment">// `myAddon.queryHasRecords()` should be the database handle (`dbHandle`), not</span>
<span class="hljs-comment">// the query handle (`query`), so the correct condition for the while-loop</span>
<span class="hljs-comment">// should be</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// myAddon.queryHasRecords(dbHandle, queryHandle)</span>
<span class="hljs-comment">//</span>
<span class="hljs-keyword">while</span> (myAddon.<span class="hljs-title function_">queryHasRecords</span>(queryHandle, dbHandle)) {
  <span class="hljs-comment">// retrieve records</span>
}</code> <button class="copy-button">copy</button></pre>
<p>In the above example <code>myAddon.queryHasRecords()</code> is a method that accepts two
arguments. The first is a database handle and the second is a query handle.
Internally, it unwraps the first argument and casts the resulting pointer to a
native database handle. It then unwraps the second argument and casts the
resulting pointer to a query handle. If the arguments are passed in the wrong
order, the casts will work, however, there is a good chance that the underlying
database operation will fail, or will even cause an invalid memory access.</p>
<p>To ensure that the pointer retrieved from the first argument is indeed a pointer
to a database handle and, similarly, that the pointer retrieved from the second
argument is indeed a pointer to a query handle, the implementation of
<code>queryHasRecords()</code> has to perform a type validation. Retaining the JavaScript
class constructor from which the database handle was instantiated and the
constructor from which the query handle was instantiated in <code>napi_ref</code>s can
help, because <code>napi_instanceof()</code> can then be used to ensure that the instances
passed into <code>queryHashRecords()</code> are indeed of the correct type.</p>
<p>Unfortunately, <code>napi_instanceof()</code> does not protect against prototype
manipulation. For example, the prototype of the database handle instance can be
set to the prototype of the constructor for query handle instances. In this
case, the database handle instance can appear as a query handle instance, and it
will pass the <code>napi_instanceof()</code> test for a query handle instance, while still
containing a pointer to a database handle.</p>
<p>To this end, Node-API provides type-tagging capabilities.</p>
<p>A type tag is a 128-bit integer unique to the addon. Node-API provides the
<code>napi_type_tag</code> structure for storing a type tag. When such a value is passed
along with a JavaScript object or <a href="#all_n-api_napi_create_external">external</a> stored in a <code>napi_value</code> to
<code>napi_type_tag_object()</code>, the JavaScript object will be "marked" with the
type tag. The "mark" is invisible on the JavaScript side. When a JavaScript
object arrives into a native binding, <code>napi_check_object_type_tag()</code> can be used
along with the original type tag to determine whether the JavaScript object was
previously "marked" with the type tag. This creates a type-checking capability
of a higher fidelity than <code>napi_instanceof()</code> can provide, because such type-
tagging survives prototype manipulation and addon unloading/reloading.</p>
<p>Continuing the above example, the following skeleton addon implementation
illustrates the use of <code>napi_type_tag_object()</code> and
<code>napi_check_object_type_tag()</code>.</p>
<pre><code class="language-c"><span class="hljs-comment">// This value is the type tag for a database handle. The command</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">//   uuidgen | sed -r -e 's/-//g' -e 's/(.{16})(.*)/0x\1, 0x\2/'</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// can be used to obtain the two values with which to initialize the structure.</span>
<span class="hljs-type">static</span> <span class="hljs-type">const</span> napi_type_tag DatabaseHandleTypeTag = {
  <span class="hljs-number">0x1edf75a38336451d</span>, <span class="hljs-number">0xa5ed9ce2e4c00c38</span>
};

<span class="hljs-comment">// This value is the type tag for a query handle.</span>
<span class="hljs-type">static</span> <span class="hljs-type">const</span> napi_type_tag QueryHandleTypeTag = {
  <span class="hljs-number">0x9c73317f9fad44a3</span>, <span class="hljs-number">0x93c3920bf3b0ad6a</span>
};

<span class="hljs-type">static</span> napi_value
<span class="hljs-title function_">openDatabase</span><span class="hljs-params">(napi_env env, napi_callback_info info)</span> {
  napi_status status;
  napi_value result;

  <span class="hljs-comment">// Perform the underlying action which results in a database handle.</span>
  DatabaseHandle* dbHandle = open_database();

  <span class="hljs-comment">// Create a new, empty JS object.</span>
  status = napi_create_object(env, &#x26;result);
  <span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;

  <span class="hljs-comment">// Tag the object to indicate that it holds a pointer to a `DatabaseHandle`.</span>
  status = napi_type_tag_object(env, result, &#x26;DatabaseHandleTypeTag);
  <span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;

  <span class="hljs-comment">// Store the pointer to the `DatabaseHandle` structure inside the JS object.</span>
  status = napi_wrap(env, result, dbHandle, <span class="hljs-literal">NULL</span>, <span class="hljs-literal">NULL</span>, <span class="hljs-literal">NULL</span>);
  <span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;

  <span class="hljs-keyword">return</span> result;
}

<span class="hljs-comment">// Later when we receive a JavaScript object purporting to be a database handle</span>
<span class="hljs-comment">// we can use `napi_check_object_type_tag()` to ensure that it is indeed such a</span>
<span class="hljs-comment">// handle.</span>

<span class="hljs-type">static</span> napi_value
<span class="hljs-title function_">query</span><span class="hljs-params">(napi_env env, napi_callback_info info)</span> {
  napi_status status;
  <span class="hljs-type">size_t</span> argc = <span class="hljs-number">2</span>;
  napi_value argv[<span class="hljs-number">2</span>];
  <span class="hljs-type">bool</span> is_db_handle;

  status = napi_get_cb_info(env, info, &#x26;argc, argv, <span class="hljs-literal">NULL</span>, <span class="hljs-literal">NULL</span>);
  <span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;

  <span class="hljs-comment">// Check that the object passed as the first parameter has the previously</span>
  <span class="hljs-comment">// applied tag.</span>
  status = napi_check_object_type_tag(env,
                                      argv[<span class="hljs-number">0</span>],
                                      &#x26;DatabaseHandleTypeTag,
                                      &#x26;is_db_handle);
  <span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;

  <span class="hljs-comment">// Throw a `TypeError` if it doesn't.</span>
  <span class="hljs-keyword">if</span> (!is_db_handle) {
    <span class="hljs-comment">// Throw a TypeError.</span>
    <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
  }
}</code> <button class="copy-button">copy</button></pre>
<h4><code>napi_define_class</code><span><a class="mark" href="#all_n-api_napi_define_class" id="all_n-api_napi_define_class">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_define_class"></a></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 <span class="hljs-title function_">napi_define_class</span><span class="hljs-params">(napi_env env,
                              <span class="hljs-type">const</span> <span class="hljs-type">char</span>* utf8name,
                              <span class="hljs-type">size_t</span> length,
                              napi_callback constructor,
                              <span class="hljs-type">void</span>* data,
                              <span class="hljs-type">size_t</span> property_count,
                              <span class="hljs-type">const</span> napi_property_descriptor* properties,
                              napi_value* result)</span>;</code> <button class="copy-button">copy</button></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. For clarity,
it is recommended to use the C++ class name when wrapping a C++ class.</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. When wrapping a C++ class, this method must be a static member
with the <a href="#all_n-api_napi_callback"><code>napi_callback</code></a> signature. A C++ class constructor cannot be
used. <a href="#all_n-api_napi_callback"><code>napi_callback</code></a> provides more details.</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, including:</p>
<ul>
<li>A JavaScript constructor function that has the class name. When wrapping a
corresponding C++ class, the callback passed via <code>constructor</code> can be used to
instantiate a new C++ class instance, which can then be placed inside the
JavaScript object instance being constructed using <a href="#all_n-api_napi_wrap"><code>napi_wrap</code></a>.</li>
<li>Properties on the constructor function whose implementation can call
corresponding <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. When wrapping a
C++ class, <em>non-static</em> data properties, accessors, and methods of the C++
class can be called from the static functions given in the property
descriptors without the <code>napi_static</code> attribute after retrieving the C++ class
instance placed inside the JavaScript object instance by using
<a href="#all_n-api_napi_unwrap"><code>napi_unwrap</code></a>.</li>
</ul>
<p>When wrapping a C++ class, the C++ constructor callback passed via <code>constructor</code>
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 <a href="#all_n-api_napi_wrap"><code>napi_wrap</code></a> for details.</p>
<p>The JavaScript constructor function returned from <a href="#all_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 to check whether provided values are instances of the class. In
that case, to prevent the function value from being garbage-collected, a
strong persistent reference to it can be created using
<a href="#all_n-api_napi_create_reference"><code>napi_create_reference</code></a>, ensuring that 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="#all_n-api_napi_add_finalizer"><code>napi_add_finalizer</code></a>.</p>
<h4><code>napi_wrap</code><span><a class="mark" href="#all_n-api_napi_wrap" id="all_n-api_napi_wrap">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_wrap"></a></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 <span class="hljs-title function_">napi_wrap</span><span class="hljs-params">(napi_env env,
                      napi_value js_object,
                      <span class="hljs-type">void</span>* native_object,
                      napi_finalize finalize_cb,
                      <span class="hljs-type">void</span>* finalize_hint,
                      napi_ref* result)</span>;</code> <button class="copy-button">copy</button></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 has been garbage-collected.
<a href="#all_n-api_napi_finalize"><code>napi_finalize</code></a> provides more details.</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="#all_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>Finalizer callbacks may be deferred, leaving a window where the object has
been garbage collected (and the weak reference is invalid) but the finalizer
hasn't been called yet. When using <code>napi_get_reference_value()</code> on weak
references returned by <code>napi_wrap()</code>, you should still handle an empty result.</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>
<h4><code>napi_unwrap</code><span><a class="mark" href="#all_n-api_napi_unwrap" id="all_n-api_napi_unwrap">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_unwrap"></a></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 <span class="hljs-title function_">napi_unwrap</span><span class="hljs-params">(napi_env env,
                        napi_value js_object,
                        <span class="hljs-type">void</span>** result)</span>;</code> <button class="copy-button">copy</button></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>
<h4><code>napi_remove_wrap</code><span><a class="mark" href="#all_n-api_napi_remove_wrap" id="all_n-api_napi_remove_wrap">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_remove_wrap"></a></h4>
<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 <span class="hljs-title function_">napi_remove_wrap</span><span class="hljs-params">(napi_env env,
                             napi_value js_object,
                             <span class="hljs-type">void</span>** result)</span>;</code> <button class="copy-button">copy</button></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>
<h4><code>napi_type_tag_object</code><span><a class="mark" href="#all_n-api_napi_type_tag_object" id="all_n-api_napi_type_tag_object">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_type_tag_object"></a></h4>
<div class="api_metadata">
<span>Added in: v14.8.0, v12.19.0</span>
<span>N-API version: 8</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_type_tag_object</span><span class="hljs-params">(napi_env env,
                                 napi_value js_object,
                                 <span class="hljs-type">const</span> napi_type_tag* type_tag)</span>;</code> <button class="copy-button">copy</button></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 or <a href="#all_n-api_napi_create_external">external</a> to be marked.</li>
<li><code>[in] type_tag</code>: The tag with which the object is to be marked.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>Associates the value of the <code>type_tag</code> pointer with the JavaScript object or
<a href="#all_n-api_napi_create_external">external</a>. <code>napi_check_object_type_tag()</code> can then be used to compare the tag
that was attached to the object with one owned by the addon to ensure that the
object has the right type.</p>
<p>If the object already has an associated type tag, this API will return
<code>napi_invalid_arg</code>.</p>
<h4><code>napi_check_object_type_tag</code><span><a class="mark" href="#all_n-api_napi_check_object_type_tag" id="all_n-api_napi_check_object_type_tag">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_check_object_type_tag"></a></h4>
<div class="api_metadata">
<span>Added in: v14.8.0, v12.19.0</span>
<span>N-API version: 8</span>
</div>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_check_object_type_tag</span><span class="hljs-params">(napi_env env,
                                       napi_value js_object,
                                       <span class="hljs-type">const</span> napi_type_tag* type_tag,
                                       <span class="hljs-type">bool</span>* result)</span>;</code> <button class="copy-button">copy</button></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 or <a href="#all_n-api_napi_create_external">external</a> whose type tag to
examine.</li>
<li><code>[in] type_tag</code>: The tag with which to compare any tag found on the object.</li>
<li><code>[out] result</code>: Whether the type tag given matched the type tag on the
object. <code>false</code> is also returned if no type tag was found on the object.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>Compares the pointer given as <code>type_tag</code> with any that can be found on
<code>js_object</code>. If no tag is found on <code>js_object</code> or, if a tag is found but it does
not match <code>type_tag</code>, then <code>result</code> is set to <code>false</code>. If a tag is found and it
matches <code>type_tag</code>, then <code>result</code> is set to <code>true</code>.</p>
<h4><code>napi_add_finalizer</code><span><a class="mark" href="#all_n-api_napi_add_finalizer" id="all_n-api_napi_add_finalizer">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_add_finalizer"></a></h4>
<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 <span class="hljs-title function_">napi_add_finalizer</span><span class="hljs-params">(napi_env env,
                               napi_value js_object,
                               <span class="hljs-type">void</span>* finalize_data,
                               node_api_basic_finalize finalize_cb,
                               <span class="hljs-type">void</span>* finalize_hint,
                               napi_ref* result)</span>;</code> <button class="copy-button">copy</button></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] finalize_data</code>: Optional data to be passed to <code>finalize_cb</code>.</li>
<li><code>[in] finalize_cb</code>: Native callback that will be used to free the
native data when the JavaScript object has been garbage-collected.
<a href="#all_n-api_napi_finalize"><code>napi_finalize</code></a> provides more details.</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> has been garbage-collected.</p>
<p>This API can be called multiple times on a single JavaScript object.</p>
<p><em>Caution</em>: The optional returned reference (if obtained) should be deleted via
<a href="#all_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>
<h5><code>node_api_post_finalizer</code><span><a class="mark" href="#all_n-api_node_api_post_finalizer" id="all_n-api_node_api_post_finalizer">#</a></span><a aria-hidden="true" class="legacy" id="n_api_node_api_post_finalizer"></a></h5>
<div class="api_metadata">
<span>Added in: v20.10.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<pre><code class="language-c">napi_status <span class="hljs-title function_">node_api_post_finalizer</span><span class="hljs-params">(node_api_basic_env env,
                                    napi_finalize finalize_cb,
                                    <span class="hljs-type">void</span>* finalize_data,
                                    <span class="hljs-type">void</span>* finalize_hint)</span>;</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[in] finalize_cb</code>: Native callback that will be used to free the
native data when the JavaScript object has been garbage-collected.
<a href="#all_n-api_napi_finalize"><code>napi_finalize</code></a> provides more details.</li>
<li><code>[in] finalize_data</code>: Optional data to be passed to <code>finalize_cb</code>.</li>
<li><code>[in] finalize_hint</code>: Optional contextual hint that is passed to the
finalize callback.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>Schedules a <code>napi_finalize</code> callback to be called asynchronously in the
event loop.</p>
<p>Normally, finalizers are called while the GC (garbage collector) collects
objects. At that point calling any Node-API that may cause changes in the GC
state will be disabled and will crash Node.js.</p>
<p><code>node_api_post_finalizer</code> helps to work around this limitation by allowing the
add-on to defer calls to such Node-APIs to a point in time outside of the GC
finalization.</p>
</section><section><h3>Simple asynchronous operations<span><a class="mark" href="#all_n-api_simple-asynchronous-operations" id="all_n-api_simple-asynchronous-operations">#</a></span><a aria-hidden="true" class="legacy" id="n_api_simple_asynchronous_operations"></a></h3>
<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>Node-API provides an ABI-stable interface for these
supporting functions which covers the most common asynchronous use cases.</p>
<p>Node-API defines the <code>napi_async_work</code> structure which is used to manage
asynchronous workers. Instances are created/deleted with
<a href="#all_n-api_napi_create_async_work"><code>napi_create_async_work</code></a> and <a href="#all_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 Node-API calls
that could result in the execution of JavaScript or interaction with
JavaScript objects. Most often, any code that needs to make Node-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"><span class="hljs-keyword">typedef</span> <span class="hljs-title function_">void</span> <span class="hljs-params">(*napi_async_execute_callback)</span><span class="hljs-params">(napi_env env,
                                            <span class="hljs-type">void</span>* data)</span>;
<span class="hljs-keyword">typedef</span> <span class="hljs-title function_">void</span> <span class="hljs-params">(*napi_async_complete_callback)</span><span class="hljs-params">(napi_env env,
                                             napi_status status,
                                             <span class="hljs-type">void</span>* data)</span>;</code> <button class="copy-button">copy</button></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="#all_n-api_napi_queue_async_work"><code>napi_queue_async_work</code></a> function:</p>
<pre><code class="language-c">napi_status <span class="hljs-title function_">napi_queue_async_work</span><span class="hljs-params">(node_api_basic_env env,
                                  napi_async_work work)</span>;</code> <button class="copy-button">copy</button></pre>
<p><a href="#all_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="#all_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>
<h4><code>napi_create_async_work</code><span><a class="mark" href="#all_n-api_napi_create_async_work" id="all_n-api_napi_create_async_work">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_async_work"></a></h4>
<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 <span class="hljs-title function_">napi_create_async_work</span><span class="hljs-params">(napi_env env,
                                   napi_value async_resource,
                                   napi_value async_resource_name,
                                   napi_async_execute_callback execute,
                                   napi_async_complete_callback complete,
                                   <span class="hljs-type">void</span>* data,
                                   napi_async_work* result)</span>;</code> <button class="copy-button">copy</button></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="#all_async_hooks_initasyncid-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. <a href="#all_n-api_napi_async_complete_callback"><code>napi_async_complete_callback</code></a> provides
more details.</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="#all_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="#all_async_hooks_type"><code>async_hooks</code> documentation</a> for more information.</p>
<h4><code>napi_delete_async_work</code><span><a class="mark" href="#all_n-api_napi_delete_async_work" id="all_n-api_napi_delete_async_work">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_delete_async_work"></a></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 <span class="hljs-title function_">napi_delete_async_work</span><span class="hljs-params">(napi_env env,
                                   napi_async_work work)</span>;</code> <button class="copy-button">copy</button></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>
<h4><code>napi_queue_async_work</code><span><a class="mark" href="#all_n-api_napi_queue_async_work" id="all_n-api_napi_queue_async_work">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_queue_async_work"></a></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 <span class="hljs-title function_">napi_queue_async_work</span><span class="hljs-params">(node_api_basic_env env,
                                  napi_async_work work)</span>;</code> <button class="copy-button">copy</button></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>
<h4><code>napi_cancel_async_work</code><span><a class="mark" href="#all_n-api_napi_cancel_async_work" id="all_n-api_napi_cancel_async_work">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_cancel_async_work"></a></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 <span class="hljs-title function_">napi_cancel_async_work</span><span class="hljs-params">(node_api_basic_env env,
                                   napi_async_work work)</span>;</code> <button class="copy-button">copy</button></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>
</section><section><h3>Custom asynchronous operations<span><a class="mark" href="#all_n-api_custom-asynchronous-operations" id="all_n-api_custom-asynchronous-operations">#</a></span><a aria-hidden="true" class="legacy" id="n_api_custom_asynchronous_operations"></a></h3>
<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>
<h4><code>napi_async_init</code><span><a class="mark" href="#all_n-api_napi_async_init" id="all_n-api_napi_async_init">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_async_init"></a></h4>
<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 <span class="hljs-title function_">napi_async_init</span><span class="hljs-params">(napi_env env,
                            napi_value async_resource,
                            napi_value async_resource_name,
                            napi_async_context* result)</span></code> <button class="copy-button">copy</button></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="#all_async_hooks_initasyncid-type-triggerasyncid-resource"><code>init</code> hooks</a> and can be
accessed by <a href="#all_async_hooks_async_hooksexecutionasyncresource"><code>async_hooks.executionAsyncResource()</code></a>.</li>
<li><code>[in] async_resource_name</code>: Identifier for the kind of resource that is being
provided for diagnostic information exposed by the <code>async_hooks</code> API.</li>
<li><code>[out] result</code>: The initialized async context.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>The <code>async_resource</code> object needs to be kept alive until
<a href="#all_n-api_napi_async_destroy"><code>napi_async_destroy</code></a> to keep <code>async_hooks</code> related API acts correctly. In
order to retain ABI compatibility with previous versions, <code>napi_async_context</code>s
are not maintaining the strong reference to the <code>async_resource</code> objects to
avoid introducing causing memory leaks. However, if the <code>async_resource</code> is
garbage collected by JavaScript engine before the <code>napi_async_context</code> was
destroyed by <code>napi_async_destroy</code>, calling <code>napi_async_context</code> related APIs
like <a href="#all_n-api_napi_open_callback_scope"><code>napi_open_callback_scope</code></a> and <a href="#all_n-api_napi_make_callback"><code>napi_make_callback</code></a> can cause
problems like loss of async context when using the <code>AsyncLocalStorage</code> API.</p>
<p>In order to retain ABI compatibility with previous versions, passing <code>NULL</code>
for <code>async_resource</code> does not result in an error. However, this is not
recommended as this will result in undesirable behavior with  <code>async_hooks</code>
<a href="#all_async_hooks_initasyncid-type-triggerasyncid-resource"><code>init</code> hooks</a> and <code>async_hooks.executionAsyncResource()</code> as the resource is
now required by the underlying <code>async_hooks</code> implementation in order to provide
the linkage between async callbacks.</p>
<h4><code>napi_async_destroy</code><span><a class="mark" href="#all_n-api_napi_async_destroy" id="all_n-api_napi_async_destroy">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_async_destroy"></a></h4>
<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 <span class="hljs-title function_">napi_async_destroy</span><span class="hljs-params">(napi_env env,
                               napi_async_context async_context)</span>;</code> <button class="copy-button">copy</button></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>
<h4><code>napi_make_callback</code><span><a class="mark" href="#all_n-api_napi_make_callback" id="all_n-api_napi_make_callback">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_make_callback"></a></h4>
<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 <span class="hljs-title function_">napi_make_callback</span><span class="hljs-params">(napi_env env,
                                           napi_async_context async_context,
                                           napi_value recv,
                                           napi_value func,
                                           <span class="hljs-type">size_t</span> argc,
                                           <span class="hljs-type">const</span> napi_value* argv,
                                           napi_value* result)</span>;</code> <button class="copy-button">copy</button></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="#all_n-api_napi_async_init"><code>napi_async_init</code></a>.
In order to retain ABI compatibility with previous versions, passing <code>NULL</code>
for <code>async_context</code> does not result in an error. However, this results
in incorrect operation of async hooks. Potential issues include loss of
async context when using the <code>AsyncLocalStorage</code> API.</li>
<li><code>[in] recv</code>: The <code>this</code> value 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. If <code>argc</code> is zero this parameter may be
omitted by passing in <code>NULL</code>.</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>
<h4><code>napi_open_callback_scope</code><span><a class="mark" href="#all_n-api_napi_open_callback_scope" id="all_n-api_napi_open_callback_scope">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_open_callback_scope"></a></h4>
<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 <span class="hljs-title function_">napi_open_callback_scope</span><span class="hljs-params">(napi_env env,
                                                 napi_value resource_object,
                                                 napi_async_context context,
                                                 napi_callback_scope* result)</span></code> <button class="copy-button">copy</button></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="#all_async_hooks_initasyncid-type-triggerasyncid-resource"><code>init</code> hooks</a>. This
parameter has been deprecated and is ignored at runtime. Use the
<code>async_resource</code> parameter in <a href="#all_n-api_napi_async_init"><code>napi_async_init</code></a> instead.</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="#all_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 Node-API calls. If there is no other script on
the stack the <a href="#all_n-api_napi_open_callback_scope"><code>napi_open_callback_scope</code></a> and
<a href="#all_n-api_napi_close_callback_scope"><code>napi_close_callback_scope</code></a> functions can be used to open/close
the required scope.</p>
<h4><code>napi_close_callback_scope</code><span><a class="mark" href="#all_n-api_napi_close_callback_scope" id="all_n-api_napi_close_callback_scope">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_close_callback_scope"></a></h4>
<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 <span class="hljs-title function_">napi_close_callback_scope</span><span class="hljs-params">(napi_env env,
                                                  napi_callback_scope scope)</span></code> <button class="copy-button">copy</button></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>
</section><section><h3>Version management<span><a class="mark" href="#all_n-api_version-management" id="all_n-api_version-management">#</a></span><a aria-hidden="true" class="legacy" id="n_api_version_management"></a></h3>
<h4><code>napi_get_node_version</code><span><a class="mark" href="#all_n-api_napi_get_node_version" id="all_n-api_napi_get_node_version">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_node_version"></a></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
<span>N-API version: 1</span>
</div>
<pre><code class="language-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> {</span>
  <span class="hljs-type">uint32_t</span> major;
  <span class="hljs-type">uint32_t</span> minor;
  <span class="hljs-type">uint32_t</span> patch;
  <span class="hljs-type">const</span> <span class="hljs-type">char</span>* release;
} napi_node_version;

napi_status <span class="hljs-title function_">napi_get_node_version</span><span class="hljs-params">(node_api_basic_env env,
                                  <span class="hljs-type">const</span> napi_node_version** version)</span>;</code> <button class="copy-button">copy</button></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="#all_process_processrelease"><code>process.release.name</code></a>.</p>
<p>The returned buffer is statically allocated and does not need to be freed.</p>
<h4><code>napi_get_version</code><span><a class="mark" href="#all_n-api_napi_get_version" id="all_n-api_napi_get_version">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_version"></a></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 <span class="hljs-title function_">napi_get_version</span><span class="hljs-params">(node_api_basic_env env,
                             <span class="hljs-type">uint32_t</span>* result)</span>;</code> <button class="copy-button">copy</button></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 Node-API supported.</li>
</ul>
<p>Returns <code>napi_ok</code> if the API succeeded.</p>
<p>This API returns the highest Node-API version supported by the
Node.js runtime. Node-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>
</section><section><h3>Memory management<span><a class="mark" href="#all_n-api_memory-management" id="all_n-api_memory-management">#</a></span><a aria-hidden="true" class="legacy" id="n_api_memory_management"></a></h3>
<h4><code>napi_adjust_external_memory</code><span><a class="mark" href="#all_n-api_napi_adjust_external_memory" id="all_n-api_napi_adjust_external_memory">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_adjust_external_memory"></a></h4>
<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 <span class="hljs-title function_">napi_adjust_external_memory</span><span class="hljs-params">(node_api_basic_env env,
                                                    <span class="hljs-type">int64_t</span> change_in_bytes,
                                                    <span class="hljs-type">int64_t</span>* result)</span>;</code> <button class="copy-button">copy</button></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 addon). Registering
externally allocated memory will trigger global garbage collections more
often than it would otherwise.</p>
</section><section><h3>Promises<span><a class="mark" href="#all_n-api_promises" id="all_n-api_promises">#</a></span><a aria-hidden="true" class="legacy" id="n_api_promises"></a></h3>
<p>Node-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;

<span class="hljs-comment">// Create the promise.</span>
status = napi_create_promise(env, &#x26;deferred, &#x26;promise);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;

<span class="hljs-comment">// Pass the deferred to a function that performs an asynchronous action.</span>
do_something_asynchronous(deferred);

<span class="hljs-comment">// Return the promise to JS</span>
<span class="hljs-keyword">return</span> promise;</code> <button class="copy-button">copy</button></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;

<span class="hljs-comment">// Create a value with which to conclude the deferred.</span>
status = napi_get_undefined(env, &#x26;undefined);
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;

<span class="hljs-comment">// Resolve or reject the promise associated with the deferred depending on</span>
<span class="hljs-comment">// whether the asynchronous action succeeded.</span>
<span class="hljs-keyword">if</span> (asynchronous_action_succeeded) {
  status = napi_resolve_deferred(env, deferred, undefined);
} <span class="hljs-keyword">else</span> {
  status = napi_reject_deferred(env, deferred, undefined);
}
<span class="hljs-keyword">if</span> (status != napi_ok) <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;

<span class="hljs-comment">// At this point the deferred has been freed, so we should assign NULL to it.</span>
deferred = <span class="hljs-literal">NULL</span>;</code> <button class="copy-button">copy</button></pre>
<h4><code>napi_create_promise</code><span><a class="mark" href="#all_n-api_napi_create_promise" id="all_n-api_napi_create_promise">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_promise"></a></h4>
<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 <span class="hljs-title function_">napi_create_promise</span><span class="hljs-params">(napi_env env,
                                napi_deferred* deferred,
                                napi_value* promise)</span>;</code> <button class="copy-button">copy</button></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>
<h4><code>napi_resolve_deferred</code><span><a class="mark" href="#all_n-api_napi_resolve_deferred" id="all_n-api_napi_resolve_deferred">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_resolve_deferred"></a></h4>
<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 <span class="hljs-title function_">napi_resolve_deferred</span><span class="hljs-params">(napi_env env,
                                  napi_deferred deferred,
                                  napi_value resolution)</span>;</code> <button class="copy-button">copy</button></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>
<h4><code>napi_reject_deferred</code><span><a class="mark" href="#all_n-api_napi_reject_deferred" id="all_n-api_napi_reject_deferred">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_reject_deferred"></a></h4>
<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 <span class="hljs-title function_">napi_reject_deferred</span><span class="hljs-params">(napi_env env,
                                 napi_deferred deferred,
                                 napi_value rejection)</span>;</code> <button class="copy-button">copy</button></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>
<h4><code>napi_is_promise</code><span><a class="mark" href="#all_n-api_napi_is_promise" id="all_n-api_napi_is_promise">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_is_promise"></a></h4>
<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 <span class="hljs-title function_">napi_is_promise</span><span class="hljs-params">(napi_env env,
                            napi_value value,
                            <span class="hljs-type">bool</span>* is_promise)</span>;</code> <button class="copy-button">copy</button></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>
</section><section><h3>Script execution<span><a class="mark" href="#all_n-api_script-execution" id="all_n-api_script-execution">#</a></span><a aria-hidden="true" class="legacy" id="n_api_script_execution"></a></h3>
<p>Node-API provides an API for executing a string containing JavaScript using the
underlying JavaScript engine.</p>
<h4><code>napi_run_script</code><span><a class="mark" href="#all_n-api_napi_run_script" id="all_n-api_napi_run_script">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_run_script"></a></h4>
<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 <span class="hljs-title function_">napi_run_script</span><span class="hljs-params">(napi_env env,
                                        napi_value script,
                                        napi_value* result)</span>;</code> <button class="copy-button">copy</button></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="#all_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="#all_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="#all_globals_global"><code>global</code></a> object.</li>
<li>The value of <code>this</code> is <a href="#all_globals_global"><code>global</code></a> within the script.</li>
</ul>
</section><section><h3>libuv event loop<span><a class="mark" href="#all_n-api_libuv-event-loop" id="all_n-api_libuv-event-loop">#</a></span><a aria-hidden="true" class="legacy" id="n_api_libuv_event_loop"></a></h3>
<p>Node-API provides a function for getting the current event loop associated with
a specific <code>napi_env</code>.</p>
<h4><code>napi_get_uv_event_loop</code><span><a class="mark" href="#all_n-api_napi_get_uv_event_loop" id="all_n-api_napi_get_uv_event_loop">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_uv_event_loop"></a></h4>
<div class="api_metadata">
<span>Added in: v9.3.0, v8.10.0</span>
<span>N-API version: 2</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status <span class="hljs-title function_">napi_get_uv_event_loop</span><span class="hljs-params">(node_api_basic_env env,
                                               <span class="hljs-keyword">struct</span> uv_loop_s** loop)</span>;</code> <button class="copy-button">copy</button></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>
<p>Note: While libuv has been relatively stable over time, it does
not provide an ABI stability guarantee. Use of this function should be avoided.
Its use may result in an addon that does not work across Node.js versions.
<a href="https://nodejs.org/docs/latest/api/n-api.html#asynchronous-thread-safe-function-calls">asynchronous-thread-safe-function-calls</a>
are an alternative for many use cases.</p>
</section><section><h3>Asynchronous thread-safe function calls<span><a class="mark" href="#all_n-api_asynchronous-thread-safe-function-calls" id="all_n-api_asynchronous-thread-safe-function-calls">#</a></span><a aria-hidden="true" class="legacy" id="n_api_asynchronous_thread_safe_function_calls"></a></h3>
<p>JavaScript functions can normally only be called from a native addon's main
thread. If an addon creates additional threads, then Node-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>
<h4>Calling a thread-safe function<span><a class="mark" href="#all_n-api_calling-a-thread-safe-function" id="all_n-api_calling-a-thread-safe-function">#</a></span><a aria-hidden="true" class="legacy" id="n_api_calling_a_thread_safe_function"></a></h4>
<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><code>napi_call_threadsafe_function()</code> should not be called with <code>napi_tsfn_blocking</code>
from a JavaScript thread, because, if the queue is full, it may cause the
JavaScript thread to deadlock.</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
Node-API runs <code>call_js_cb</code> in a context appropriate for callbacks.</p>
<p>Zero or more queued items may be invoked in each tick of the event loop.
Applications should not depend on a specific behavior other than progress in
invoking callbacks will be made and events will be invoked
as time moves forward.</p>
<h4>Reference counting of thread-safe functions<span><a class="mark" href="#all_n-api_reference-counting-of-thread-safe-functions" id="all_n-api_reference-counting-of-thread-safe-functions">#</a></span><a aria-hidden="true" class="legacy" id="n_api_reference_counting_of_thread_safe_functions"></a></h4>
<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 use 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 acquisitions 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 not use
the thread-safe function anymore because it is no longer guaranteed to
be allocated.</strong></p>
<h4>Deciding whether to keep the process running<span><a class="mark" href="#all_n-api_deciding-whether-to-keep-the-process-running" id="all_n-api_deciding-whether-to-keep-the-process-running">#</a></span><a aria-hidden="true" class="legacy" id="n_api_deciding_whether_to_keep_the_process_running"></a></h4>
<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>
<h4><code>napi_create_threadsafe_function</code><span><a class="mark" href="#all_n-api_napi_create_threadsafe_function" id="all_n-api_napi_create_threadsafe_function">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_create_threadsafe_function"></a></h4>
<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, v10.17.0</td>
<td><p>Made <code>func</code> parameter optional with custom <code>call_js_cb</code>.</p></td></tr>
<tr><td>v10.6.0</td>
<td><p><span>Added in: v10.6.0</span></p></td></tr>
</tbody></table>
</details>
<span>N-API version: 4</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status
<span class="hljs-title function_">napi_create_threadsafe_function</span><span class="hljs-params">(napi_env env,
                                napi_value func,
                                napi_value async_resource,
                                napi_value async_resource_name,
                                <span class="hljs-type">size_t</span> max_queue_size,
                                <span class="hljs-type">size_t</span> initial_thread_count,
                                <span class="hljs-type">void</span>* thread_finalize_data,
                                napi_finalize thread_finalize_cb,
                                <span class="hljs-type">void</span>* context,
                                napi_threadsafe_function_call_js call_js_cb,
                                napi_threadsafe_function* result)</span>;</code> <button class="copy-button">copy</button></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="#all_async_hooks_initasyncid-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.
<a href="#all_n-api_napi_threadsafe_function_call_js"><code>napi_threadsafe_function_call_js</code></a> provides more details.</li>
<li><code>[out] result</code>: The asynchronous thread-safe JavaScript function.</li>
</ul>
<p><strong>Change History:</strong></p>
<ul>
<li>
<p>Experimental (<code>NAPI_EXPERIMENTAL</code> is defined):</p>
<p>Uncaught exceptions thrown in <code>call_js_cb</code> are handled with the
<a href="#all_process_event-uncaughtexception"><code>'uncaughtException'</code></a> event, instead of being ignored.</p>
</li>
</ul>
<h4><code>napi_get_threadsafe_function_context</code><span><a class="mark" href="#all_n-api_napi_get_threadsafe_function_context" id="all_n-api_napi_get_threadsafe_function_context">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_get_threadsafe_function_context"></a></h4>
<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
<span class="hljs-title function_">napi_get_threadsafe_function_context</span><span class="hljs-params">(napi_threadsafe_function func,
                                     <span class="hljs-type">void</span>** result)</span>;</code> <button class="copy-button">copy</button></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>
<h4><code>napi_call_threadsafe_function</code><span><a class="mark" href="#all_n-api_napi_call_threadsafe_function" id="all_n-api_napi_call_threadsafe_function">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_call_threadsafe_function"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.5.0</td>
<td><p>Support for <code>napi_would_deadlock</code> has been reverted.</p></td></tr>
<tr><td>v14.1.0</td>
<td><p>Return <code>napi_would_deadlock</code> when called with <code>napi_tsfn_blocking</code> from the main thread or a worker thread and the queue is full.</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
<span class="hljs-title function_">napi_call_threadsafe_function</span><span class="hljs-params">(napi_threadsafe_function func,
                              <span class="hljs-type">void</span>* data,
                              napi_threadsafe_function_call_mode is_blocking)</span>;</code> <button class="copy-button">copy</button></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 should not be called with <code>napi_tsfn_blocking</code> from a JavaScript
thread, because, if the queue is full, it may cause the JavaScript thread to
deadlock.</p>
<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>
<h4><code>napi_acquire_threadsafe_function</code><span><a class="mark" href="#all_n-api_napi_acquire_threadsafe_function" id="all_n-api_napi_acquire_threadsafe_function">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_acquire_threadsafe_function"></a></h4>
<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
<span class="hljs-title function_">napi_acquire_threadsafe_function</span><span class="hljs-params">(napi_threadsafe_function func)</span>;</code> <button class="copy-button">copy</button></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>
<h4><code>napi_release_threadsafe_function</code><span><a class="mark" href="#all_n-api_napi_release_threadsafe_function" id="all_n-api_napi_release_threadsafe_function">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_release_threadsafe_function"></a></h4>
<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
<span class="hljs-title function_">napi_release_threadsafe_function</span><span class="hljs-params">(napi_threadsafe_function func,
                                 napi_threadsafe_function_release_mode mode)</span>;</code> <button class="copy-button">copy</button></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>
<h4><code>napi_ref_threadsafe_function</code><span><a class="mark" href="#all_n-api_napi_ref_threadsafe_function" id="all_n-api_napi_ref_threadsafe_function">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_ref_threadsafe_function"></a></h4>
<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
<span class="hljs-title function_">napi_ref_threadsafe_function</span><span class="hljs-params">(node_api_basic_env env, napi_threadsafe_function func)</span>;</code> <button class="copy-button">copy</button></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="https://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>
<h4><code>napi_unref_threadsafe_function</code><span><a class="mark" href="#all_n-api_napi_unref_threadsafe_function" id="all_n-api_napi_unref_threadsafe_function">#</a></span><a aria-hidden="true" class="legacy" id="n_api_napi_unref_threadsafe_function"></a></h4>
<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
<span class="hljs-title function_">napi_unref_threadsafe_function</span><span class="hljs-params">(node_api_basic_env env, napi_threadsafe_function func)</span>;</code> <button class="copy-button">copy</button></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="https://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>
</section><section><h3>Miscellaneous utilities<span><a class="mark" href="#all_n-api_miscellaneous-utilities" id="all_n-api_miscellaneous-utilities">#</a></span><a aria-hidden="true" class="legacy" id="n_api_miscellaneous_utilities"></a></h3>
<h4><code>node_api_get_module_file_name</code><span><a class="mark" href="#all_n-api_node_api_get_module_file_name" id="all_n-api_node_api_get_module_file_name">#</a></span><a aria-hidden="true" class="legacy" id="n_api_node_api_get_module_file_name"></a></h4>
<div class="api_metadata">
<span>Added in: v15.9.0, v14.18.0, v12.22.0</span>
<span>N-API version: 9</span>
</div>
<pre><code class="language-c">NAPI_EXTERN napi_status
<span class="hljs-title function_">node_api_get_module_file_name</span><span class="hljs-params">(node_api_basic_env env, <span class="hljs-type">const</span> <span class="hljs-type">char</span>** result)</span>;
</code> <button class="copy-button">copy</button></pre>
<ul>
<li><code>[in] env</code>: The environment that the API is invoked under.</li>
<li><code>[out] result</code>: A URL containing the absolute path of the
location from which the add-on was loaded. For a file on the local
file system it will start with <code>file://</code>. The string is null-terminated and
owned by <code>env</code> and must thus not be modified or freed.</li>
</ul>
<p><code>result</code> may be an empty string if the add-on loading process fails to establish
the add-on's file name during loading.</p></section>
        </section>
<section><h2>C++ embedder API<span><a class="mark" href="#all_embedding_c-embedder-api" id="all_embedding_c-embedder-api">#</a></span><a aria-hidden="true" class="legacy" id="embedding_c_embedder_api"></a></h2>

<p>Node.js provides a number of C++ APIs that can be used to execute JavaScript
in a Node.js environment from other C++ software.</p>
<p>The documentation for these APIs can be found in <a href="https://github.com/nodejs/node/blob/HEAD/src/node.h">src/node.h</a> in the Node.js
source tree. In addition to the APIs exposed by Node.js, some required concepts
are provided by the V8 embedder API.</p>
<p>Because using Node.js as an embedded library is different from writing code
that is executed by Node.js, breaking changes do not follow typical Node.js
<a href="deprecations.html">deprecation policy</a> and may occur on each semver-major release without prior
warning.</p>
<section><h3>Example embedding application<span><a class="mark" href="#all_embedding_example-embedding-application" id="all_embedding_example-embedding-application">#</a></span><a aria-hidden="true" class="legacy" id="embedding_example_embedding_application"></a></h3>
<p>The following sections will provide an overview over how to use these APIs
to create an application from scratch that will perform the equivalent of
<code>node -e &#x3C;code></code>, i.e. that will take a piece of JavaScript and run it in
a Node.js-specific environment.</p>
<p>The full code can be found <a href="https://github.com/nodejs/node/blob/HEAD/test/embedding/embedtest.cc">in the Node.js source tree</a>.</p>
<h4>Setting up per-process state<span><a class="mark" href="#all_embedding_setting-up-per-process-state" id="all_embedding_setting-up-per-process-state">#</a></span><a aria-hidden="true" class="legacy" id="embedding_setting_up_per_process_state"></a></h4>
<p>Node.js requires some per-process state management in order to run:</p>
<ul>
<li>Arguments parsing for Node.js <a href="cli.html">CLI options</a>,</li>
<li>V8 per-process requirements, such as a <code>v8::Platform</code> instance.</li>
</ul>
<p>The following example shows how these can be set up. Some class names are from
the <code>node</code> and <code>v8</code> C++ namespaces, respectively.</p>
<pre><code class="language-cpp"><span class="hljs-function"><span class="hljs-type">int</span> <span class="hljs-title">main</span><span class="hljs-params">(<span class="hljs-type">int</span> argc, <span class="hljs-type">char</span>** argv)</span> </span>{
  argv = <span class="hljs-built_in">uv_setup_args</span>(argc, argv);
  <span class="hljs-function">std::vector&#x3C;std::string> <span class="hljs-title">args</span><span class="hljs-params">(argv, argv + argc)</span></span>;
  <span class="hljs-comment">// Parse Node.js CLI options, and print any errors that have occurred while</span>
  <span class="hljs-comment">// trying to parse them.</span>
  std::unique_ptr&#x3C;node::InitializationResult> result =
      node::<span class="hljs-built_in">InitializeOncePerProcess</span>(args, {
        node::ProcessInitializationFlags::kNoInitializeV8,
        node::ProcessInitializationFlags::kNoInitializeNodeV8Platform
      });

  <span class="hljs-keyword">for</span> (<span class="hljs-type">const</span> std::string&#x26; error : result-><span class="hljs-built_in">errors</span>())
    <span class="hljs-built_in">fprintf</span>(stderr, <span class="hljs-string">"%s: %s\n"</span>, args[<span class="hljs-number">0</span>].<span class="hljs-built_in">c_str</span>(), error.<span class="hljs-built_in">c_str</span>());
  <span class="hljs-keyword">if</span> (result-><span class="hljs-built_in">early_return</span>() != <span class="hljs-number">0</span>) {
    <span class="hljs-keyword">return</span> result-><span class="hljs-built_in">exit_code</span>();
  }

  <span class="hljs-comment">// Create a v8::Platform instance. `MultiIsolatePlatform::Create()` is a way</span>
  <span class="hljs-comment">// to create a v8::Platform instance that Node.js can use when creating</span>
  <span class="hljs-comment">// Worker threads. When no `MultiIsolatePlatform` instance is present,</span>
  <span class="hljs-comment">// Worker threads are disabled.</span>
  std::unique_ptr&#x3C;MultiIsolatePlatform> platform =
      MultiIsolatePlatform::<span class="hljs-built_in">Create</span>(<span class="hljs-number">4</span>);
  V8::<span class="hljs-built_in">InitializePlatform</span>(platform.<span class="hljs-built_in">get</span>());
  V8::<span class="hljs-built_in">Initialize</span>();

  <span class="hljs-comment">// See below for the contents of this function.</span>
  <span class="hljs-type">int</span> ret = <span class="hljs-built_in">RunNodeInstance</span>(
      platform.<span class="hljs-built_in">get</span>(), result-><span class="hljs-built_in">args</span>(), result-><span class="hljs-built_in">exec_args</span>());

  V8::<span class="hljs-built_in">Dispose</span>();
  V8::<span class="hljs-built_in">DisposePlatform</span>();

  node::<span class="hljs-built_in">TearDownOncePerProcess</span>();
  <span class="hljs-keyword">return</span> ret;
}</code> <button class="copy-button">copy</button></pre>
<h4>Per-instance state<span><a class="mark" href="#all_embedding_per-instance-state" id="all_embedding_per-instance-state">#</a></span><a aria-hidden="true" class="legacy" id="embedding_per_instance_state"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>The <code>CommonEnvironmentSetup</code> and <code>SpinEventLoop</code> utilities were added.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Node.js has a concept of a “Node.js instance”, that is commonly being referred
to as <code>node::Environment</code>. Each <code>node::Environment</code> is associated with:</p>
<ul>
<li>Exactly one <code>v8::Isolate</code>, i.e. one JS Engine instance,</li>
<li>Exactly one <code>uv_loop_t</code>, i.e. one event loop, and</li>
<li>A number of <code>v8::Context</code>s, but exactly one main <code>v8::Context</code>.</li>
<li>One <code>node::IsolateData</code> instance that contains information that could be
shared by multiple <code>node::Environment</code>s that use the same <code>v8::Isolate</code>.
Currently, no testing is performed for this scenario.</li>
</ul>
<p>In order to set up a <code>v8::Isolate</code>, an <code>v8::ArrayBuffer::Allocator</code> needs
to be provided. One possible choice is the default Node.js allocator, which
can be created through <code>node::ArrayBufferAllocator::Create()</code>. Using the Node.js
allocator allows minor performance optimizations when addons use the Node.js
C++ <code>Buffer</code> API, and is required in order to track <code>ArrayBuffer</code> memory in
<a href="#all_process_processmemoryusage"><code>process.memoryUsage()</code></a>.</p>
<p>Additionally, each <code>v8::Isolate</code> that is used for a Node.js instance needs to
be registered and unregistered with the <code>MultiIsolatePlatform</code> instance, if one
is being used, in order for the platform to know which event loop to use
for tasks scheduled by the <code>v8::Isolate</code>.</p>
<p>The <code>node::NewIsolate()</code> helper function creates a <code>v8::Isolate</code>,
sets it up with some Node.js-specific hooks (e.g. the Node.js error handler),
and registers it with the platform automatically.</p>
<pre><code class="language-cpp"><span class="hljs-function"><span class="hljs-type">int</span> <span class="hljs-title">RunNodeInstance</span><span class="hljs-params">(MultiIsolatePlatform* platform,
                    <span class="hljs-type">const</span> std::vector&#x3C;std::string>&#x26; args,
                    <span class="hljs-type">const</span> std::vector&#x3C;std::string>&#x26; exec_args)</span> </span>{
  <span class="hljs-type">int</span> exit_code = <span class="hljs-number">0</span>;

  <span class="hljs-comment">// Setup up a libuv event loop, v8::Isolate, and Node.js Environment.</span>
  std::vector&#x3C;std::string> errors;
  std::unique_ptr&#x3C;CommonEnvironmentSetup> setup =
      CommonEnvironmentSetup::<span class="hljs-built_in">Create</span>(platform, &#x26;errors, args, exec_args);
  <span class="hljs-keyword">if</span> (!setup) {
    <span class="hljs-keyword">for</span> (<span class="hljs-type">const</span> std::string&#x26; err : errors)
      <span class="hljs-built_in">fprintf</span>(stderr, <span class="hljs-string">"%s: %s\n"</span>, args[<span class="hljs-number">0</span>].<span class="hljs-built_in">c_str</span>(), err.<span class="hljs-built_in">c_str</span>());
    <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;
  }

  Isolate* isolate = setup-><span class="hljs-built_in">isolate</span>();
  Environment* env = setup-><span class="hljs-built_in">env</span>();

  {
    <span class="hljs-function">Locker <span class="hljs-title">locker</span><span class="hljs-params">(isolate)</span></span>;
    <span class="hljs-function">Isolate::Scope <span class="hljs-title">isolate_scope</span><span class="hljs-params">(isolate)</span></span>;
    <span class="hljs-function">HandleScope <span class="hljs-title">handle_scope</span><span class="hljs-params">(isolate)</span></span>;
    <span class="hljs-comment">// The v8::Context needs to be entered when node::CreateEnvironment() and</span>
    <span class="hljs-comment">// node::LoadEnvironment() are being called.</span>
    <span class="hljs-function">Context::Scope <span class="hljs-title">context_scope</span><span class="hljs-params">(setup->context())</span></span>;

    <span class="hljs-comment">// Set up the Node.js instance for execution, and run code inside of it.</span>
    <span class="hljs-comment">// There is also a variant that takes a callback and provides it with</span>
    <span class="hljs-comment">// the `require` and `process` objects, so that it can manually compile</span>
    <span class="hljs-comment">// and run scripts as needed.</span>
    <span class="hljs-comment">// The `require` function inside this script does *not* access the file</span>
    <span class="hljs-comment">// system, and can only load built-in Node.js modules.</span>
    <span class="hljs-comment">// `module.createRequire()` is being used to create one that is able to</span>
    <span class="hljs-comment">// load files from the disk, and uses the standard CommonJS file loader</span>
    <span class="hljs-comment">// instead of the internal-only `require` function.</span>
    MaybeLocal&#x3C;Value> loadenv_ret = node::<span class="hljs-built_in">LoadEnvironment</span>(
        env,
        <span class="hljs-string">"const publicRequire ="</span>
        <span class="hljs-string">"  require('node:module').createRequire(process.cwd() + '/');"</span>
        <span class="hljs-string">"globalThis.require = publicRequire;"</span>
        <span class="hljs-string">"require('node:vm').runInThisContext(process.argv[1]);"</span>);

    <span class="hljs-keyword">if</span> (loadenv_ret.<span class="hljs-built_in">IsEmpty</span>())  <span class="hljs-comment">// There has been a JS exception.</span>
      <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;

    exit_code = node::<span class="hljs-built_in">SpinEventLoop</span>(env).<span class="hljs-built_in">FromMaybe</span>(<span class="hljs-number">1</span>);

    <span class="hljs-comment">// node::Stop() can be used to explicitly stop the event loop and keep</span>
    <span class="hljs-comment">// further JavaScript from running. It can be called from any thread,</span>
    <span class="hljs-comment">// and will act like worker.terminate() if called from another thread.</span>
    node::<span class="hljs-built_in">Stop</span>(env);
  }

  <span class="hljs-keyword">return</span> exit_code;
}</code> <button class="copy-button">copy</button></pre></section>
        </section>
<section><h2>Child process<span><a class="mark" href="#all_child_process_child-process" id="all_child_process_child-process">#</a></span><a aria-hidden="true" class="legacy" id="child_process_child_process"></a></h2>

<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/child_process.js">lib/child_process.js</a></p>
<p>The <code>node:child_process</code> module provides the ability to spawn subprocesses 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="#all_child_process_child_processspawncommand-args-options"><code>child_process.spawn()</code></a> function:</p>

<pre class="with-48-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { spawn } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-keyword">const</span> ls = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'ls'</span>, [<span class="hljs-string">'-lh'</span>, <span class="hljs-string">'/usr'</span>]);

ls.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`stdout: <span class="hljs-subst">${data}</span>`</span>);
});

ls.<span class="hljs-property">stderr</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`stderr: <span class="hljs-subst">${data}</span>`</span>);
});

ls.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`child process exited with code <span class="hljs-subst">${code}</span>`</span>);
});</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { spawn } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">const</span> ls = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'ls'</span>, [<span class="hljs-string">'-lh'</span>, <span class="hljs-string">'/usr'</span>]);

ls.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`stdout: <span class="hljs-subst">${data}</span>`</span>);
});

ls.<span class="hljs-property">stderr</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`stderr: <span class="hljs-subst">${data}</span>`</span>);
});

ls.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`child process exited with code <span class="hljs-subst">${code}</span>`</span>);
});</code><button class="copy-button">copy</button></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 subprocess. These pipes have
limited (and platform-specific) capacity. If the subprocess writes to
stdout in excess of that limit without the output being captured, the
subprocess blocks 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 is performed using the <code>options.env.PATH</code> environment
variable if <code>env</code> is in the <code>options</code> object. Otherwise, <code>process.env.PATH</code> is
used. If <code>options.env</code> is set without <code>PATH</code>, lookup on Unix is performed
on a default search path search of <code>/usr/bin:/bin</code> (see your operating system's
manual for execvpe/execvp), on Windows the current processes environment
variable <code>PATH</code> is used.</p>
<p>On Windows, environment variables are case-insensitive. Node.js
lexicographically sorts the <code>env</code> keys and uses the first one that
case-insensitively matches. Only first (in lexicographic order) entry will be
passed to the subprocess. This might lead to issues on Windows when passing
objects to the <code>env</code> option that have multiple variants of the same key, such as
<code>PATH</code> and <code>Path</code>.</p>
<p>The <a href="#all_child_process_child_processspawncommand-args-options"><code>child_process.spawn()</code></a> method spawns the child process asynchronously,
without blocking the Node.js event loop. The <a href="#all_child_process_child_processspawnsynccommand-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>node:child_process</code> module provides a handful of
synchronous and asynchronous alternatives to <a href="#all_child_process_child_processspawncommand-args-options"><code>child_process.spawn()</code></a> and
<a href="#all_child_process_child_processspawnsynccommand-args-options"><code>child_process.spawnSync()</code></a>. Each of these alternatives are implemented on
top of <a href="#all_child_process_child_processspawncommand-args-options"><code>child_process.spawn()</code></a> or <a href="#all_child_process_child_processspawnsynccommand-args-options"><code>child_process.spawnSync()</code></a>.</p>
<ul>
<li><a href="#all_child_process_child_processexeccommand-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="#all_child_process_child_processexecfilefile-args-options-callback"><code>child_process.execFile()</code></a>: similar to <a href="#all_child_process_child_processexeccommand-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="#all_child_process_child_processforkmodulepath-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="#all_child_process_child_processexecsynccommand-options"><code>child_process.execSync()</code></a>: a synchronous version of
<a href="#all_child_process_child_processexeccommand-options-callback"><code>child_process.exec()</code></a> that will block the Node.js event loop.</li>
<li><a href="#all_child_process_child_processexecfilesyncfile-args-options"><code>child_process.execFileSync()</code></a>: a synchronous version of
<a href="#all_child_process_child_processexecfilefile-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="#all_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>
<section><h3>Asynchronous process creation<span><a class="mark" href="#all_child_process_asynchronous-process-creation" id="all_child_process_asynchronous-process-creation">#</a></span><a aria-hidden="true" class="legacy" id="child_process_asynchronous_process_creation"></a></h3>
<p>The <a href="#all_child_process_child_processspawncommand-args-options"><code>child_process.spawn()</code></a>, <a href="#all_child_process_child_processforkmodulepath-args-options"><code>child_process.fork()</code></a>, <a href="#all_child_process_child_processexeccommand-options-callback"><code>child_process.exec()</code></a>,
and <a href="#all_child_process_child_processexecfilefile-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="#all_child_process_class-childprocess"><code>ChildProcess</code></a> instance. These objects
implement the Node.js <a href="#all_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="#all_child_process_child_processexeccommand-options-callback"><code>child_process.exec()</code></a> and <a href="#all_child_process_child_processexecfilefile-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>
<h4>Spawning <code>.bat</code> and <code>.cmd</code> files on Windows<span><a class="mark" href="#all_child_process_spawning-bat-and-cmd-files-on-windows" id="all_child_process_spawning-bat-and-cmd-files-on-windows">#</a></span><a aria-hidden="true" class="legacy" id="child_process_spawning_bat_and_cmd_files_on_windows"></a></h4>
<p>The importance of the distinction between <a href="#all_child_process_child_processexeccommand-options-callback"><code>child_process.exec()</code></a> and
<a href="#all_child_process_child_processexecfilefile-args-options-callback"><code>child_process.execFile()</code></a> can vary based on platform. On Unix-type
operating systems (Unix, Linux, macOS) <a href="#all_child_process_child_processexecfilefile-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="#all_child_process_child_processexecfilefile-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="#all_child_process_child_processspawncommand-args-options"><code>child_process.spawn()</code></a> with the <code>shell</code> option set, with
<a href="#all_child_process_child_processexeccommand-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="#all_child_process_child_processexeccommand-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 class="with-54-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-comment">// OR...</span>
<span class="hljs-keyword">const</span> { exec, spawn } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);

<span class="hljs-title function_">exec</span>(<span class="hljs-string">'my.bat'</span>, <span class="hljs-function">(<span class="hljs-params">err, stdout, stderr</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err);
    <span class="hljs-keyword">return</span>;
  }
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(stdout);
});

<span class="hljs-comment">// Script with spaces in the filename:</span>
<span class="hljs-keyword">const</span> bat = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'"my script.cmd"'</span>, [<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>], { <span class="hljs-attr">shell</span>: <span class="hljs-literal">true</span> });
<span class="hljs-comment">// or:</span>
<span class="hljs-title function_">exec</span>(<span class="hljs-string">'"my script.cmd" a b'</span>, <span class="hljs-function">(<span class="hljs-params">err, stdout, stderr</span>) =></span> {
  <span class="hljs-comment">// ...</span>
});</code><code class="language-js mjs"><span class="hljs-comment">// OR...</span>
<span class="hljs-keyword">import</span> { exec, spawn } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;

<span class="hljs-title function_">exec</span>(<span class="hljs-string">'my.bat'</span>, <span class="hljs-function">(<span class="hljs-params">err, stdout, stderr</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err);
    <span class="hljs-keyword">return</span>;
  }
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(stdout);
});

<span class="hljs-comment">// Script with spaces in the filename:</span>
<span class="hljs-keyword">const</span> bat = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'"my script.cmd"'</span>, [<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>], { <span class="hljs-attr">shell</span>: <span class="hljs-literal">true</span> });
<span class="hljs-comment">// or:</span>
<span class="hljs-title function_">exec</span>(<span class="hljs-string">'"my script.cmd" a b'</span>, <span class="hljs-function">(<span class="hljs-params">err, stdout, stderr</span>) =></span> {
  <span class="hljs-comment">// ...</span>
});</code><button class="copy-button">copy</button></pre>
<h4><code>child_process.exec(command[, options][, callback])</code><span><a class="mark" href="#all_child_process_child_processexeccommand-options-callback" id="all_child_process_child_processexeccommand-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="child_process_child_process_exec_command_options_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.4.0</td>
<td><p>AbortSignal support was added.</p></td></tr>
<tr><td>v16.4.0, v14.18.0</td>
<td><p>The <code>cwd</code> option can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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> | <a href="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></a> Current working directory of the child process.
<strong>Default:</strong> <code>process.cwd()</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="#all_child_process_shell-requirements">Shell requirements</a> and <a href="#all_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>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> allows aborting the child process using an
AbortSignal.</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="#all_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><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.
<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="#all_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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a></li>
</ul>
</li>
<li>Returns: <a href="#all_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 class="with-47-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { exec } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);

<span class="hljs-title function_">exec</span>(<span class="hljs-string">'"/path/to/test file/test.sh" arg1 arg2'</span>);
<span class="hljs-comment">// Double quotes are used so that the space in the path is not interpreted as</span>
<span class="hljs-comment">// a delimiter of multiple arguments.</span>

<span class="hljs-title function_">exec</span>(<span class="hljs-string">'echo "The \\$HOME variable is $HOME"'</span>);
<span class="hljs-comment">// The $HOME variable is escaped in the first instance, but not in the second.</span></code><code class="language-js mjs"><span class="hljs-keyword">import</span> { exec } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;

<span class="hljs-title function_">exec</span>(<span class="hljs-string">'"/path/to/test file/test.sh" arg1 arg2'</span>);
<span class="hljs-comment">// Double quotes are used so that the space in the path is not interpreted as</span>
<span class="hljs-comment">// a delimiter of multiple arguments.</span>

<span class="hljs-title function_">exec</span>(<span class="hljs-string">'echo "The \\$HOME variable is $HOME"'</span>);
<span class="hljs-comment">// The $HOME variable is escaped in the first instance, but not in the second.</span></code><button class="copy-button">copy</button></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="#all_errors_class-error"><code>Error</code></a>. The <code>error.code</code> property will be
the exit code of the process. By convention, any exit code other than <code>0</code>
indicates an error. <code>error.signal</code> will be the signal that terminated the
process.</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 class="with-66-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { exec } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-title function_">exec</span>(<span class="hljs-string">'cat *.js missing_file | wc -l'</span>, <span class="hljs-function">(<span class="hljs-params">error, stdout, stderr</span>) =></span> {
  <span class="hljs-keyword">if</span> (error) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`exec error: <span class="hljs-subst">${error}</span>`</span>);
    <span class="hljs-keyword">return</span>;
  }
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`stdout: <span class="hljs-subst">${stdout}</span>`</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`stderr: <span class="hljs-subst">${stderr}</span>`</span>);
});</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { exec } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-title function_">exec</span>(<span class="hljs-string">'cat *.js missing_file | wc -l'</span>, <span class="hljs-function">(<span class="hljs-params">error, stdout, stderr</span>) =></span> {
  <span class="hljs-keyword">if</span> (error) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`exec error: <span class="hljs-subst">${error}</span>`</span>);
    <span class="hljs-keyword">return</span>;
  }
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`stdout: <span class="hljs-subst">${stdout}</span>`</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`stderr: <span class="hljs-subst">${stderr}</span>`</span>);
});</code><button class="copy-button">copy</button></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="#all_util_utilpromisifyoriginal"><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 class="with-64-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">const</span> exec = util.<span class="hljs-title function_">promisify</span>(<span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>).<span class="hljs-property">exec</span>);

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">lsExample</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">const</span> { stdout, stderr } = <span class="hljs-keyword">await</span> <span class="hljs-title function_">exec</span>(<span class="hljs-string">'ls'</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'stdout:'</span>, stdout);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'stderr:'</span>, stderr);
}
<span class="hljs-title function_">lsExample</span>();</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { promisify } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;
<span class="hljs-keyword">import</span> child_process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">const</span> exec = <span class="hljs-title function_">promisify</span>(child_process.<span class="hljs-property">exec</span>);

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">lsExample</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">const</span> { stdout, stderr } = <span class="hljs-keyword">await</span> <span class="hljs-title function_">exec</span>(<span class="hljs-string">'ls'</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'stdout:'</span>, stdout);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'stderr:'</span>, stderr);
}
<span class="hljs-title function_">lsExample</span>();</code><button class="copy-button">copy</button></pre>
<p>If the <code>signal</code> option is enabled, calling <code>.abort()</code> on the corresponding
<code>AbortController</code> is similar to calling <code>.kill()</code> on the child process except
the error passed to the callback will be an <code>AbortError</code>:</p>

<pre class="with-47-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { exec } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-keyword">const</span> controller = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
<span class="hljs-keyword">const</span> { signal } = controller;
<span class="hljs-keyword">const</span> child = <span class="hljs-title function_">exec</span>(<span class="hljs-string">'grep ssh'</span>, { signal }, <span class="hljs-function">(<span class="hljs-params">error</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(error); <span class="hljs-comment">// an AbortError</span>
});
controller.<span class="hljs-title function_">abort</span>();</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { exec } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">const</span> controller = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
<span class="hljs-keyword">const</span> { signal } = controller;
<span class="hljs-keyword">const</span> child = <span class="hljs-title function_">exec</span>(<span class="hljs-string">'grep ssh'</span>, { signal }, <span class="hljs-function">(<span class="hljs-params">error</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(error); <span class="hljs-comment">// an AbortError</span>
});
controller.<span class="hljs-title function_">abort</span>();</code><button class="copy-button">copy</button></pre>
<h4><code>child_process.execFile(file[, args][, options][, callback])</code><span><a class="mark" href="#all_child_process_child_processexecfilefile-args-options-callback" id="all_child_process_child_processexecfilefile-args-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="child_process_child_process_execfile_file_args_options_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.4.0, v14.18.0</td>
<td><p>The <code>cwd</code> option can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v15.4.0, v14.17.0</td>
<td><p>AbortSignal support was added.</p></td></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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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> | <a href="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></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="#all_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="#all_child_process_shell-requirements">Shell requirements</a> and
<a href="#all_child_process_default-windows-shell">Default Windows shell</a>. <strong>Default:</strong> <code>false</code> (no shell).</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> allows aborting the child process using an
AbortSignal.</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> Called with the output when process terminates.
<ul>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#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="#all_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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a></li>
</ul>
</li>
<li>Returns: <a href="#all_child_process_class-childprocess" class="type">&#x3C;ChildProcess></a></li>
</ul>
<p>The <code>child_process.execFile()</code> function is similar to <a href="#all_child_process_child_processexeccommand-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="#all_child_process_child_processexeccommand-options-callback"><code>child_process.exec()</code></a>.</p>
<p>The same options as <a href="#all_child_process_child_processexeccommand-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 class="with-74-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { execFile } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-keyword">const</span> child = <span class="hljs-title function_">execFile</span>(<span class="hljs-string">'node'</span>, [<span class="hljs-string">'--version'</span>], <span class="hljs-function">(<span class="hljs-params">error, stdout, stderr</span>) =></span> {
  <span class="hljs-keyword">if</span> (error) {
    <span class="hljs-keyword">throw</span> error;
  }
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(stdout);
});</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { execFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">const</span> child = <span class="hljs-title function_">execFile</span>(<span class="hljs-string">'node'</span>, [<span class="hljs-string">'--version'</span>], <span class="hljs-function">(<span class="hljs-params">error, stdout, stderr</span>) =></span> {
  <span class="hljs-keyword">if</span> (error) {
    <span class="hljs-keyword">throw</span> error;
  }
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(stdout);
});</code><button class="copy-button">copy</button></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="#all_util_utilpromisifyoriginal"><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 class="with-72-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">const</span> execFile = util.<span class="hljs-title function_">promisify</span>(<span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>).<span class="hljs-property">execFile</span>);
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">getVersion</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">const</span> { stdout } = <span class="hljs-keyword">await</span> <span class="hljs-title function_">execFile</span>(<span class="hljs-string">'node'</span>, [<span class="hljs-string">'--version'</span>]);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(stdout);
}
<span class="hljs-title function_">getVersion</span>();</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { promisify } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;
<span class="hljs-keyword">import</span> child_process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">const</span> execFile = <span class="hljs-title function_">promisify</span>(child_process.<span class="hljs-property">execFile</span>);
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">getVersion</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">const</span> { stdout } = <span class="hljs-keyword">await</span> <span class="hljs-title function_">execFile</span>(<span class="hljs-string">'node'</span>, [<span class="hljs-string">'--version'</span>]);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(stdout);
}
<span class="hljs-title function_">getVersion</span>();</code><button class="copy-button">copy</button></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>
<p>If the <code>signal</code> option is enabled, calling <code>.abort()</code> on the corresponding
<code>AbortController</code> is similar to calling <code>.kill()</code> on the child process except
the error passed to the callback will be an <code>AbortError</code>:</p>

<pre class="with-51-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { execFile } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-keyword">const</span> controller = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
<span class="hljs-keyword">const</span> { signal } = controller;
<span class="hljs-keyword">const</span> child = <span class="hljs-title function_">execFile</span>(<span class="hljs-string">'node'</span>, [<span class="hljs-string">'--version'</span>], { signal }, <span class="hljs-function">(<span class="hljs-params">error</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(error); <span class="hljs-comment">// an AbortError</span>
});
controller.<span class="hljs-title function_">abort</span>();</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { execFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">const</span> controller = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
<span class="hljs-keyword">const</span> { signal } = controller;
<span class="hljs-keyword">const</span> child = <span class="hljs-title function_">execFile</span>(<span class="hljs-string">'node'</span>, [<span class="hljs-string">'--version'</span>], { signal }, <span class="hljs-function">(<span class="hljs-params">error</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(error); <span class="hljs-comment">// an AbortError</span>
});
controller.<span class="hljs-title function_">abort</span>();</code><button class="copy-button">copy</button></pre>
<h4><code>child_process.fork(modulePath[, args][, options])</code><span><a class="mark" href="#all_child_process_child_processforkmodulepath-args-options" id="all_child_process_child_processforkmodulepath-args-options">#</a></span><a aria-hidden="true" class="legacy" id="child_process_child_process_fork_modulepath_args_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.4.0, v16.14.0</td>
<td><p>The <code>modulePath</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v16.4.0, v14.18.0</td>
<td><p>The <code>cwd</code> option can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v15.13.0, v14.18.0</td>
<td><p>timeout was added.</p></td></tr>
<tr><td>v15.11.0, v14.18.0</td>
<td><p>killSignal for AbortSignal was added.</p></td></tr>
<tr><td>v15.6.0, v14.17.0</td>
<td><p>AbortSignal support was added.</p></td></tr>
<tr><td>v13.2.0, 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> | <a href="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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> | <a href="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></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="#all_child_process_optionsdetached"><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>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="#all_child_process_advanced-serialization">Advanced serialization</a> for more details. <strong>Default:</strong> <code>'json'</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> Allows closing the child process using an
AbortSignal.</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 by timeout or abort signal. <strong>Default:</strong> <code>'SIGTERM'</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="#all_child_process_child_processspawncommand-args-options"><code>child_process.spawn()</code></a>'s
<a href="#all_child_process_optionsstdio"><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="#all_child_process_child_processspawncommand-args-options"><code>child_process.spawn()</code></a>'s <a href="#all_child_process_optionsstdio"><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>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>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>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>
</ul>
</li>
<li>Returns: <a href="#all_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="#all_child_process_child_processspawncommand-args-options"><code>child_process.spawn()</code></a> used specifically to spawn new Node.js processes.
Like <a href="#all_child_process_child_processspawncommand-args-options"><code>child_process.spawn()</code></a>, a <a href="#all_child_process_class-childprocess"><code>ChildProcess</code></a> object is returned. The
returned <a href="#all_child_process_class-childprocess"><code>ChildProcess</code></a> will have an additional communication channel
built-in that allows messages to be passed back and forth between the parent and
child. See <a href="#all_child_process_subprocesssendmessage-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="#all_process_processexecpath"><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="#all_child_process_child_processspawncommand-args-options"><code>child_process.spawn()</code></a> is not supported by
<code>child_process.fork()</code> and will be ignored if set.</p>
<p>If the <code>signal</code> option is enabled, calling <code>.abort()</code> on the corresponding
<code>AbortController</code> is similar to calling <code>.kill()</code> on the child process except
the error passed to the callback will be an <code>AbortError</code>:</p>

<pre class="with-47-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { fork } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-keyword">if</span> (process.<span class="hljs-property">argv</span>[<span class="hljs-number">2</span>] === <span class="hljs-string">'child'</span>) {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Hello from <span class="hljs-subst">${process.argv[<span class="hljs-number">2</span>]}</span>!`</span>);
  }, <span class="hljs-number">1_000</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-keyword">const</span> controller = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
  <span class="hljs-keyword">const</span> { signal } = controller;
  <span class="hljs-keyword">const</span> child = <span class="hljs-title function_">fork</span>(__filename, [<span class="hljs-string">'child'</span>], { signal });
  child.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
    <span class="hljs-comment">// This will be called with err being an AbortError if the controller aborts</span>
  });
  controller.<span class="hljs-title function_">abort</span>(); <span class="hljs-comment">// Stops the child process</span>
}</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { fork } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-keyword">if</span> (process.<span class="hljs-property">argv</span>[<span class="hljs-number">2</span>] === <span class="hljs-string">'child'</span>) {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Hello from <span class="hljs-subst">${process.argv[<span class="hljs-number">2</span>]}</span>!`</span>);
  }, <span class="hljs-number">1_000</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-keyword">const</span> controller = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
  <span class="hljs-keyword">const</span> { signal } = controller;
  <span class="hljs-keyword">const</span> child = <span class="hljs-title function_">fork</span>(<span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>, [<span class="hljs-string">'child'</span>], { signal });
  child.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
    <span class="hljs-comment">// This will be called with err being an AbortError if the controller aborts</span>
  });
  controller.<span class="hljs-title function_">abort</span>(); <span class="hljs-comment">// Stops the child process</span>
}</code><button class="copy-button">copy</button></pre>
<h4><code>child_process.spawn(command[, args][, options])</code><span><a class="mark" href="#all_child_process_child_processspawncommand-args-options" id="all_child_process_child_processspawncommand-args-options">#</a></span><a aria-hidden="true" class="legacy" id="child_process_child_process_spawn_command_args_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.4.0, v14.18.0</td>
<td><p>The <code>cwd</code> option can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v15.13.0, v14.18.0</td>
<td><p>timeout was added.</p></td></tr>
<tr><td>v15.11.0, v14.18.0</td>
<td><p>killSignal for AbortSignal was added.</p></td></tr>
<tr><td>v15.5.0, v14.17.0</td>
<td><p>AbortSignal support was added.</p></td></tr>
<tr><td>v13.2.0, 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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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> | <a href="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></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="#all_child_process_optionsstdio"><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="#all_child_process_optionsdetached"><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="#all_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="#all_child_process_shell-requirements">Shell requirements</a> and
<a href="#all_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>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> allows aborting the child process using an
AbortSignal.</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 by timeout or abort signal. <strong>Default:</strong> <code>'SIGTERM'</code>.</li>
</ul>
</li>
<li>Returns: <a href="#all_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"><span class="hljs-keyword">const</span> defaults = {
  <span class="hljs-attr">cwd</span>: <span class="hljs-literal">undefined</span>,
  <span class="hljs-attr">env</span>: process.<span class="hljs-property">env</span>,
};</code> <button class="copy-button">copy</button></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. If given,
but the path does not exist, the child process emits an <code>ENOENT</code> error
and exits immediately. <code>ENOENT</code> is also emitted when the command
does not exist.</p>
<p>Use <code>env</code> to specify environment variables that will be visible to the new
process, the default is <a href="#all_process_processenv"><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 class="with-48-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { spawn } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-keyword">const</span> ls = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'ls'</span>, [<span class="hljs-string">'-lh'</span>, <span class="hljs-string">'/usr'</span>]);

ls.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`stdout: <span class="hljs-subst">${data}</span>`</span>);
});

ls.<span class="hljs-property">stderr</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`stderr: <span class="hljs-subst">${data}</span>`</span>);
});

ls.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`child process exited with code <span class="hljs-subst">${code}</span>`</span>);
});</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { spawn } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">const</span> ls = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'ls'</span>, [<span class="hljs-string">'-lh'</span>, <span class="hljs-string">'/usr'</span>]);

ls.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`stdout: <span class="hljs-subst">${data}</span>`</span>);
});

ls.<span class="hljs-property">stderr</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`stderr: <span class="hljs-subst">${data}</span>`</span>);
});

ls.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`child process exited with code <span class="hljs-subst">${code}</span>`</span>);
});</code><button class="copy-button">copy</button></pre>
<p>Example: A very elaborate way to run <code>ps ax | grep ssh</code></p>

<pre class="with-48-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { spawn } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-keyword">const</span> ps = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'ps'</span>, [<span class="hljs-string">'ax'</span>]);
<span class="hljs-keyword">const</span> grep = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'grep'</span>, [<span class="hljs-string">'ssh'</span>]);

ps.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
  grep.<span class="hljs-property">stdin</span>.<span class="hljs-title function_">write</span>(data);
});

ps.<span class="hljs-property">stderr</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`ps stderr: <span class="hljs-subst">${data}</span>`</span>);
});

ps.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
  <span class="hljs-keyword">if</span> (code !== <span class="hljs-number">0</span>) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`ps process exited with code <span class="hljs-subst">${code}</span>`</span>);
  }
  grep.<span class="hljs-property">stdin</span>.<span class="hljs-title function_">end</span>();
});

grep.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data.<span class="hljs-title function_">toString</span>());
});

grep.<span class="hljs-property">stderr</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`grep stderr: <span class="hljs-subst">${data}</span>`</span>);
});

grep.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
  <span class="hljs-keyword">if</span> (code !== <span class="hljs-number">0</span>) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`grep process exited with code <span class="hljs-subst">${code}</span>`</span>);
  }
});</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { spawn } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">const</span> ps = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'ps'</span>, [<span class="hljs-string">'ax'</span>]);
<span class="hljs-keyword">const</span> grep = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'grep'</span>, [<span class="hljs-string">'ssh'</span>]);

ps.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
  grep.<span class="hljs-property">stdin</span>.<span class="hljs-title function_">write</span>(data);
});

ps.<span class="hljs-property">stderr</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`ps stderr: <span class="hljs-subst">${data}</span>`</span>);
});

ps.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
  <span class="hljs-keyword">if</span> (code !== <span class="hljs-number">0</span>) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`ps process exited with code <span class="hljs-subst">${code}</span>`</span>);
  }
  grep.<span class="hljs-property">stdin</span>.<span class="hljs-title function_">end</span>();
});

grep.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data.<span class="hljs-title function_">toString</span>());
});

grep.<span class="hljs-property">stderr</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`grep stderr: <span class="hljs-subst">${data}</span>`</span>);
});

grep.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
  <span class="hljs-keyword">if</span> (code !== <span class="hljs-number">0</span>) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`grep process exited with code <span class="hljs-subst">${code}</span>`</span>);
  }
});</code><button class="copy-button">copy</button></pre>
<p>Example of checking for failed <code>spawn</code>:</p>

<pre class="with-48-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { spawn } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-keyword">const</span> subprocess = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'bad_command'</span>);

subprocess.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'Failed to start subprocess.'</span>);
});</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { spawn } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">const</span> subprocess = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'bad_command'</span>);

subprocess.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'Failed to start subprocess.'</span>);
});</code><button class="copy-button">copy</button></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 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>
<p>If the <code>signal</code> option is enabled, calling <code>.abort()</code> on the corresponding
<code>AbortController</code> is similar to calling <code>.kill()</code> on the child process except
the error passed to the callback will be an <code>AbortError</code>:</p>

<pre class="with-48-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { spawn } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-keyword">const</span> controller = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
<span class="hljs-keyword">const</span> { signal } = controller;
<span class="hljs-keyword">const</span> grep = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'grep'</span>, [<span class="hljs-string">'ssh'</span>], { signal });
grep.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-comment">// This will be called with err being an AbortError if the controller aborts</span>
});
controller.<span class="hljs-title function_">abort</span>(); <span class="hljs-comment">// Stops the child process</span></code><code class="language-js mjs"><span class="hljs-keyword">import</span> { spawn } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">const</span> controller = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
<span class="hljs-keyword">const</span> { signal } = controller;
<span class="hljs-keyword">const</span> grep = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'grep'</span>, [<span class="hljs-string">'ssh'</span>], { signal });
grep.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-comment">// This will be called with err being an AbortError if the controller aborts</span>
});
controller.<span class="hljs-title function_">abort</span>(); <span class="hljs-comment">// Stops the child process</span></code><button class="copy-button">copy</button></pre>
<h5><code>options.detached</code><span><a class="mark" href="#all_child_process_optionsdetached" id="all_child_process_optionsdetached">#</a></span><a aria-hidden="true" class="legacy" id="child_process_options_detached"></a></h5>
<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 class="with-48-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { spawn } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-keyword">const</span> subprocess = <span class="hljs-title function_">spawn</span>(process.<span class="hljs-property">argv</span>[<span class="hljs-number">0</span>], [<span class="hljs-string">'child_program.js'</span>], {
  <span class="hljs-attr">detached</span>: <span class="hljs-literal">true</span>,
  <span class="hljs-attr">stdio</span>: <span class="hljs-string">'ignore'</span>,
});

subprocess.<span class="hljs-title function_">unref</span>();</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { spawn } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-keyword">const</span> subprocess = <span class="hljs-title function_">spawn</span>(process.<span class="hljs-property">argv</span>[<span class="hljs-number">0</span>], [<span class="hljs-string">'child_program.js'</span>], {
  <span class="hljs-attr">detached</span>: <span class="hljs-literal">true</span>,
  <span class="hljs-attr">stdio</span>: <span class="hljs-string">'ignore'</span>,
});

subprocess.<span class="hljs-title function_">unref</span>();</code><button class="copy-button">copy</button></pre>
<p>Alternatively one can redirect the child process' output into files:</p>

<pre class="with-48-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { openSync } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> { spawn } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-keyword">const</span> out = <span class="hljs-title function_">openSync</span>(<span class="hljs-string">'./out.log'</span>, <span class="hljs-string">'a'</span>);
<span class="hljs-keyword">const</span> err = <span class="hljs-title function_">openSync</span>(<span class="hljs-string">'./out.log'</span>, <span class="hljs-string">'a'</span>);

<span class="hljs-keyword">const</span> subprocess = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'prg'</span>, [], {
  <span class="hljs-attr">detached</span>: <span class="hljs-literal">true</span>,
  <span class="hljs-attr">stdio</span>: [ <span class="hljs-string">'ignore'</span>, out, err ],
});

subprocess.<span class="hljs-title function_">unref</span>();</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { openSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">import</span> { spawn } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">const</span> out = <span class="hljs-title function_">openSync</span>(<span class="hljs-string">'./out.log'</span>, <span class="hljs-string">'a'</span>);
<span class="hljs-keyword">const</span> err = <span class="hljs-title function_">openSync</span>(<span class="hljs-string">'./out.log'</span>, <span class="hljs-string">'a'</span>);

<span class="hljs-keyword">const</span> subprocess = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'prg'</span>, [], {
  <span class="hljs-attr">detached</span>: <span class="hljs-literal">true</span>,
  <span class="hljs-attr">stdio</span>: [ <span class="hljs-string">'ignore'</span>, out, err ],
});

subprocess.<span class="hljs-title function_">unref</span>();</code><button class="copy-button">copy</button></pre>
<h5><code>options.stdio</code><span><a class="mark" href="#all_child_process_optionsstdio" id="all_child_process_optionsstdio">#</a></span><a aria-hidden="true" class="legacy" id="child_process_options_stdio"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.6.0, v14.18.0</td>
<td><p>Added the <code>overlapped</code> stdio flag.</p></td></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="#all_child_process_subprocessstdin"><code>subprocess.stdin</code></a>,
<a href="#all_child_process_subprocessstdout"><code>subprocess.stdout</code></a>, and <a href="#all_child_process_subprocessstderr"><code>subprocess.stderr</code></a> streams on the
<a href="#all_child_process_class-childprocess"><code>ChildProcess</code></a> object. This is equivalent to setting the <code>options.stdio</code>
equal to <code>['pipe', 'pipe', 'pipe']</code>.</p>
<p>For convenience, <code>options.stdio</code> may be one of the following strings:</p>
<ul>
<li><code>'pipe'</code>: equivalent to <code>['pipe', 'pipe', 'pipe']</code> (the default)</li>
<li><code>'overlapped'</code>: equivalent to <code>['overlapped', 'overlapped', 'overlapped']</code></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="#all_child_process_subprocessstdio"><code>subprocess.stdio[fd]</code></a>. Pipes
created for fds 0, 1, and 2 are also available as <a href="#all_child_process_subprocessstdin"><code>subprocess.stdin</code></a>,
<a href="#all_child_process_subprocessstdout"><code>subprocess.stdout</code></a> and <a href="#all_child_process_subprocessstderr"><code>subprocess.stderr</code></a>, respectively.
These are not actual Unix pipes and therefore the child process
can not use them by their descriptor files,
e.g. <code>/dev/fd/2</code> or <code>/dev/stdout</code>.</p>
</li>
<li>
<p><code>'overlapped'</code>: Same as <code>'pipe'</code> except that the <code>FILE_FLAG_OVERLAPPED</code> flag
is set on the handle. This is necessary for overlapped I/O on the child
process's stdio handles. See the
<a href="https://docs.microsoft.com/en-us/windows/win32/fileio/synchronous-and-asynchronous-i-o">docs</a>
for more details. This is exactly the same as <code>'pipe'</code> on non-Windows
systems.</p>
</li>
<li>
<p><code>'ipc'</code>: Create an IPC channel for passing messages/file descriptors
between parent and child. A <a href="#all_child_process_class-childprocess"><code>ChildProcess</code></a> may have at most one IPC
stdio file descriptor. Setting this option enables the
<a href="#all_child_process_subprocesssendmessage-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="#all_process_processsendmessage-sendhandle-options-callback"><code>process.send()</code></a> and
<a href="#all_process_processdisconnect"><code>process.disconnect()</code></a> methods, as well as <a href="#all_process_event-disconnect"><code>'disconnect'</code></a> and
<a href="#all_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="#all_process_processsendmessage-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="#all_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 start 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 open in the parent process. It is shared with the child
process, similar to how <a href="#all_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 class="with-48-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { spawn } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-comment">// Child will use parent's stdios.</span>
<span class="hljs-title function_">spawn</span>(<span class="hljs-string">'prg'</span>, [], { <span class="hljs-attr">stdio</span>: <span class="hljs-string">'inherit'</span> });

<span class="hljs-comment">// Spawn child sharing only stderr.</span>
<span class="hljs-title function_">spawn</span>(<span class="hljs-string">'prg'</span>, [], { <span class="hljs-attr">stdio</span>: [<span class="hljs-string">'pipe'</span>, <span class="hljs-string">'pipe'</span>, process.<span class="hljs-property">stderr</span>] });

<span class="hljs-comment">// Open an extra fd=4, to interact with programs presenting a</span>
<span class="hljs-comment">// startd-style interface.</span>
<span class="hljs-title function_">spawn</span>(<span class="hljs-string">'prg'</span>, [], { <span class="hljs-attr">stdio</span>: [<span class="hljs-string">'pipe'</span>, <span class="hljs-literal">null</span>, <span class="hljs-literal">null</span>, <span class="hljs-literal">null</span>, <span class="hljs-string">'pipe'</span>] });</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { spawn } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-comment">// Child will use parent's stdios.</span>
<span class="hljs-title function_">spawn</span>(<span class="hljs-string">'prg'</span>, [], { <span class="hljs-attr">stdio</span>: <span class="hljs-string">'inherit'</span> });

<span class="hljs-comment">// Spawn child sharing only stderr.</span>
<span class="hljs-title function_">spawn</span>(<span class="hljs-string">'prg'</span>, [], { <span class="hljs-attr">stdio</span>: [<span class="hljs-string">'pipe'</span>, <span class="hljs-string">'pipe'</span>, process.<span class="hljs-property">stderr</span>] });

<span class="hljs-comment">// Open an extra fd=4, to interact with programs presenting a</span>
<span class="hljs-comment">// startd-style interface.</span>
<span class="hljs-title function_">spawn</span>(<span class="hljs-string">'prg'</span>, [], { <span class="hljs-attr">stdio</span>: [<span class="hljs-string">'pipe'</span>, <span class="hljs-literal">null</span>, <span class="hljs-literal">null</span>, <span class="hljs-literal">null</span>, <span class="hljs-string">'pipe'</span>] });</code><button class="copy-button">copy</button></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="#all_process_event-disconnect"><code>'disconnect'</code></a> event
or the <a href="#all_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>See also: <a href="#all_child_process_child_processexeccommand-options-callback"><code>child_process.exec()</code></a> and <a href="#all_child_process_child_processforkmodulepath-args-options"><code>child_process.fork()</code></a>.</p>
</section><section><h3>Synchronous process creation<span><a class="mark" href="#all_child_process_synchronous-process-creation" id="all_child_process_synchronous-process-creation">#</a></span><a aria-hidden="true" class="legacy" id="child_process_synchronous_process_creation"></a></h3>
<p>The <a href="#all_child_process_child_processspawnsynccommand-args-options"><code>child_process.spawnSync()</code></a>, <a href="#all_child_process_child_processexecsynccommand-options"><code>child_process.execSync()</code></a>, and
<a href="#all_child_process_child_processexecfilesyncfile-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>
<h4><code>child_process.execFileSync(file[, args][, options])</code><span><a class="mark" href="#all_child_process_child_processexecfilesyncfile-args-options" id="all_child_process_child_processexecfilesyncfile-args-options">#</a></span><a aria-hidden="true" class="legacy" id="child_process_child_process_execfilesync_file_args_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.4.0, v14.18.0</td>
<td><p>The <code>cwd</code> option can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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> | <a href="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></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="#all_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. If <code>stdio[0]</code> is set to <code>'pipe'</code>, 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.
See <a href="#all_child_process_child_processspawncommand-args-options"><code>child_process.spawn()</code></a>'s <a href="#all_child_process_optionsstdio"><code>stdio</code></a>. <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="#all_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="#all_child_process_shell-requirements">Shell requirements</a> and
<a href="#all_child_process_default-windows-shell">Default Windows shell</a>. <strong>Default:</strong> <code>false</code> (no shell).</li>
</ul>
</li>
<li>Returns: <a href="#all_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="#all_child_process_child_processexecfilefile-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="#all_errors_class-error"><code>Error</code></a> that will include the full result of the underlying
<a href="#all_child_process_child_processspawnsynccommand-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>

<pre class="with-55-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { execFileSync } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);

<span class="hljs-keyword">try</span> {
  <span class="hljs-keyword">const</span> stdout = <span class="hljs-title function_">execFileSync</span>(<span class="hljs-string">'my-script.sh'</span>, [<span class="hljs-string">'my-arg'</span>], {
    <span class="hljs-comment">// Capture stdout and stderr from child process. Overrides the</span>
    <span class="hljs-comment">// default behavior of streaming child stderr to the parent stderr</span>
    <span class="hljs-attr">stdio</span>: <span class="hljs-string">'pipe'</span>,

    <span class="hljs-comment">// Use utf8 encoding for stdio pipes</span>
    <span class="hljs-attr">encoding</span>: <span class="hljs-string">'utf8'</span>,
  });

  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(stdout);
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-keyword">if</span> (err.<span class="hljs-property">code</span>) {
    <span class="hljs-comment">// Spawning child process failed</span>
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err.<span class="hljs-property">code</span>);
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-comment">// Child was spawned but exited with non-zero exit code</span>
    <span class="hljs-comment">// Error contains any stdout and stderr from the child</span>
    <span class="hljs-keyword">const</span> { stdout, stderr } = err;

    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>({ stdout, stderr });
  }
}</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { execFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;

<span class="hljs-keyword">try</span> {
  <span class="hljs-keyword">const</span> stdout = <span class="hljs-title function_">execFileSync</span>(<span class="hljs-string">'my-script.sh'</span>, [<span class="hljs-string">'my-arg'</span>], {
    <span class="hljs-comment">// Capture stdout and stderr from child process. Overrides the</span>
    <span class="hljs-comment">// default behavior of streaming child stderr to the parent stderr</span>
    <span class="hljs-attr">stdio</span>: <span class="hljs-string">'pipe'</span>,

    <span class="hljs-comment">// Use utf8 encoding for stdio pipes</span>
    <span class="hljs-attr">encoding</span>: <span class="hljs-string">'utf8'</span>,
  });

  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(stdout);
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-keyword">if</span> (err.<span class="hljs-property">code</span>) {
    <span class="hljs-comment">// Spawning child process failed</span>
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err.<span class="hljs-property">code</span>);
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-comment">// Child was spawned but exited with non-zero exit code</span>
    <span class="hljs-comment">// Error contains any stdout and stderr from the child</span>
    <span class="hljs-keyword">const</span> { stdout, stderr } = err;

    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>({ stdout, stderr });
  }
}</code><button class="copy-button">copy</button></pre>
<h4><code>child_process.execSync(command[, options])</code><span><a class="mark" href="#all_child_process_child_processexecsynccommand-options" id="all_child_process_child_processexecsynccommand-options">#</a></span><a aria-hidden="true" class="legacy" id="child_process_child_process_execsync_command_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.4.0, v14.18.0</td>
<td><p>The <code>cwd</code> option can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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> | <a href="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></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="#all_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. If <code>stdio[0]</code> is set to <code>'pipe'</code>, 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.
See <a href="#all_child_process_child_processspawncommand-args-options"><code>child_process.spawn()</code></a>'s <a href="#all_child_process_optionsstdio"><code>stdio</code></a>. <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="#all_child_process_shell-requirements">Shell requirements</a> and <a href="#all_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="#all_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="#all_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="#all_child_process_child_processexeccommand-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="#all_errors_class-error"><code>Error</code></a> object will contain the entire result from
<a href="#all_child_process_child_processspawnsynccommand-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>
<h4><code>child_process.spawnSync(command[, args][, options])</code><span><a class="mark" href="#all_child_process_child_processspawnsynccommand-args-options" id="all_child_process_child_processspawnsynccommand-args-options">#</a></span><a aria-hidden="true" class="legacy" id="child_process_child_process_spawnsync_command_args_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.4.0, v14.18.0</td>
<td><p>The <code>cwd</code> option can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></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>v5.7.0</td>
<td><p>The <code>shell</code> option is supported now.</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>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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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> | <a href="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></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="#all_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. If <code>stdio[0]</code> is set to <code>'pipe'</code>, 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.
See <a href="#all_child_process_child_processspawncommand-args-options"><code>child_process.spawn()</code></a>'s <a href="#all_child_process_optionsstdio"><code>stdio</code></a>. <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 and any output is
truncated. See caveat at <a href="#all_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="#all_child_process_shell-requirements">Shell requirements</a> and
<a href="#all_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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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="#all_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="#all_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="#all_child_process_child_processspawncommand-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>
</section><section><h3>Class: <code>ChildProcess</code><span><a class="mark" href="#all_child_process_class-childprocess" id="all_child_process_class-childprocess">#</a></span><a aria-hidden="true" class="legacy" id="child_process_class_childprocess"></a></h3>
<div class="api_metadata">
<span>Added in: v2.2.0</span>
</div>
<ul>
<li>Extends: <a href="#all_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="#all_child_process_child_processspawncommand-args-options"><code>child_process.spawn()</code></a>, <a href="#all_child_process_child_processexeccommand-options-callback"><code>child_process.exec()</code></a>,
<a href="#all_child_process_child_processexecfilefile-args-options-callback"><code>child_process.execFile()</code></a>, or <a href="#all_child_process_child_processforkmodulepath-args-options"><code>child_process.fork()</code></a> methods to create
instances of <code>ChildProcess</code>.</p>
<h4>Event: <code>'close'</code><span><a class="mark" href="#all_child_process_event-close" id="all_child_process_event-close">#</a></span><a aria-hidden="true" class="legacy" id="child_process_event_close"></a></h4>
<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 after a process has ended <em>and</em> the stdio
streams of a child process have been closed. This is distinct from the
<a href="#all_child_process_event-exit"><code>'exit'</code></a> event, since multiple processes might share the same stdio
streams. The <code>'close'</code> event will always emit after <a href="#all_child_process_event-exit"><code>'exit'</code></a> was
already emitted, or <a href="#all_child_process_event-error"><code>'error'</code></a> if the child failed to spawn.</p>

<pre class="with-48-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { spawn } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-keyword">const</span> ls = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'ls'</span>, [<span class="hljs-string">'-lh'</span>, <span class="hljs-string">'/usr'</span>]);

ls.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`stdout: <span class="hljs-subst">${data}</span>`</span>);
});

ls.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`child process close all stdio with code <span class="hljs-subst">${code}</span>`</span>);
});

ls.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`child process exited with code <span class="hljs-subst">${code}</span>`</span>);
});</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { spawn } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">const</span> ls = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'ls'</span>, [<span class="hljs-string">'-lh'</span>, <span class="hljs-string">'/usr'</span>]);

ls.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`stdout: <span class="hljs-subst">${data}</span>`</span>);
});

ls.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`child process close all stdio with code <span class="hljs-subst">${code}</span>`</span>);
});

ls.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`child process exited with code <span class="hljs-subst">${code}</span>`</span>);
});</code><button class="copy-button">copy</button></pre>
<h4>Event: <code>'disconnect'</code><span><a class="mark" href="#all_child_process_event-disconnect" id="all_child_process_event-disconnect">#</a></span><a aria-hidden="true" class="legacy" id="child_process_event_disconnect"></a></h4>
<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="#all_child_process_subprocessdisconnect"><code>subprocess.disconnect()</code></a> method in parent process or
<a href="#all_process_processdisconnect"><code>process.disconnect()</code></a> in child process. After disconnecting it is no longer
possible to send or receive messages, and the <a href="#all_child_process_subprocessconnected"><code>subprocess.connected</code></a>
property is <code>false</code>.</p>
<h4>Event: <code>'error'</code><span><a class="mark" href="#all_child_process_event-error" id="all_child_process_event-error">#</a></span><a aria-hidden="true" class="legacy" id="child_process_event_error"></a></h4>
<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>
<ul>
<li>The process could not be spawned.</li>
<li>The process could not be killed.</li>
<li>Sending a message to the child process failed.</li>
<li>The child process was aborted via the <code>signal</code> option.</li>
</ul>
<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="#all_child_process_subprocesskillsignal"><code>subprocess.kill()</code></a> and <a href="#all_child_process_subprocesssendmessage-sendhandle-options-callback"><code>subprocess.send()</code></a>.</p>
<h4>Event: <code>'exit'</code><span><a class="mark" href="#all_child_process_event-exit" id="all_child_process_event-exit">#</a></span><a aria-hidden="true" class="legacy" id="child_process_event_exit"></a></h4>
<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>
<h4>Event: <code>'message'</code><span><a class="mark" href="#all_child_process_event-message" id="all_child_process_event-message">#</a></span><a aria-hidden="true" class="legacy" id="child_process_event_message"></a></h4>
<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="#all_net_serverlistenhandle-backlog-callback" class="type">&#x3C;Handle></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> <code>undefined</code> or a <a href="#all_net_class-netsocket"><code>net.Socket</code></a>,
<a href="#all_net_class-netserver"><code>net.Server</code></a>, or <a href="#all_dgram_class-dgramsocket"><code>dgram.Socket</code></a> object.</li>
</ul>
<p>The <code>'message'</code> event is triggered when a child process uses
<a href="#all_process_processsendmessage-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="#all_child_process_advanced-serialization">Advanced serialization</a> for more details.</p>
<h4>Event: <code>'spawn'</code><span><a class="mark" href="#all_child_process_event-spawn" id="all_child_process_event-spawn">#</a></span><a aria-hidden="true" class="legacy" id="child_process_event_spawn"></a></h4>
<div class="api_metadata">
<span>Added in: v15.1.0, v14.17.0</span>
</div>
<p>The <code>'spawn'</code> event is emitted once the child process has spawned successfully.
If the child process does not spawn successfully, the <code>'spawn'</code> event is not
emitted and the <code>'error'</code> event is emitted instead.</p>
<p>If emitted, the <code>'spawn'</code> event comes before all other events and before any
data is received via <code>stdout</code> or <code>stderr</code>.</p>
<p>The <code>'spawn'</code> event will fire regardless of whether an error occurs <strong>within</strong>
the spawned process. For example, if <code>bash some-command</code> spawns successfully,
the <code>'spawn'</code> event will fire, though <code>bash</code> may fail to spawn <code>some-command</code>.
This caveat also applies when using <code>{ shell: true }</code>.</p>
<h4><code>subprocess.channel</code><span><a class="mark" href="#all_child_process_subprocesschannel" id="all_child_process_subprocesschannel">#</a></span><a aria-hidden="true" class="legacy" id="child_process_subprocess_channel"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.0.0</td>
<td><p>The object no longer accidentally exposes native C++ bindings.</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><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 exists, this property is <code>undefined</code>.</p>
<h5><code>subprocess.channel.ref()</code><span><a class="mark" href="#all_child_process_subprocesschannelref" id="all_child_process_subprocesschannelref">#</a></span><a aria-hidden="true" class="legacy" id="child_process_subprocess_channel_ref"></a></h5>
<div class="api_metadata">
<span>Added in: v7.1.0</span>
</div>
<p>This method makes the IPC channel keep the event loop of the parent process
running if <code>.unref()</code> has been called before.</p>
<h5><code>subprocess.channel.unref()</code><span><a class="mark" href="#all_child_process_subprocesschannelunref" id="all_child_process_subprocesschannelunref">#</a></span><a aria-hidden="true" class="legacy" id="child_process_subprocess_channel_unref"></a></h5>
<div class="api_metadata">
<span>Added in: v7.1.0</span>
</div>
<p>This method makes the IPC channel not keep the event loop of the parent process
running, and lets it finish even while the channel is open.</p>
<h4><code>subprocess.connected</code><span><a class="mark" href="#all_child_process_subprocessconnected" id="all_child_process_subprocessconnected">#</a></span><a aria-hidden="true" class="legacy" id="child_process_subprocess_connected"></a></h4>
<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>
<h4><code>subprocess.disconnect()</code><span><a class="mark" href="#all_child_process_subprocessdisconnect" id="all_child_process_subprocessdisconnect">#</a></span><a aria-hidden="true" class="legacy" id="child_process_subprocess_disconnect"></a></h4>
<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="#all_child_process_child_processforkmodulepath-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>
<h4><code>subprocess.exitCode</code><span><a class="mark" href="#all_child_process_subprocessexitcode" id="all_child_process_subprocessexitcode">#</a></span><a aria-hidden="true" class="legacy" id="child_process_subprocess_exitcode"></a></h4>
<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>
<h4><code>subprocess.kill([signal])</code><span><a class="mark" href="#all_child_process_subprocesskillsignal" id="all_child_process_subprocesskillsignal">#</a></span><a aria-hidden="true" class="legacy" id="child_process_subprocess_kill_signal"></a></h4>
<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 class="with-48-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { spawn } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-keyword">const</span> grep = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'grep'</span>, [<span class="hljs-string">'ssh'</span>]);

grep.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">(<span class="hljs-params">code, signal</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(
    <span class="hljs-string">`child process terminated due to receipt of signal <span class="hljs-subst">${signal}</span>`</span>);
});

<span class="hljs-comment">// Send SIGHUP to process.</span>
grep.<span class="hljs-title function_">kill</span>(<span class="hljs-string">'SIGHUP'</span>);</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { spawn } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">const</span> grep = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'grep'</span>, [<span class="hljs-string">'ssh'</span>]);

grep.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">(<span class="hljs-params">code, signal</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(
    <span class="hljs-string">`child process terminated due to receipt of signal <span class="hljs-subst">${signal}</span>`</span>);
});

<span class="hljs-comment">// Send SIGHUP to process.</span>
grep.<span class="hljs-title function_">kill</span>(<span class="hljs-string">'SIGHUP'</span>);</code><button class="copy-button">copy</button></pre>
<p>The <a href="#all_child_process_class-childprocess"><code>ChildProcess</code></a> object may emit an <a href="#all_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 Windows, where POSIX signals do not exist, the <code>signal</code> argument will be
ignored, and the process will be killed forcefully and abruptly (similar to
<code>'SIGKILL'</code>).
See <a href="#all_process_signal-events">Signal Events</a> for more details.</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 class="with-48-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { spawn } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);

<span class="hljs-keyword">const</span> subprocess = <span class="hljs-title function_">spawn</span>(
  <span class="hljs-string">'sh'</span>,
  [
    <span class="hljs-string">'-c'</span>,
    <span class="hljs-string">`node -e "setInterval(() => {
      console.log(process.pid, 'is alive')
    }, 500);"`</span>,
  ], {
    <span class="hljs-attr">stdio</span>: [<span class="hljs-string">'inherit'</span>, <span class="hljs-string">'inherit'</span>, <span class="hljs-string">'inherit'</span>],
  },
);

<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
  subprocess.<span class="hljs-title function_">kill</span>(); <span class="hljs-comment">// Does not terminate the Node.js process in the shell.</span>
}, <span class="hljs-number">2000</span>);</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { spawn } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;

<span class="hljs-keyword">const</span> subprocess = <span class="hljs-title function_">spawn</span>(
  <span class="hljs-string">'sh'</span>,
  [
    <span class="hljs-string">'-c'</span>,
    <span class="hljs-string">`node -e "setInterval(() => {
      console.log(process.pid, 'is alive')
    }, 500);"`</span>,
  ], {
    <span class="hljs-attr">stdio</span>: [<span class="hljs-string">'inherit'</span>, <span class="hljs-string">'inherit'</span>, <span class="hljs-string">'inherit'</span>],
  },
);

<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
  subprocess.<span class="hljs-title function_">kill</span>(); <span class="hljs-comment">// Does not terminate the Node.js process in the shell.</span>
}, <span class="hljs-number">2000</span>);</code><button class="copy-button">copy</button></pre>
<h4><code>subprocess[Symbol.dispose]()</code><span><a class="mark" href="#all_child_process_subprocesssymboldispose" id="all_child_process_subprocesssymboldispose">#</a></span><a aria-hidden="true" class="legacy" id="child_process_subprocess_symbol_dispose"></a></h4>
<div class="api_metadata">
<span>Added in: v20.5.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Calls <a href="#all_child_process_subprocesskillsignal"><code>subprocess.kill()</code></a> with <code>'SIGTERM'</code>.</p>
<h4><code>subprocess.killed</code><span><a class="mark" href="#all_child_process_subprocesskilled" id="all_child_process_subprocesskilled">#</a></span><a aria-hidden="true" class="legacy" id="child_process_subprocess_killed"></a></h4>
<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>
<h4><code>subprocess.pid</code><span><a class="mark" href="#all_child_process_subprocesspid" id="all_child_process_subprocesspid">#</a></span><a aria-hidden="true" class="legacy" id="child_process_subprocess_pid"></a></h4>
<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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a></li>
</ul>
<p>Returns the process identifier (PID) of the child process. If the child process
fails to spawn due to errors, then the value is <code>undefined</code> and <code>error</code> is
emitted.</p>

<pre class="with-48-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { spawn } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-keyword">const</span> grep = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'grep'</span>, [<span class="hljs-string">'ssh'</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Spawned child pid: <span class="hljs-subst">${grep.pid}</span>`</span>);
grep.<span class="hljs-property">stdin</span>.<span class="hljs-title function_">end</span>();</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { spawn } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">const</span> grep = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'grep'</span>, [<span class="hljs-string">'ssh'</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Spawned child pid: <span class="hljs-subst">${grep.pid}</span>`</span>);
grep.<span class="hljs-property">stdin</span>.<span class="hljs-title function_">end</span>();</code><button class="copy-button">copy</button></pre>
<h4><code>subprocess.ref()</code><span><a class="mark" href="#all_child_process_subprocessref" id="all_child_process_subprocessref">#</a></span><a aria-hidden="true" class="legacy" id="child_process_subprocess_ref"></a></h4>
<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 class="with-48-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { spawn } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-keyword">const</span> subprocess = <span class="hljs-title function_">spawn</span>(process.<span class="hljs-property">argv</span>[<span class="hljs-number">0</span>], [<span class="hljs-string">'child_program.js'</span>], {
  <span class="hljs-attr">detached</span>: <span class="hljs-literal">true</span>,
  <span class="hljs-attr">stdio</span>: <span class="hljs-string">'ignore'</span>,
});

subprocess.<span class="hljs-title function_">unref</span>();
subprocess.<span class="hljs-title function_">ref</span>();</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { spawn } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-keyword">const</span> subprocess = <span class="hljs-title function_">spawn</span>(process.<span class="hljs-property">argv</span>[<span class="hljs-number">0</span>], [<span class="hljs-string">'child_program.js'</span>], {
  <span class="hljs-attr">detached</span>: <span class="hljs-literal">true</span>,
  <span class="hljs-attr">stdio</span>: <span class="hljs-string">'ignore'</span>,
});

subprocess.<span class="hljs-title function_">unref</span>();
subprocess.<span class="hljs-title function_">ref</span>();</code><button class="copy-button">copy</button></pre>
<h4><code>subprocess.send(message[, sendHandle[, options]][, callback])</code><span><a class="mark" href="#all_child_process_subprocesssendmessage-sendhandle-options-callback" id="all_child_process_subprocesssendmessage-sendhandle-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="child_process_subprocess_send_message_sendhandle_options_callback"></a></h4>
<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="#all_net_serverlistenhandle-backlog-callback" class="type">&#x3C;Handle></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> <code>undefined</code>, or a <a href="#all_net_class-netsocket"><code>net.Socket</code></a>,
<a href="#all_net_class-netserver"><code>net.Server</code></a>, or <a href="#all_dgram_class-dgramsocket"><code>dgram.Socket</code></a> object.</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> 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:
<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="#all_child_process_child_processforkmodulepath-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="#all_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 class="with-60-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { fork } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-keyword">const</span> forkedProcess = <span class="hljs-title function_">fork</span>(<span class="hljs-string">`<span class="hljs-subst">${__dirname}</span>/sub.js`</span>);

forkedProcess.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'PARENT got message:'</span>, message);
});

<span class="hljs-comment">// Causes the child to print: CHILD got message: { hello: 'world' }</span>
forkedProcess.<span class="hljs-title function_">send</span>({ <span class="hljs-attr">hello</span>: <span class="hljs-string">'world'</span> });</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { fork } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">const</span> forkedProcess = <span class="hljs-title function_">fork</span>(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-keyword">import</span>.meta.dirname}</span>/sub.js`</span>);

forkedProcess.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'PARENT got message:'</span>, message);
});

<span class="hljs-comment">// Causes the child to print: CHILD got message: { hello: 'world' }</span>
forkedProcess.<span class="hljs-title function_">send</span>({ <span class="hljs-attr">hello</span>: <span class="hljs-string">'world'</span> });</code><button class="copy-button">copy</button></pre>
<p>And then the child script, <code>'sub.js'</code> might look like this:</p>
<pre><code class="language-js">process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'CHILD got message:'</span>, message);
});

<span class="hljs-comment">// Causes the parent to print: PARENT got message: { foo: 'bar', baz: null }</span>
process.<span class="hljs-title function_">send</span>({ <span class="hljs-attr">foo</span>: <span class="hljs-string">'bar'</span>, <span class="hljs-attr">baz</span>: <span class="hljs-title class_">NaN</span> });</code> <button class="copy-button">copy</button></pre>
<p>Child Node.js processes will have a <a href="#all_process_processsendmessage-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="#all_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="#all_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. Sending IPC sockets is
not supported on Windows.</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="#all_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="#all_child_process_class-childprocess"><code>ChildProcess</code></a> object. This can
happen, for instance, when the child process has already exited.</p>
<p><code>subprocess.send()</code> will return <code>false</code> if the channel has closed or when the
backlog of unsent messages exceeds a threshold that makes it unwise to send
more. Otherwise, the method returns <code>true</code>. The <code>callback</code> function can be
used to implement flow control.</p>
<h5>Example: sending a server object<span><a class="mark" href="#all_child_process_example-sending-a-server-object" id="all_child_process_example-sending-a-server-object">#</a></span><a aria-hidden="true" class="legacy" id="child_process_example_sending_a_server_object"></a></h5>
<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 class="with-47-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { fork } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-keyword">const</span> { createServer } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:net'</span>);

<span class="hljs-keyword">const</span> subprocess = <span class="hljs-title function_">fork</span>(<span class="hljs-string">'subprocess.js'</span>);

<span class="hljs-comment">// Open up the server object and send the handle.</span>
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'connection'</span>, <span class="hljs-function">(<span class="hljs-params">socket</span>) =></span> {
  socket.<span class="hljs-title function_">end</span>(<span class="hljs-string">'handled by parent'</span>);
});
server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">1337</span>, <span class="hljs-function">() =></span> {
  subprocess.<span class="hljs-title function_">send</span>(<span class="hljs-string">'server'</span>, server);
});</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { fork } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">import</span> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:net'</span>;

<span class="hljs-keyword">const</span> subprocess = <span class="hljs-title function_">fork</span>(<span class="hljs-string">'subprocess.js'</span>);

<span class="hljs-comment">// Open up the server object and send the handle.</span>
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'connection'</span>, <span class="hljs-function">(<span class="hljs-params">socket</span>) =></span> {
  socket.<span class="hljs-title function_">end</span>(<span class="hljs-string">'handled by parent'</span>);
});
server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">1337</span>, <span class="hljs-function">() =></span> {
  subprocess.<span class="hljs-title function_">send</span>(<span class="hljs-string">'server'</span>, server);
});</code><button class="copy-button">copy</button></pre>
<p>The child would then receive the server object as:</p>
<pre><code class="language-js">process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">m, server</span>) =></span> {
  <span class="hljs-keyword">if</span> (m === <span class="hljs-string">'server'</span>) {
    server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'connection'</span>, <span class="hljs-function">(<span class="hljs-params">socket</span>) =></span> {
      socket.<span class="hljs-title function_">end</span>(<span class="hljs-string">'handled by child'</span>);
    });
  }
});</code> <button class="copy-button">copy</button></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>node:net</code> module,
<code>node: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, only
supported on Unix platforms.</p>
<h5>Example: sending a socket object<span><a class="mark" href="#all_child_process_example-sending-a-socket-object" id="all_child_process_example-sending-a-socket-object">#</a></span><a aria-hidden="true" class="legacy" id="child_process_example_sending_a_socket_object"></a></h5>
<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 class="with-47-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { fork } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-keyword">const</span> { createServer } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:net'</span>);

<span class="hljs-keyword">const</span> normal = <span class="hljs-title function_">fork</span>(<span class="hljs-string">'subprocess.js'</span>, [<span class="hljs-string">'normal'</span>]);
<span class="hljs-keyword">const</span> special = <span class="hljs-title function_">fork</span>(<span class="hljs-string">'subprocess.js'</span>, [<span class="hljs-string">'special'</span>]);

<span class="hljs-comment">// Open up the server and send sockets to child. Use pauseOnConnect to prevent</span>
<span class="hljs-comment">// the sockets from being read before they are sent to the child process.</span>
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>({ <span class="hljs-attr">pauseOnConnect</span>: <span class="hljs-literal">true</span> });
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'connection'</span>, <span class="hljs-function">(<span class="hljs-params">socket</span>) =></span> {

  <span class="hljs-comment">// If this is special priority...</span>
  <span class="hljs-keyword">if</span> (socket.<span class="hljs-property">remoteAddress</span> === <span class="hljs-string">'74.125.127.100'</span>) {
    special.<span class="hljs-title function_">send</span>(<span class="hljs-string">'socket'</span>, socket);
    <span class="hljs-keyword">return</span>;
  }
  <span class="hljs-comment">// This is normal priority.</span>
  normal.<span class="hljs-title function_">send</span>(<span class="hljs-string">'socket'</span>, socket);
});
server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">1337</span>);</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { fork } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">import</span> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:net'</span>;

<span class="hljs-keyword">const</span> normal = <span class="hljs-title function_">fork</span>(<span class="hljs-string">'subprocess.js'</span>, [<span class="hljs-string">'normal'</span>]);
<span class="hljs-keyword">const</span> special = <span class="hljs-title function_">fork</span>(<span class="hljs-string">'subprocess.js'</span>, [<span class="hljs-string">'special'</span>]);

<span class="hljs-comment">// Open up the server and send sockets to child. Use pauseOnConnect to prevent</span>
<span class="hljs-comment">// the sockets from being read before they are sent to the child process.</span>
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>({ <span class="hljs-attr">pauseOnConnect</span>: <span class="hljs-literal">true</span> });
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'connection'</span>, <span class="hljs-function">(<span class="hljs-params">socket</span>) =></span> {

  <span class="hljs-comment">// If this is special priority...</span>
  <span class="hljs-keyword">if</span> (socket.<span class="hljs-property">remoteAddress</span> === <span class="hljs-string">'74.125.127.100'</span>) {
    special.<span class="hljs-title function_">send</span>(<span class="hljs-string">'socket'</span>, socket);
    <span class="hljs-keyword">return</span>;
  }
  <span class="hljs-comment">// This is normal priority.</span>
  normal.<span class="hljs-title function_">send</span>(<span class="hljs-string">'socket'</span>, socket);
});
server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">1337</span>);</code><button class="copy-button">copy</button></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.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">m, socket</span>) =></span> {
  <span class="hljs-keyword">if</span> (m === <span class="hljs-string">'socket'</span>) {
    <span class="hljs-keyword">if</span> (socket) {
      <span class="hljs-comment">// Check that the client socket exists.</span>
      <span class="hljs-comment">// It is possible for the socket to be closed between the time it is</span>
      <span class="hljs-comment">// sent and the time it is received in the child process.</span>
      socket.<span class="hljs-title function_">end</span>(<span class="hljs-string">`Request handled with <span class="hljs-subst">${process.argv[<span class="hljs-number">2</span>]}</span> priority`</span>);
    }
  }
});</code> <button class="copy-button">copy</button></pre>
<p>Do not use <code>.maxConnections</code> on a socket that has been passed to a subprocess.
The parent cannot track when the socket is destroyed.</p>
<p>Any <code>'message'</code> handlers in the subprocess should 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>
<h4><code>subprocess.signalCode</code><span><a class="mark" href="#all_child_process_subprocesssignalcode" id="all_child_process_subprocesssignalcode">#</a></span><a aria-hidden="true" class="legacy" id="child_process_subprocess_signalcode"></a></h4>
<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#Null_type" class="type">&#x3C;null></a></li>
</ul>
<p>The <code>subprocess.signalCode</code> property indicates the signal received by
the child process if any, else <code>null</code>.</p>
<h4><code>subprocess.spawnargs</code><span><a class="mark" href="#all_child_process_subprocessspawnargs" id="all_child_process_subprocessspawnargs">#</a></span><a aria-hidden="true" class="legacy" id="child_process_subprocess_spawnargs"></a></h4>
<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>
<h4><code>subprocess.spawnfile</code><span><a class="mark" href="#all_child_process_subprocessspawnfile" id="all_child_process_subprocessspawnfile">#</a></span><a aria-hidden="true" class="legacy" id="child_process_subprocess_spawnfile"></a></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>The <code>subprocess.spawnfile</code> property indicates the executable file name of
the child process that is launched.</p>
<p>For <a href="#all_child_process_child_processforkmodulepath-args-options"><code>child_process.fork()</code></a>, its value will be equal to
<a href="#all_process_processexecpath"><code>process.execPath</code></a>.
For <a href="#all_child_process_child_processspawncommand-args-options"><code>child_process.spawn()</code></a>, its value will be the name of
the executable file.
For <a href="#all_child_process_child_processexeccommand-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>
<h4><code>subprocess.stderr</code><span><a class="mark" href="#all_child_process_subprocessstderr" id="all_child_process_subprocessstderr">#</a></span><a aria-hidden="true" class="legacy" id="child_process_subprocess_stderr"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><a href="#all_stream_class-streamreadable" class="type">&#x3C;stream.Readable></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>
</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>
<p>The <code>subprocess.stderr</code> property can be <code>null</code> or <code>undefined</code>
if the child process could not be successfully spawned.</p>
<h4><code>subprocess.stdin</code><span><a class="mark" href="#all_child_process_subprocessstdin" id="all_child_process_subprocessstdin">#</a></span><a aria-hidden="true" class="legacy" id="child_process_subprocess_stdin"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><a href="#all_stream_class-streamwritable" class="type">&#x3C;stream.Writable></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>
</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>
<p>The <code>subprocess.stdin</code> property can be <code>null</code> or <code>undefined</code>
if the child process could not be successfully spawned.</p>
<h4><code>subprocess.stdio</code><span><a class="mark" href="#all_child_process_subprocessstdio" id="all_child_process_subprocessstdio">#</a></span><a aria-hidden="true" class="legacy" id="child_process_subprocess_stdio"></a></h4>
<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="#all_child_process_optionsstdio"><code>stdio</code></a> option passed to <a href="#all_child_process_child_processspawncommand-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 class="with-38-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> child_process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);

<span class="hljs-keyword">const</span> subprocess = child_process.<span class="hljs-title function_">spawn</span>(<span class="hljs-string">'ls'</span>, {
  <span class="hljs-attr">stdio</span>: [
    <span class="hljs-number">0</span>, <span class="hljs-comment">// Use parent's stdin for child.</span>
    <span class="hljs-string">'pipe'</span>, <span class="hljs-comment">// Pipe child's stdout to parent.</span>
    fs.<span class="hljs-title function_">openSync</span>(<span class="hljs-string">'err.out'</span>, <span class="hljs-string">'w'</span>), <span class="hljs-comment">// Direct child's stderr to a file.</span>
  ],
});

assert.<span class="hljs-title function_">strictEqual</span>(subprocess.<span class="hljs-property">stdio</span>[<span class="hljs-number">0</span>], <span class="hljs-literal">null</span>);
assert.<span class="hljs-title function_">strictEqual</span>(subprocess.<span class="hljs-property">stdio</span>[<span class="hljs-number">0</span>], subprocess.<span class="hljs-property">stdin</span>);

<span class="hljs-title function_">assert</span>(subprocess.<span class="hljs-property">stdout</span>);
assert.<span class="hljs-title function_">strictEqual</span>(subprocess.<span class="hljs-property">stdio</span>[<span class="hljs-number">1</span>], subprocess.<span class="hljs-property">stdout</span>);

assert.<span class="hljs-title function_">strictEqual</span>(subprocess.<span class="hljs-property">stdio</span>[<span class="hljs-number">2</span>], <span class="hljs-literal">null</span>);
assert.<span class="hljs-title function_">strictEqual</span>(subprocess.<span class="hljs-property">stdio</span>[<span class="hljs-number">2</span>], subprocess.<span class="hljs-property">stderr</span>);</code><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">import</span> child_process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;

<span class="hljs-keyword">const</span> subprocess = child_process.<span class="hljs-title function_">spawn</span>(<span class="hljs-string">'ls'</span>, {
  <span class="hljs-attr">stdio</span>: [
    <span class="hljs-number">0</span>, <span class="hljs-comment">// Use parent's stdin for child.</span>
    <span class="hljs-string">'pipe'</span>, <span class="hljs-comment">// Pipe child's stdout to parent.</span>
    fs.<span class="hljs-title function_">openSync</span>(<span class="hljs-string">'err.out'</span>, <span class="hljs-string">'w'</span>), <span class="hljs-comment">// Direct child's stderr to a file.</span>
  ],
});

assert.<span class="hljs-title function_">strictEqual</span>(subprocess.<span class="hljs-property">stdio</span>[<span class="hljs-number">0</span>], <span class="hljs-literal">null</span>);
assert.<span class="hljs-title function_">strictEqual</span>(subprocess.<span class="hljs-property">stdio</span>[<span class="hljs-number">0</span>], subprocess.<span class="hljs-property">stdin</span>);

<span class="hljs-title function_">assert</span>(subprocess.<span class="hljs-property">stdout</span>);
assert.<span class="hljs-title function_">strictEqual</span>(subprocess.<span class="hljs-property">stdio</span>[<span class="hljs-number">1</span>], subprocess.<span class="hljs-property">stdout</span>);

assert.<span class="hljs-title function_">strictEqual</span>(subprocess.<span class="hljs-property">stdio</span>[<span class="hljs-number">2</span>], <span class="hljs-literal">null</span>);
assert.<span class="hljs-title function_">strictEqual</span>(subprocess.<span class="hljs-property">stdio</span>[<span class="hljs-number">2</span>], subprocess.<span class="hljs-property">stderr</span>);</code><button class="copy-button">copy</button></pre>
<p>The <code>subprocess.stdio</code> property can be <code>undefined</code> if the child process could
not be successfully spawned.</p>
<h4><code>subprocess.stdout</code><span><a class="mark" href="#all_child_process_subprocessstdout" id="all_child_process_subprocessstdout">#</a></span><a aria-hidden="true" class="legacy" id="child_process_subprocess_stdout"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><a href="#all_stream_class-streamreadable" class="type">&#x3C;stream.Readable></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>
</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 class="with-48-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { spawn } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);

<span class="hljs-keyword">const</span> subprocess = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'ls'</span>);

subprocess.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Received chunk <span class="hljs-subst">${data}</span>`</span>);
});</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { spawn } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;

<span class="hljs-keyword">const</span> subprocess = <span class="hljs-title function_">spawn</span>(<span class="hljs-string">'ls'</span>);

subprocess.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Received chunk <span class="hljs-subst">${data}</span>`</span>);
});</code><button class="copy-button">copy</button></pre>
<p>The <code>subprocess.stdout</code> property can be <code>null</code> or <code>undefined</code>
if the child process could not be successfully spawned.</p>
<h4><code>subprocess.unref()</code><span><a class="mark" href="#all_child_process_subprocessunref" id="all_child_process_subprocessunref">#</a></span><a aria-hidden="true" class="legacy" id="child_process_subprocess_unref"></a></h4>
<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 class="with-48-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { spawn } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-keyword">const</span> subprocess = <span class="hljs-title function_">spawn</span>(process.<span class="hljs-property">argv</span>[<span class="hljs-number">0</span>], [<span class="hljs-string">'child_program.js'</span>], {
  <span class="hljs-attr">detached</span>: <span class="hljs-literal">true</span>,
  <span class="hljs-attr">stdio</span>: <span class="hljs-string">'ignore'</span>,
});

subprocess.<span class="hljs-title function_">unref</span>();</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { spawn } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-keyword">const</span> subprocess = <span class="hljs-title function_">spawn</span>(process.<span class="hljs-property">argv</span>[<span class="hljs-number">0</span>], [<span class="hljs-string">'child_program.js'</span>], {
  <span class="hljs-attr">detached</span>: <span class="hljs-literal">true</span>,
  <span class="hljs-attr">stdio</span>: <span class="hljs-string">'ignore'</span>,
});

subprocess.<span class="hljs-title function_">unref</span>();</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>maxBuffer</code> and Unicode<span><a class="mark" href="#all_child_process_maxbuffer-and-unicode" id="all_child_process_maxbuffer-and-unicode">#</a></span><a aria-hidden="true" class="legacy" id="child_process_maxbuffer_and_unicode"></a></h3>
<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>
</section><section><h3>Shell requirements<span><a class="mark" href="#all_child_process_shell-requirements" id="all_child_process_shell-requirements">#</a></span><a aria-hidden="true" class="legacy" id="child_process_shell_requirements"></a></h3>
<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>
</section><section><h3>Default Windows shell<span><a class="mark" href="#all_child_process_default-windows-shell" id="all_child_process_default-windows-shell">#</a></span><a aria-hidden="true" class="legacy" id="child_process_default_windows_shell"></a></h3>
<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>
</section><section><h3>Advanced serialization<span><a class="mark" href="#all_child_process_advanced-serialization" id="all_child_process_advanced-serialization">#</a></span><a aria-hidden="true" class="legacy" id="child_process_advanced_serialization"></a></h3>
<div class="api_metadata">
<span>Added in: v13.2.0, v12.16.0</span>
</div>
<p>Child processes support a serialization mechanism for IPC that is based on the
<a href="#all_v8_serialization-api">serialization API of the <code>node: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="#all_child_process_child_processspawncommand-args-options"><code>child_process.spawn()</code></a>
or <a href="#all_child_process_child_processforkmodulepath-args-options"><code>child_process.fork()</code></a>.</p></section>
        </section>
<section><h2>Cluster<span><a class="mark" href="#all_cluster_cluster" id="all_cluster_cluster">#</a></span><a aria-hidden="true" class="legacy" id="cluster_cluster"></a></h2>

<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/cluster.js">lib/cluster.js</a></p>
<p>Clusters of Node.js processes can be used to run multiple instances of Node.js
that can distribute workloads among their application threads. When process
isolation is not needed, use the <a href="worker_threads.html"><code>worker_threads</code></a> module instead, which
allows running multiple application threads within a single Node.js instance.</p>
<p>The cluster module allows easy creation of child processes that all share
server ports.</p>

<pre class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> cluster <span class="hljs-keyword">from</span> <span class="hljs-string">'node:cluster'</span>;
<span class="hljs-keyword">import</span> http <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;
<span class="hljs-keyword">import</span> { availableParallelism } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:os'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-keyword">const</span> numCPUs = <span class="hljs-title function_">availableParallelism</span>();

<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Primary <span class="hljs-subst">${process.pid}</span> is running`</span>);

  <span class="hljs-comment">// Fork workers.</span>
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; numCPUs; i++) {
    cluster.<span class="hljs-title function_">fork</span>();
  }

  cluster.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">worker, code, signal</span>) =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`worker <span class="hljs-subst">${worker.process.pid}</span> died`</span>);
  });
} <span class="hljs-keyword">else</span> {
  <span class="hljs-comment">// Workers can share any TCP connection</span>
  <span class="hljs-comment">// In this case it is an HTTP server</span>
  http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
    res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>);
    res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'hello world\n'</span>);
  }).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);

  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Worker <span class="hljs-subst">${process.pid}</span> started`</span>);
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> cluster = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:cluster'</span>);
<span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);
<span class="hljs-keyword">const</span> numCPUs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:os'</span>).<span class="hljs-title function_">availableParallelism</span>();
<span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Primary <span class="hljs-subst">${process.pid}</span> is running`</span>);

  <span class="hljs-comment">// Fork workers.</span>
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; numCPUs; i++) {
    cluster.<span class="hljs-title function_">fork</span>();
  }

  cluster.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">worker, code, signal</span>) =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`worker <span class="hljs-subst">${worker.process.pid}</span> died`</span>);
  });
} <span class="hljs-keyword">else</span> {
  <span class="hljs-comment">// Workers can share any TCP connection</span>
  <span class="hljs-comment">// In this case it is an HTTP server</span>
  http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
    res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>);
    res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'hello world\n'</span>);
  }).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);

  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Worker <span class="hljs-subst">${process.pid}</span> started`</span>);
}</code><button class="copy-button">copy</button></pre>
<p>Running Node.js will now share port 8000 between the workers:</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node server.js</span>
Primary 3596 is running
Worker 4324 started
Worker 4520 started
Worker 6056 started
Worker 5644 started</code> <button class="copy-button">copy</button></pre>
<p>On Windows, it is not yet possible to set up a named pipe server in a worker.</p>
<section><h3>How it works<span><a class="mark" href="#all_cluster_how-it-works" id="all_cluster_how-it-works">#</a></span><a aria-hidden="true" class="legacy" id="cluster_how_it_works"></a></h3>

<p>The worker processes are spawned using the <a href="#all_child_process_child_processforkmodulepath-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 primary 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 primary 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 primary
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 primary,
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 primary
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>node:cluster</code> module is networking, it can
also be used for other use cases requiring worker processes.</p>
</section><section><h3>Class: <code>Worker</code><span><a class="mark" href="#all_cluster_class-worker" id="all_cluster_class-worker">#</a></span><a aria-hidden="true" class="legacy" id="cluster_class_worker"></a></h3>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div>
<ul>
<li>Extends: <a href="#all_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 primary it can be obtained using <code>cluster.workers</code>. In a worker
it can be obtained using <code>cluster.worker</code>.</p>
<h4>Event: <code>'disconnect'</code><span><a class="mark" href="#all_cluster_event-disconnect" id="all_cluster_event-disconnect">#</a></span><a aria-hidden="true" class="legacy" id="cluster_event_disconnect"></a></h4>
<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.<span class="hljs-title function_">fork</span>().<span class="hljs-title function_">on</span>(<span class="hljs-string">'disconnect'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-comment">// Worker has disconnected</span>
});</code> <button class="copy-button">copy</button></pre>
<h4>Event: <code>'error'</code><span><a class="mark" href="#all_cluster_event-error" id="all_cluster_event-error">#</a></span><a aria-hidden="true" class="legacy" id="cluster_event_error"></a></h4>
<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="#all_child_process_child_processforkmodulepath-args-options"><code>child_process.fork()</code></a>.</p>
<p>Within a worker, <code>process.on('error')</code> may also be used.</p>
<h4>Event: <code>'exit'</code><span><a class="mark" href="#all_cluster_event-exit" id="all_cluster_event-exit">#</a></span><a aria-hidden="true" class="legacy" id="cluster_event_exit"></a></h4>
<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 class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> cluster <span class="hljs-keyword">from</span> <span class="hljs-string">'node:cluster'</span>;

<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) {
  <span class="hljs-keyword">const</span> worker = cluster.<span class="hljs-title function_">fork</span>();
  worker.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">code, signal</span>) =></span> {
    <span class="hljs-keyword">if</span> (signal) {
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`worker was killed by signal: <span class="hljs-subst">${signal}</span>`</span>);
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (code !== <span class="hljs-number">0</span>) {
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`worker exited with error code: <span class="hljs-subst">${code}</span>`</span>);
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'worker success!'</span>);
    }
  });
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> cluster = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:cluster'</span>);

<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) {
  <span class="hljs-keyword">const</span> worker = cluster.<span class="hljs-title function_">fork</span>();
  worker.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">code, signal</span>) =></span> {
    <span class="hljs-keyword">if</span> (signal) {
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`worker was killed by signal: <span class="hljs-subst">${signal}</span>`</span>);
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (code !== <span class="hljs-number">0</span>) {
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`worker exited with error code: <span class="hljs-subst">${code}</span>`</span>);
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'worker success!'</span>);
    }
  });
}</code><button class="copy-button">copy</button></pre>
<h4>Event: <code>'listening'</code><span><a class="mark" href="#all_cluster_event-listening" id="all_cluster_event-listening">#</a></span><a aria-hidden="true" class="legacy" id="cluster_event_listening"></a></h4>
<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 class="with-45-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs">cluster.<span class="hljs-title function_">fork</span>().<span class="hljs-title function_">on</span>(<span class="hljs-string">'listening'</span>, <span class="hljs-function">(<span class="hljs-params">address</span>) =></span> {
  <span class="hljs-comment">// Worker is listening</span>
});</code><code class="language-js cjs">cluster.<span class="hljs-title function_">fork</span>().<span class="hljs-title function_">on</span>(<span class="hljs-string">'listening'</span>, <span class="hljs-function">(<span class="hljs-params">address</span>) =></span> {
  <span class="hljs-comment">// Worker is listening</span>
});</code><button class="copy-button">copy</button></pre>
<p>It is not emitted in the worker.</p>
<h4>Event: <code>'message'</code><span><a class="mark" href="#all_cluster_event-message" id="all_cluster_event-message">#</a></span><a aria-hidden="true" class="legacy" id="cluster_event_message"></a></h4>
<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="#all_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 primary
process of the number of HTTP requests received by the workers:</p>

<pre class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> cluster <span class="hljs-keyword">from</span> <span class="hljs-string">'node:cluster'</span>;
<span class="hljs-keyword">import</span> http <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;
<span class="hljs-keyword">import</span> { availableParallelism } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:os'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) {

  <span class="hljs-comment">// Keep track of http requests</span>
  <span class="hljs-keyword">let</span> numReqs = <span class="hljs-number">0</span>;
  <span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`numReqs = <span class="hljs-subst">${numReqs}</span>`</span>);
  }, <span class="hljs-number">1000</span>);

  <span class="hljs-comment">// Count requests</span>
  <span class="hljs-keyword">function</span> <span class="hljs-title function_">messageHandler</span>(<span class="hljs-params">msg</span>) {
    <span class="hljs-keyword">if</span> (msg.<span class="hljs-property">cmd</span> &#x26;&#x26; msg.<span class="hljs-property">cmd</span> === <span class="hljs-string">'notifyRequest'</span>) {
      numReqs += <span class="hljs-number">1</span>;
    }
  }

  <span class="hljs-comment">// Start workers and listen for messages containing notifyRequest</span>
  <span class="hljs-keyword">const</span> numCPUs = <span class="hljs-title function_">availableParallelism</span>();
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; numCPUs; i++) {
    cluster.<span class="hljs-title function_">fork</span>();
  }

  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> id <span class="hljs-keyword">in</span> cluster.<span class="hljs-property">workers</span>) {
    cluster.<span class="hljs-property">workers</span>[id].<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, messageHandler);
  }

} <span class="hljs-keyword">else</span> {

  <span class="hljs-comment">// Worker processes have a http server.</span>
  http.<span class="hljs-title class_">Server</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
    res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>);
    res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'hello world\n'</span>);

    <span class="hljs-comment">// Notify primary about the request</span>
    process.<span class="hljs-title function_">send</span>({ <span class="hljs-attr">cmd</span>: <span class="hljs-string">'notifyRequest'</span> });
  }).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> cluster = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:cluster'</span>);
<span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);
<span class="hljs-keyword">const</span> numCPUs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:os'</span>).<span class="hljs-title function_">availableParallelism</span>();
<span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) {

  <span class="hljs-comment">// Keep track of http requests</span>
  <span class="hljs-keyword">let</span> numReqs = <span class="hljs-number">0</span>;
  <span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`numReqs = <span class="hljs-subst">${numReqs}</span>`</span>);
  }, <span class="hljs-number">1000</span>);

  <span class="hljs-comment">// Count requests</span>
  <span class="hljs-keyword">function</span> <span class="hljs-title function_">messageHandler</span>(<span class="hljs-params">msg</span>) {
    <span class="hljs-keyword">if</span> (msg.<span class="hljs-property">cmd</span> &#x26;&#x26; msg.<span class="hljs-property">cmd</span> === <span class="hljs-string">'notifyRequest'</span>) {
      numReqs += <span class="hljs-number">1</span>;
    }
  }

  <span class="hljs-comment">// Start workers and listen for messages containing notifyRequest</span>
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; numCPUs; i++) {
    cluster.<span class="hljs-title function_">fork</span>();
  }

  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> id <span class="hljs-keyword">in</span> cluster.<span class="hljs-property">workers</span>) {
    cluster.<span class="hljs-property">workers</span>[id].<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, messageHandler);
  }

} <span class="hljs-keyword">else</span> {

  <span class="hljs-comment">// Worker processes have a http server.</span>
  http.<span class="hljs-title class_">Server</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
    res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>);
    res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'hello world\n'</span>);

    <span class="hljs-comment">// Notify primary about the request</span>
    process.<span class="hljs-title function_">send</span>({ <span class="hljs-attr">cmd</span>: <span class="hljs-string">'notifyRequest'</span> });
  }).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);
}</code><button class="copy-button">copy</button></pre>
<h4>Event: <code>'online'</code><span><a class="mark" href="#all_cluster_event-online" id="all_cluster_event-online">#</a></span><a aria-hidden="true" class="legacy" id="cluster_event_online"></a></h4>
<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.<span class="hljs-title function_">fork</span>().<span class="hljs-title function_">on</span>(<span class="hljs-string">'online'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-comment">// Worker is online</span>
});</code> <button class="copy-button">copy</button></pre>
<p>It is not emitted in the worker.</p>
<h4><code>worker.disconnect()</code><span><a class="mark" href="#all_cluster_workerdisconnect" id="all_cluster_workerdisconnect">#</a></span><a aria-hidden="true" class="legacy" id="cluster_worker_disconnect"></a></h4>
<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="#all_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 primary, 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="#all_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="#all_child_process_subprocessdisconnect"><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"><span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) {
  <span class="hljs-keyword">const</span> worker = cluster.<span class="hljs-title function_">fork</span>();
  <span class="hljs-keyword">let</span> timeout;

  worker.<span class="hljs-title function_">on</span>(<span class="hljs-string">'listening'</span>, <span class="hljs-function">(<span class="hljs-params">address</span>) =></span> {
    worker.<span class="hljs-title function_">send</span>(<span class="hljs-string">'shutdown'</span>);
    worker.<span class="hljs-title function_">disconnect</span>();
    timeout = <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
      worker.<span class="hljs-title function_">kill</span>();
    }, <span class="hljs-number">2000</span>);
  });

  worker.<span class="hljs-title function_">on</span>(<span class="hljs-string">'disconnect'</span>, <span class="hljs-function">() =></span> {
    <span class="hljs-built_in">clearTimeout</span>(timeout);
  });

} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isWorker</span>) {
  <span class="hljs-keyword">const</span> net = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:net'</span>);
  <span class="hljs-keyword">const</span> server = net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">socket</span>) =></span> {
    <span class="hljs-comment">// Connections never end</span>
  });

  server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);

  process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg</span>) =></span> {
    <span class="hljs-keyword">if</span> (msg === <span class="hljs-string">'shutdown'</span>) {
      <span class="hljs-comment">// Initiate graceful close of any connections to server</span>
    }
  });
}</code> <button class="copy-button">copy</button></pre>
<h4><code>worker.exitedAfterDisconnect</code><span><a class="mark" href="#all_cluster_workerexitedafterdisconnect" id="all_cluster_workerexitedafterdisconnect">#</a></span><a aria-hidden="true" class="legacy" id="cluster_worker_exitedafterdisconnect"></a></h4>
<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>.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="#all_cluster_workerexitedafterdisconnect"><code>worker.exitedAfterDisconnect</code></a> allows distinguishing between
voluntary and accidental exit, the primary may choose not to respawn a worker
based on this value.</p>
<pre><code class="language-js">cluster.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">worker, code, signal</span>) =></span> {
  <span class="hljs-keyword">if</span> (worker.<span class="hljs-property">exitedAfterDisconnect</span> === <span class="hljs-literal">true</span>) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Oh, it was just voluntary – no need to worry'</span>);
  }
});

<span class="hljs-comment">// kill worker</span>
worker.<span class="hljs-title function_">kill</span>();</code> <button class="copy-button">copy</button></pre>
<h4><code>worker.id</code><span><a class="mark" href="#all_cluster_workerid" id="all_cluster_workerid">#</a></span><a aria-hidden="true" class="legacy" id="cluster_worker_id"></a></h4>
<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;integer></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>
<h4><code>worker.isConnected()</code><span><a class="mark" href="#all_cluster_workerisconnected" id="all_cluster_workerisconnected">#</a></span><a aria-hidden="true" class="legacy" id="cluster_worker_isconnected"></a></h4>
<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 primary via its
IPC channel, <code>false</code> otherwise. A worker is connected to its primary after it
has been created. It is disconnected after the <code>'disconnect'</code> event is emitted.</p>
<h4><code>worker.isDead()</code><span><a class="mark" href="#all_cluster_workerisdead" id="all_cluster_workerisdead">#</a></span><a aria-hidden="true" class="legacy" id="cluster_worker_isdead"></a></h4>
<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 class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> cluster <span class="hljs-keyword">from</span> <span class="hljs-string">'node:cluster'</span>;
<span class="hljs-keyword">import</span> http <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;
<span class="hljs-keyword">import</span> { availableParallelism } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:os'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-keyword">const</span> numCPUs = <span class="hljs-title function_">availableParallelism</span>();

<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Primary <span class="hljs-subst">${process.pid}</span> is running`</span>);

  <span class="hljs-comment">// Fork workers.</span>
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; numCPUs; i++) {
    cluster.<span class="hljs-title function_">fork</span>();
  }

  cluster.<span class="hljs-title function_">on</span>(<span class="hljs-string">'fork'</span>, <span class="hljs-function">(<span class="hljs-params">worker</span>) =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'worker is dead:'</span>, worker.<span class="hljs-title function_">isDead</span>());
  });

  cluster.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">worker, code, signal</span>) =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'worker is dead:'</span>, worker.<span class="hljs-title function_">isDead</span>());
  });
} <span class="hljs-keyword">else</span> {
  <span class="hljs-comment">// Workers can share any TCP connection. In this case, it is an HTTP server.</span>
  http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
    res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>);
    res.<span class="hljs-title function_">end</span>(<span class="hljs-string">`Current process\n <span class="hljs-subst">${process.pid}</span>`</span>);
    process.<span class="hljs-title function_">kill</span>(process.<span class="hljs-property">pid</span>);
  }).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> cluster = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:cluster'</span>);
<span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);
<span class="hljs-keyword">const</span> numCPUs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:os'</span>).<span class="hljs-title function_">availableParallelism</span>();
<span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Primary <span class="hljs-subst">${process.pid}</span> is running`</span>);

  <span class="hljs-comment">// Fork workers.</span>
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; numCPUs; i++) {
    cluster.<span class="hljs-title function_">fork</span>();
  }

  cluster.<span class="hljs-title function_">on</span>(<span class="hljs-string">'fork'</span>, <span class="hljs-function">(<span class="hljs-params">worker</span>) =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'worker is dead:'</span>, worker.<span class="hljs-title function_">isDead</span>());
  });

  cluster.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">worker, code, signal</span>) =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'worker is dead:'</span>, worker.<span class="hljs-title function_">isDead</span>());
  });
} <span class="hljs-keyword">else</span> {
  <span class="hljs-comment">// Workers can share any TCP connection. In this case, it is an HTTP server.</span>
  http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
    res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>);
    res.<span class="hljs-title function_">end</span>(<span class="hljs-string">`Current process\n <span class="hljs-subst">${process.pid}</span>`</span>);
    process.<span class="hljs-title function_">kill</span>(process.<span class="hljs-property">pid</span>);
  }).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);
}</code><button class="copy-button">copy</button></pre>
<h4><code>worker.kill([signal])</code><span><a class="mark" href="#all_cluster_workerkillsignal" id="all_cluster_workerkillsignal">#</a></span><a aria-hidden="true" class="legacy" id="cluster_worker_kill_signal"></a></h4>
<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 primary worker, 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 killing the process with <code>signal</code>.</p>
<p>The <code>kill()</code> function kills the worker process without waiting for a graceful
disconnect, it has the same behavior as <code>worker.process.kill()</code>.</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="#all_process_processkillpid-signal"><code>kill()</code></a>.</p>
<h4><code>worker.process</code><span><a class="mark" href="#all_cluster_workerprocess" id="all_cluster_workerprocess">#</a></span><a aria-hidden="true" class="legacy" id="cluster_worker_process"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div>
<ul>
<li><a href="#all_child_process_class-childprocess" class="type">&#x3C;ChildProcess></a></li>
</ul>
<p>All workers are created using <a href="#all_child_process_child_processforkmodulepath-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="#all_child_process_child_processforkmodulepath-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>
<h4><code>worker.send(message[, sendHandle[, options]][, callback])</code><span><a class="mark" href="#all_cluster_workersendmessage-sendhandle-options-callback" id="all_cluster_workersendmessage-sendhandle-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="cluster_worker_send_message_sendhandle_options_callback"></a></h4>
<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="#all_net_serverlistenhandle-backlog-callback" class="type">&#x3C;Handle></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> 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:
<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 primary, optionally with a handle.</p>
<p>In the primary, this sends a message to a specific worker. It is identical to
<a href="#all_child_process_subprocesssendmessage-sendhandle-options-callback"><code>ChildProcess.send()</code></a>.</p>
<p>In a worker, this sends a message to the primary. It is identical to
<code>process.send()</code>.</p>
<p>This example will echo back all messages from the primary:</p>
<pre><code class="language-js"><span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) {
  <span class="hljs-keyword">const</span> worker = cluster.<span class="hljs-title function_">fork</span>();
  worker.<span class="hljs-title function_">send</span>(<span class="hljs-string">'hi there'</span>);

} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isWorker</span>) {
  process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg</span>) =></span> {
    process.<span class="hljs-title function_">send</span>(msg);
  });
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Event: <code>'disconnect'</code><span><a class="mark" href="#all_cluster_event-disconnect_1" id="all_cluster_event-disconnect_1">#</a></span><a aria-hidden="true" class="legacy" id="cluster_event_disconnect_1"></a></h3>
<div class="api_metadata">
<span>Added in: v0.7.9</span>
</div>
<ul>
<li><code>worker</code> <a href="#all_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.<span class="hljs-title function_">on</span>(<span class="hljs-string">'disconnect'</span>, <span class="hljs-function">(<span class="hljs-params">worker</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`The worker #<span class="hljs-subst">${worker.id}</span> has disconnected`</span>);
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Event: <code>'exit'</code><span><a class="mark" href="#all_cluster_event-exit_1" id="all_cluster_event-exit_1">#</a></span><a aria-hidden="true" class="legacy" id="cluster_event_exit_1"></a></h3>
<div class="api_metadata">
<span>Added in: v0.7.9</span>
</div>
<ul>
<li><code>worker</code> <a href="#all_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="#all_cluster_clusterforkenv"><code>.fork()</code></a> again.</p>
<pre><code class="language-js">cluster.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">worker, code, signal</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'worker %d died (%s). restarting...'</span>,
              worker.<span class="hljs-property">process</span>.<span class="hljs-property">pid</span>, signal || code);
  cluster.<span class="hljs-title function_">fork</span>();
});</code> <button class="copy-button">copy</button></pre>
<p>See <a href="#all_child_process_event-exit"><code>child_process</code> event: <code>'exit'</code></a>.</p>
</section><section><h3>Event: <code>'fork'</code><span><a class="mark" href="#all_cluster_event-fork" id="all_cluster_event-fork">#</a></span><a aria-hidden="true" class="legacy" id="cluster_event_fork"></a></h3>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div>
<ul>
<li><code>worker</code> <a href="#all_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"><span class="hljs-keyword">const</span> timeouts = [];
<span class="hljs-keyword">function</span> <span class="hljs-title function_">errorMsg</span>(<span class="hljs-params"></span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'Something must be wrong with the connection ...'</span>);
}

cluster.<span class="hljs-title function_">on</span>(<span class="hljs-string">'fork'</span>, <span class="hljs-function">(<span class="hljs-params">worker</span>) =></span> {
  timeouts[worker.<span class="hljs-property">id</span>] = <span class="hljs-built_in">setTimeout</span>(errorMsg, <span class="hljs-number">2000</span>);
});
cluster.<span class="hljs-title function_">on</span>(<span class="hljs-string">'listening'</span>, <span class="hljs-function">(<span class="hljs-params">worker, address</span>) =></span> {
  <span class="hljs-built_in">clearTimeout</span>(timeouts[worker.<span class="hljs-property">id</span>]);
});
cluster.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">worker, code, signal</span>) =></span> {
  <span class="hljs-built_in">clearTimeout</span>(timeouts[worker.<span class="hljs-property">id</span>]);
  <span class="hljs-title function_">errorMsg</span>();
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Event: <code>'listening'</code><span><a class="mark" href="#all_cluster_event-listening_1" id="all_cluster_event-listening_1">#</a></span><a aria-hidden="true" class="legacy" id="cluster_event_listening_1"></a></h3>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div>
<ul>
<li><code>worker</code> <a href="#all_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
primary.</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.<span class="hljs-title function_">on</span>(<span class="hljs-string">'listening'</span>, <span class="hljs-function">(<span class="hljs-params">worker, address</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(
    <span class="hljs-string">`A worker is now connected to <span class="hljs-subst">${address.address}</span>:<span class="hljs-subst">${address.port}</span>`</span>);
});</code> <button class="copy-button">copy</button></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> (UDPv4 or UDPv6)</li>
</ul>
</section><section><h3>Event: <code>'message'</code><span><a class="mark" href="#all_cluster_event-message_1" id="all_cluster_event-message_1">#</a></span><a aria-hidden="true" class="legacy" id="cluster_event_message_1"></a></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 <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="#all_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 primary receives a message from any worker.</p>
<p>See <a href="#all_child_process_event-message"><code>child_process</code> event: <code>'message'</code></a>.</p>
</section><section><h3>Event: <code>'online'</code><span><a class="mark" href="#all_cluster_event-online_1" id="all_cluster_event-online_1">#</a></span><a aria-hidden="true" class="legacy" id="cluster_event_online_1"></a></h3>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div>
<ul>
<li><code>worker</code> <a href="#all_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 primary 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
primary forks a worker, and <code>'online'</code> is emitted when the worker is running.</p>
<pre><code class="language-js">cluster.<span class="hljs-title function_">on</span>(<span class="hljs-string">'online'</span>, <span class="hljs-function">(<span class="hljs-params">worker</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Yay, the worker responded after it was forked'</span>);
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Event: <code>'setup'</code><span><a class="mark" href="#all_cluster_event-setup" id="all_cluster_event-setup">#</a></span><a aria-hidden="true" class="legacy" id="cluster_event_setup"></a></h3>
<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="#all_cluster_clustersetupprimarysettings"><code>.setupPrimary()</code></a> is called.</p>
<p>The <code>settings</code> object is the <code>cluster.settings</code> object at the time
<a href="#all_cluster_clustersetupprimarysettings"><code>.setupPrimary()</code></a> was called and is advisory only, since multiple calls to
<a href="#all_cluster_clustersetupprimarysettings"><code>.setupPrimary()</code></a> can be made in a single tick.</p>
<p>If accuracy is important, use <code>cluster.settings</code>.</p>
</section><section><h3><code>cluster.disconnect([callback])</code><span><a class="mark" href="#all_cluster_clusterdisconnectcallback" id="all_cluster_clusterdisconnectcallback">#</a></span><a aria-hidden="true" class="legacy" id="cluster_cluster_disconnect_callback"></a></h3>
<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
primary 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 primary process.</p>
</section><section><h3><code>cluster.fork([env])</code><span><a class="mark" href="#all_cluster_clusterforkenv" id="all_cluster_clusterforkenv">#</a></span><a aria-hidden="true" class="legacy" id="cluster_cluster_fork_env"></a></h3>
<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="#all_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 primary process.</p>
</section><section><h3><code>cluster.isMaster</code><span><a class="mark" href="#all_cluster_clusterismaster" id="all_cluster_clusterismaster">#</a></span><a aria-hidden="true" class="legacy" id="cluster_cluster_ismaster"></a></h3>
<div class="api_metadata">
<span>Added in: v0.8.1</span><span>Deprecated since: v16.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated</div><p></p>
<p>Deprecated alias for <a href="#all_cluster_clusterisprimary"><code>cluster.isPrimary</code></a>.</p>
</section><section><h3><code>cluster.isPrimary</code><span><a class="mark" href="#all_cluster_clusterisprimary" id="all_cluster_clusterisprimary">#</a></span><a aria-hidden="true" class="legacy" id="cluster_cluster_isprimary"></a></h3>
<div class="api_metadata">
<span>Added in: v16.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>True if the process is a primary. This is determined
by the <code>process.env.NODE_UNIQUE_ID</code>. If <code>process.env.NODE_UNIQUE_ID</code> is
undefined, then <code>isPrimary</code> is <code>true</code>.</p>
</section><section><h3><code>cluster.isWorker</code><span><a class="mark" href="#all_cluster_clusterisworker" id="all_cluster_clusterisworker">#</a></span><a aria-hidden="true" class="legacy" id="cluster_cluster_isworker"></a></h3>
<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 primary (it is the negation of <code>cluster.isPrimary</code>).</p>
</section><section><h3><code>cluster.schedulingPolicy</code><span><a class="mark" href="#all_cluster_clusterschedulingpolicy" id="all_cluster_clusterschedulingpolicy">#</a></span><a aria-hidden="true" class="legacy" id="cluster_cluster_schedulingpolicy"></a></h3>
<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="#all_cluster_clustersetupprimarysettings"><code>.setupPrimary()</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>
</section><section><h3><code>cluster.settings</code><span><a class="mark" href="#all_cluster_clustersettings" id="all_cluster_clustersettings">#</a></span><a aria-hidden="true" class="legacy" id="cluster_cluster_settings"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.2.0, 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><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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="#all_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>. See
<a href="#all_child_process_child_processspawncommand-args-options"><code>child_process.spawn()</code></a>'s <a href="#all_child_process_optionsstdio"><code>stdio</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>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
primary'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="#all_cluster_clustersetupprimarysettings"><code>.setupPrimary()</code></a> (or <a href="#all_cluster_clusterforkenv"><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>
</section><section><h3><code>cluster.setupMaster([settings])</code><span><a class="mark" href="#all_cluster_clustersetupmastersettings" id="all_cluster_clustersetupmastersettings">#</a></span><a aria-hidden="true" class="legacy" id="cluster_cluster_setupmaster_settings"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0</td>
<td><p><span>Deprecated since: v16.0.0</span></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>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated</div><p></p>
<p>Deprecated alias for <a href="#all_cluster_clustersetupprimarysettings"><code>.setupPrimary()</code></a>.</p>
</section><section><h3><code>cluster.setupPrimary([settings])</code><span><a class="mark" href="#all_cluster_clustersetupprimarysettings" id="all_cluster_clustersetupprimarysettings">#</a></span><a aria-hidden="true" class="legacy" id="cluster_cluster_setupprimary_settings"></a></h3>
<div class="api_metadata">
<span>Added in: v16.0.0</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> See <a href="#all_cluster_clustersettings"><code>cluster.settings</code></a>.</li>
</ul>
<p><code>setupPrimary</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="#all_cluster_clusterforkenv"><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>.setupPrimary()</code> is
the <code>env</code> passed to <a href="#all_cluster_clusterforkenv"><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.setupPrimary()</code> is called.</p>

<pre class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> cluster <span class="hljs-keyword">from</span> <span class="hljs-string">'node:cluster'</span>;

cluster.<span class="hljs-title function_">setupPrimary</span>({
  <span class="hljs-attr">exec</span>: <span class="hljs-string">'worker.js'</span>,
  <span class="hljs-attr">args</span>: [<span class="hljs-string">'--use'</span>, <span class="hljs-string">'https'</span>],
  <span class="hljs-attr">silent</span>: <span class="hljs-literal">true</span>,
});
cluster.<span class="hljs-title function_">fork</span>(); <span class="hljs-comment">// https worker</span>
cluster.<span class="hljs-title function_">setupPrimary</span>({
  <span class="hljs-attr">exec</span>: <span class="hljs-string">'worker.js'</span>,
  <span class="hljs-attr">args</span>: [<span class="hljs-string">'--use'</span>, <span class="hljs-string">'http'</span>],
});
cluster.<span class="hljs-title function_">fork</span>(); <span class="hljs-comment">// http worker</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> cluster = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:cluster'</span>);

cluster.<span class="hljs-title function_">setupPrimary</span>({
  <span class="hljs-attr">exec</span>: <span class="hljs-string">'worker.js'</span>,
  <span class="hljs-attr">args</span>: [<span class="hljs-string">'--use'</span>, <span class="hljs-string">'https'</span>],
  <span class="hljs-attr">silent</span>: <span class="hljs-literal">true</span>,
});
cluster.<span class="hljs-title function_">fork</span>(); <span class="hljs-comment">// https worker</span>
cluster.<span class="hljs-title function_">setupPrimary</span>({
  <span class="hljs-attr">exec</span>: <span class="hljs-string">'worker.js'</span>,
  <span class="hljs-attr">args</span>: [<span class="hljs-string">'--use'</span>, <span class="hljs-string">'http'</span>],
});
cluster.<span class="hljs-title function_">fork</span>(); <span class="hljs-comment">// http worker</span></code><button class="copy-button">copy</button></pre>
<p>This can only be called from the primary process.</p>
</section><section><h3><code>cluster.worker</code><span><a class="mark" href="#all_cluster_clusterworker" id="all_cluster_clusterworker">#</a></span><a aria-hidden="true" class="legacy" id="cluster_cluster_worker"></a></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/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
<p>A reference to the current worker object. Not available in the primary process.</p>

<pre class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> cluster <span class="hljs-keyword">from</span> <span class="hljs-string">'node:cluster'</span>;

<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'I am primary'</span>);
  cluster.<span class="hljs-title function_">fork</span>();
  cluster.<span class="hljs-title function_">fork</span>();
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isWorker</span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`I am worker #<span class="hljs-subst">${cluster.worker.id}</span>`</span>);
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> cluster = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:cluster'</span>);

<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'I am primary'</span>);
  cluster.<span class="hljs-title function_">fork</span>();
  cluster.<span class="hljs-title function_">fork</span>();
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isWorker</span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`I am worker #<span class="hljs-subst">${cluster.worker.id}</span>`</span>);
}</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>cluster.workers</code><span><a class="mark" href="#all_cluster_clusterworkers" id="all_cluster_clusterworkers">#</a></span><a aria-hidden="true" class="legacy" id="cluster_cluster_workers"></a></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/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. This makes it
easy to loop through all the workers. It is only available in the primary
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 the last <code>'disconnect'</code> or <code>'exit'</code> event is emitted.</p>

<pre class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> cluster <span class="hljs-keyword">from</span> <span class="hljs-string">'node:cluster'</span>;

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> worker <span class="hljs-keyword">of</span> <span class="hljs-title class_">Object</span>.<span class="hljs-title function_">values</span>(cluster.<span class="hljs-property">workers</span>)) {
  worker.<span class="hljs-title function_">send</span>(<span class="hljs-string">'big announcement to all workers'</span>);
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> cluster = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:cluster'</span>);

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> worker <span class="hljs-keyword">of</span> <span class="hljs-title class_">Object</span>.<span class="hljs-title function_">values</span>(cluster.<span class="hljs-property">workers</span>)) {
  worker.<span class="hljs-title function_">send</span>(<span class="hljs-string">'big announcement to all workers'</span>);
}</code><button class="copy-button">copy</button></pre></section>
        </section>
<section><h2>Command-line API<span><a class="mark" href="#all_cli_command-line-api" id="all_cli_command-line-api">#</a></span><a aria-hidden="true" class="legacy" id="cli_command_line_api"></a></h2>


<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>
<section><h3>Synopsis<span><a class="mark" href="#all_cli_synopsis" id="all_cli_synopsis">#</a></span><a aria-hidden="true" class="legacy" id="cli_synopsis"></a></h3>
<p><code>node [options] [V8 options] [&#x3C;program-entry-point> | -e "script" | -] [--] [arguments]</code></p>
<p><code>node inspect [&#x3C;program-entry-point> | -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>For more info about <code>node inspect</code>, see the <a href="debugger.html">debugger</a> documentation.</p>
</section><section><h3>Program entry point<span><a class="mark" href="#all_cli_program-entry-point" id="all_cli_program-entry-point">#</a></span><a aria-hidden="true" class="legacy" id="cli_program_entry_point"></a></h3>
<p>The program entry point is a specifier-like string. If the string is not an
absolute path, it's resolved as a relative path from the current working
directory. That path is then resolved by <a href="modules.html">CommonJS</a> module loader, or by the
<a href="#all_packages_modules-loaders">ES module loader</a> if <a href="#all_cli_--experimental-default-typetype"><code>--experimental-default-type=module</code></a>
is passed. If no corresponding file is found, an error is thrown.</p>
<p>If a file is found, its path will be passed to the
<a href="#all_packages_modules-loaders">ES module loader</a> under any of the following conditions:</p>
<ul>
<li>The program was started with a command-line flag that forces the entry
point to be loaded with ECMAScript module loader, such as <code>--import</code> or
<a href="#all_cli_--experimental-default-typetype"><code>--experimental-default-type=module</code></a>.</li>
<li>The file has an <code>.mjs</code> extension.</li>
<li>The file does not have a <code>.cjs</code> extension, and the nearest parent
<code>package.json</code> file contains a top-level <a href="#all_packages_type"><code>"type"</code></a> field with a value of
<code>"module"</code>.</li>
</ul>
<p>Otherwise, the file is loaded using the CommonJS module loader. See
<a href="#all_packages_modules-loaders">Modules loaders</a> for more details.</p>
<h4>ECMAScript modules loader entry point caveat<span><a class="mark" href="#all_cli_ecmascript-modules-loader-entry-point-caveat" id="all_cli_ecmascript-modules-loader-entry-point-caveat">#</a></span><a aria-hidden="true" class="legacy" id="cli_ecmascript_modules_loader_entry_point_caveat"></a></h4>
<p>When loading, the <a href="#all_packages_modules-loaders">ES module loader</a> loads the program
entry point, the <code>node</code> command will accept as input only files with <code>.js</code>,
<code>.mjs</code>, or <code>.cjs</code> extensions; with <code>.wasm</code> extensions when
<a href="#all_cli_--experimental-wasm-modules"><code>--experimental-wasm-modules</code></a> is enabled; and with no extension when
<a href="#all_cli_--experimental-default-typetype"><code>--experimental-default-type=module</code></a> is passed.</p>
</section><section><h3>Options<span><a class="mark" href="#all_cli_options" id="all_cli_options">#</a></span><a aria-hidden="true" class="legacy" id="cli_options"></a></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>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>). For example, <code>--pending-deprecation</code> is
equivalent to <code>--pending_deprecation</code>.</p>
<p>If an option that takes a single value (such as <code>--max-http-header-size</code>) is
passed more than once, then the last passed value is used. Options from the
command line take precedence over options passed through the <a href="#all_cli_node_optionsoptions"><code>NODE_OPTIONS</code></a>
environment variable.</p>
<h4><code>-</code><span><a class="mark" href="#all_cli_-" id="all_cli_-">#</a></span><a aria-hidden="true" class="legacy" id="cli"></a></h4>
<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 is read from stdin, and the rest of the options
are passed to that script.</p>
<h4><code>--</code><span><a class="mark" href="#all_cli_--" id="all_cli_--">#</a></span><a aria-hidden="true" class="legacy" id="cli_1"></a></h4>
<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 is used as a script filename.</p>
<h4><code>--abort-on-uncaught-exception</code><span><a class="mark" href="#all_cli_--abort-on-uncaught-exception" id="all_cli_--abort-on-uncaught-exception">#</a></span><a aria-hidden="true" class="legacy" id="cli_abort_on_uncaught_exception"></a></h4>
<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="#all_process_processsetuncaughtexceptioncapturecallbackfn"><code>process.setUncaughtExceptionCaptureCallback()</code></a> (and through usage of the
<code>node:domain</code> module that uses it).</p>
<h4><code>--allow-addons</code><span><a class="mark" href="#all_cli_--allow-addons" id="all_cli_--allow-addons">#</a></span><a aria-hidden="true" class="legacy" id="cli_allow_addons"></a></h4>
<div class="api_metadata">
<span>Added in: v20.12.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active development</div><p></p>
<p>When using the <a href="#all_permissions_permission-model">Permission Model</a>, the process will not be able to use
native addons by default.
Attempts to do so will throw an <code>ERR_DLOPEN_DISABLED</code> unless the
user explicitly passes the <code>--allow-addons</code> flag when starting Node.js.</p>
<p>Example:</p>
<pre><code class="language-js cjs"><span class="hljs-comment">// Attempt to require an native addon</span>
<span class="hljs-built_in">require</span>(<span class="hljs-string">'nodejs-addon-example'</span>);</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node --experimental-permission --allow-fs-read=* index.js</span>
node:internal/modules/cjs/loader:1319
  return process.dlopen(module, path.toNamespacedPath(filename));
                 ^

Error: Cannot load native addon because loading addons is disabled.
    at Module._extensions..node (node:internal/modules/cjs/loader:1319:18)
    at Module.load (node:internal/modules/cjs/loader:1091:32)
    at Module._load (node:internal/modules/cjs/loader:938:12)
    at Module.require (node:internal/modules/cjs/loader:1115:19)
    at require (node:internal/modules/helpers:130:18)
    at Object.&#x3C;anonymous> (/home/index.js:1:15)
    at Module._compile (node:internal/modules/cjs/loader:1233:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1287:10)
    at Module.load (node:internal/modules/cjs/loader:1091:32)
    at Module._load (node:internal/modules/cjs/loader:938:12) {
  code: 'ERR_DLOPEN_DISABLED'
}</code> <button class="copy-button">copy</button></pre>
<h4><code>--allow-child-process</code><span><a class="mark" href="#all_cli_--allow-child-process" id="all_cli_--allow-child-process">#</a></span><a aria-hidden="true" class="legacy" id="cli_allow_child_process"></a></h4>
<div class="api_metadata">
<span>Added in: v20.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active development</div><p></p>
<p>When using the <a href="#all_permissions_permission-model">Permission Model</a>, the process will not be able to spawn any
child process by default.
Attempts to do so will throw an <code>ERR_ACCESS_DENIED</code> unless the
user explicitly passes the <code>--allow-child-process</code> flag when starting Node.js.</p>
<p>Example:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> childProcess = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);
<span class="hljs-comment">// Attempt to bypass the permission</span>
childProcess.<span class="hljs-title function_">spawn</span>(<span class="hljs-string">'node'</span>, [<span class="hljs-string">'-e'</span>, <span class="hljs-string">'require("fs").writeFileSync("/new-file", "example")'</span>]);</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node --experimental-permission --allow-fs-read=* index.js</span>
node:internal/child_process:388
  const err = this._handle.spawn(options);
                           ^
Error: Access to this API has been restricted
    at ChildProcess.spawn (node:internal/child_process:388:28)
    at Object.spawn (node:child_process:723:9)
    at Object.&#x3C;anonymous> (/home/index.js:3:14)
    at Module._compile (node:internal/modules/cjs/loader:1120:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1174:10)
    at Module.load (node:internal/modules/cjs/loader:998:32)
    at Module._load (node:internal/modules/cjs/loader:839:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:17:47 {
  code: 'ERR_ACCESS_DENIED',
  permission: 'ChildProcess'
}</code> <button class="copy-button">copy</button></pre>
<h4><code>--allow-fs-read</code><span><a class="mark" href="#all_cli_--allow-fs-read" id="all_cli_--allow-fs-read">#</a></span><a aria-hidden="true" class="legacy" id="cli_allow_fs_read"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.7.0</td>
<td><p>Paths delimited by comma (<code>,</code>) are no longer allowed.</p></td></tr>
<tr><td>v20.0.0</td>
<td><p><span>Added in: v20.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active development</div><p></p>
<p>This flag configures file system read permissions using
the <a href="#all_permissions_permission-model">Permission Model</a>.</p>
<p>The valid arguments for the <code>--allow-fs-read</code> flag are:</p>
<ul>
<li><code>*</code> - To allow all <code>FileSystemRead</code> operations.</li>
<li>Multiple paths can be allowed using multiple <code>--allow-fs-read</code> flags.
Example <code>--allow-fs-read=/folder1/ --allow-fs-read=/folder1/</code></li>
</ul>
<p>Paths delimited by comma (<code>,</code>) are no longer allowed.
When passing a single flag with a comma a warning will be displayed.</p>
<p>Examples can be found in the <a href="#all_permissions_file-system-permissions">File System Permissions</a> documentation.</p>
<p>Relative paths are NOT yet supported by the CLI flag.</p>
<p>The initializer module also needs to be allowed. Consider the following example:</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node --experimental-permission t.js</span>
node:internal/modules/cjs/loader:162
  const result = internalModuleStat(filename);
                 ^

Error: Access to this API has been restricted
    at stat (node:internal/modules/cjs/loader:162:18)
    at Module._findPath (node:internal/modules/cjs/loader:640:16)
    at resolveMainPath (node:internal/modules/run_main:15:25)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:53:24)
    at node:internal/main/run_main_module:23:47 {
  code: 'ERR_ACCESS_DENIED',
  permission: 'FileSystemRead',
  resource: '/Users/rafaelgss/repos/os/node/t.js'
}</code> <button class="copy-button">copy</button></pre>
<p>The process needs to have access to the <code>index.js</code> module:</p>
<pre><code class="language-bash">node --experimental-permission --allow-fs-read=/path/to/index.js index.js</code> <button class="copy-button">copy</button></pre>
<h4><code>--allow-fs-write</code><span><a class="mark" href="#all_cli_--allow-fs-write" id="all_cli_--allow-fs-write">#</a></span><a aria-hidden="true" class="legacy" id="cli_allow_fs_write"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.7.0</td>
<td><p>Paths delimited by comma (<code>,</code>) are no longer allowed.</p></td></tr>
<tr><td>v20.0.0</td>
<td><p><span>Added in: v20.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active development</div><p></p>
<p>This flag configures file system write permissions using
the <a href="#all_permissions_permission-model">Permission Model</a>.</p>
<p>The valid arguments for the <code>--allow-fs-write</code> flag are:</p>
<ul>
<li><code>*</code> - To allow all <code>FileSystemWrite</code> operations.</li>
<li>Multiple paths can be allowed using multiple <code>--allow-fs-write</code> flags.
Example <code>--allow-fs-write=/folder1/ --allow-fs-write=/folder1/</code></li>
</ul>
<p>Paths delimited by comma (<code>,</code>) are no longer allowed.
When passing a single flag with a comma a warning will be displayed.</p>
<p>Examples can be found in the <a href="#all_permissions_file-system-permissions">File System Permissions</a> documentation.</p>
<p>Relative paths are NOT supported through the CLI flag.</p>
<h4><code>--allow-wasi</code><span><a class="mark" href="#all_cli_--allow-wasi" id="all_cli_--allow-wasi">#</a></span><a aria-hidden="true" class="legacy" id="cli_allow_wasi"></a></h4>
<div class="api_metadata">
<span>Added in: v20.16.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active development</div><p></p>
<p>When using the <a href="#all_permissions_permission-model">Permission Model</a>, the process will not be capable of creating
any WASI instances by default.
For security reasons, the call will throw an <code>ERR_ACCESS_DENIED</code> unless the
user explicitly passes the flag <code>--allow-wasi</code> in the main Node.js process.</p>
<p>Example:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-variable constant_">WASI</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:wasi'</span>);
<span class="hljs-comment">// Attempt to bypass the permission</span>
<span class="hljs-keyword">new</span> <span class="hljs-title function_">WASI</span>({
  <span class="hljs-attr">version</span>: <span class="hljs-string">'preview1'</span>,
  <span class="hljs-comment">// Attempt to mount the whole filesystem</span>
  <span class="hljs-attr">preopens</span>: {
    <span class="hljs-string">'/'</span>: <span class="hljs-string">'/'</span>,
  },
});</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node --experimental-permission --allow-fs-read=* index.js</span>
node:wasi:99
    const wrap = new _WASI(args, env, preopens, stdio);
                 ^

Error: Access to this API has been restricted
    at new WASI (node:wasi:99:18)
    at Object.&#x3C;anonymous> (/home/index.js:3:1)
    at Module._compile (node:internal/modules/cjs/loader:1476:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1555:10)
    at Module.load (node:internal/modules/cjs/loader:1288:32)
    at Module._load (node:internal/modules/cjs/loader:1104:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:191:14)
    at node:internal/main/run_main_module:30:49 {
  code: 'ERR_ACCESS_DENIED',
  permission: 'WASI',
}</code> <button class="copy-button">copy</button></pre>
<h4><code>--allow-worker</code><span><a class="mark" href="#all_cli_--allow-worker" id="all_cli_--allow-worker">#</a></span><a aria-hidden="true" class="legacy" id="cli_allow_worker"></a></h4>
<div class="api_metadata">
<span>Added in: v20.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active development</div><p></p>
<p>When using the <a href="#all_permissions_permission-model">Permission Model</a>, the process will not be able to create any
worker threads by default.
For security reasons, the call will throw an <code>ERR_ACCESS_DENIED</code> unless the
user explicitly pass the flag <code>--allow-worker</code> in the main Node.js process.</p>
<p>Example:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Worker</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
<span class="hljs-comment">// Attempt to bypass the permission</span>
<span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename);</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node --experimental-permission --allow-fs-read=* index.js</span>
node:internal/worker:188
    this[kHandle] = new WorkerImpl(url,
                    ^

Error: Access to this API has been restricted
    at new Worker (node:internal/worker:188:21)
    at Object.&#x3C;anonymous> (/home/index.js.js:3:1)
    at Module._compile (node:internal/modules/cjs/loader:1120:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1174:10)
    at Module.load (node:internal/modules/cjs/loader:998:32)
    at Module._load (node:internal/modules/cjs/loader:839:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:17:47 {
  code: 'ERR_ACCESS_DENIED',
  permission: 'WorkerThreads'
}</code> <button class="copy-button">copy</button></pre>
<h4><code>--build-snapshot</code><span><a class="mark" href="#all_cli_--build-snapshot" id="all_cli_--build-snapshot">#</a></span><a aria-hidden="true" class="legacy" id="cli_build_snapshot"></a></h4>
<div class="api_metadata">
<span>Added in: v18.8.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Generates a snapshot blob when the process exits and writes it to
disk, which can be loaded later with <code>--snapshot-blob</code>.</p>
<p>When building the snapshot, if <code>--snapshot-blob</code> is not specified,
the generated blob will be written, by default, to <code>snapshot.blob</code>
in the current working directory. Otherwise it will be written to
the path specified by <code>--snapshot-blob</code>.</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash"><span class="hljs-built_in">echo</span> <span class="hljs-string">"globalThis.foo = 'I am from the snapshot'"</span> > snapshot.js</span>
<span class="hljs-meta prompt_">
# </span><span class="language-bash">Run snapshot.js to initialize the application and snapshot the</span>
<span class="hljs-meta prompt_"># </span><span class="language-bash">state of it into snapshot.blob.</span>
<span class="hljs-meta prompt_">$ </span><span class="language-bash">node --snapshot-blob snapshot.blob --build-snapshot snapshot.js</span>
<span class="hljs-meta prompt_">
$ </span><span class="language-bash"><span class="hljs-built_in">echo</span> <span class="hljs-string">"console.log(globalThis.foo)"</span> > index.js</span>
<span class="hljs-meta prompt_">
# </span><span class="language-bash">Load the generated snapshot and start the application from index.js.</span>
<span class="hljs-meta prompt_">$ </span><span class="language-bash">node --snapshot-blob snapshot.blob index.js</span>
I am from the snapshot</code> <button class="copy-button">copy</button></pre>
<p>The <a href="#all_v8_startup-snapshot-api"><code>v8.startupSnapshot</code> API</a> can be used to specify an entry point at
snapshot building time, thus avoiding the need of an additional entry
script at deserialization time:</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash"><span class="hljs-built_in">echo</span> <span class="hljs-string">"require('v8').startupSnapshot.setDeserializeMainFunction(() => console.log('I am from the snapshot'))"</span> > snapshot.js</span>
<span class="hljs-meta prompt_">$ </span><span class="language-bash">node --snapshot-blob snapshot.blob --build-snapshot snapshot.js</span>
<span class="hljs-meta prompt_">$ </span><span class="language-bash">node --snapshot-blob snapshot.blob</span>
I am from the snapshot</code> <button class="copy-button">copy</button></pre>
<p>For more information, check out the <a href="#all_v8_startup-snapshot-api"><code>v8.startupSnapshot</code> API</a> documentation.</p>
<p>Currently the support for run-time snapshot is experimental in that:</p>
<ol>
<li>User-land modules are not yet supported in the snapshot, so only
one single file can be snapshotted. Users can bundle their applications
into a single script with their bundler of choice before building
a snapshot, however.</li>
<li>Only a subset of the built-in modules work in the snapshot, though the
Node.js core test suite checks that a few fairly complex applications
can be snapshotted. Support for more modules are being added. If any
crashes or buggy behaviors occur when building a snapshot, please file
a report in the <a href="https://github.com/nodejs/node/issues">Node.js issue tracker</a> and link to it in the
<a href="https://github.com/nodejs/node/issues/44014">tracking issue for user-land snapshots</a>.</li>
</ol>
<h4><code>--build-snapshot-config</code><span><a class="mark" href="#all_cli_--build-snapshot-config" id="all_cli_--build-snapshot-config">#</a></span><a aria-hidden="true" class="legacy" id="cli_build_snapshot_config"></a></h4>
<div class="api_metadata">
<span>Added in: v20.12.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Specifies the path to a JSON configuration file which configures snapshot
creation behavior.</p>
<p>The following options are currently supported:</p>
<ul>
<li><code>builder</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Required. Provides the name to the script that is executed
before building the snapshot, as if <a href="#all_cli_--build-snapshot"><code>--build-snapshot</code></a> had been passed
with <code>builder</code> as the main script name.</li>
<li><code>withoutCodeCache</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Optional. Including the code cache reduces the
time spent on compiling functions included in the snapshot at the expense
of a bigger snapshot size and potentially breaking portability of the
snapshot.</li>
</ul>
<p>When using this flag, additional script files provided on the command line will
not be executed and instead be interpreted as regular command line arguments.</p>
<h4><code>-c</code>, <code>--check</code><span><a class="mark" href="#all_cli_-c---check" id="all_cli_-c---check">#</a></span><a aria-hidden="true" class="legacy" id="cli_c_check"></a></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>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>
<h4><code>--completion-bash</code><span><a class="mark" href="#all_cli_--completion-bash" id="all_cli_--completion-bash">#</a></span><a aria-hidden="true" class="legacy" id="cli_completion_bash"></a></h4>
<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-bash">node --completion-bash > node_bash_completion
<span class="hljs-built_in">source</span> node_bash_completion</code> <button class="copy-button">copy</button></pre>
<h4><code>-C condition</code>, <code>--conditions=condition</code><span><a class="mark" href="#all_cli_-c-condition---conditionscondition" id="all_cli_-c-condition---conditionscondition">#</a></span><a aria-hidden="true" class="legacy" id="cli_c_condition_conditions_condition"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.18.0</td>
<td><p>The flag is no longer experimental.</p></td></tr>
<tr><td>v14.9.0, v12.19.0</td>
<td><p><span>Added in: v14.9.0, v12.19.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p>Provide custom <a href="#all_packages_conditional-exports">conditional exports</a> resolution conditions.</p>
<p>Any number of custom string condition names are permitted.</p>
<p>The default Node.js conditions of <code>"node"</code>, <code>"default"</code>, <code>"import"</code>, and
<code>"require"</code> will always apply as defined.</p>
<p>For example, to run a module with "development" resolutions:</p>
<pre><code class="language-bash">node -C development app.js</code> <button class="copy-button">copy</button></pre>
<h4><code>--cpu-prof</code><span><a class="mark" href="#all_cli_--cpu-prof" id="all_cli_--cpu-prof">#</a></span><a aria-hidden="true" class="legacy" id="cli_cpu_prof"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.16.0</td>
<td><p>The <code>--cpu-prof</code> flags are now stable.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p><span>Added in: v12.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</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 is placed
in the current working directory.</p>
<p>If <code>--cpu-prof-name</code> is not specified, the generated profile is
named <code>CPU.${yyyymmdd}.${hhmmss}.${pid}.${tid}.${seq}.cpuprofile</code>.</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node --cpu-prof index.js</span>
<span class="hljs-meta prompt_">$ </span><span class="language-bash"><span class="hljs-built_in">ls</span> *.cpuprofile</span>
CPU.20190409.202950.15293.0.0.cpuprofile</code> <button class="copy-button">copy</button></pre>
<h4><code>--cpu-prof-dir</code><span><a class="mark" href="#all_cli_--cpu-prof-dir" id="all_cli_--cpu-prof-dir">#</a></span><a aria-hidden="true" class="legacy" id="cli_cpu_prof_dir"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.16.0</td>
<td><p>The <code>--cpu-prof</code> flags are now stable.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p><span>Added in: v12.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p>Specify the directory where the CPU profiles generated by <code>--cpu-prof</code> will
be placed.</p>
<p>The default value is controlled by the
<a href="#all_cli_--diagnostic-dirdirectory"><code>--diagnostic-dir</code></a> command-line option.</p>
<h4><code>--cpu-prof-interval</code><span><a class="mark" href="#all_cli_--cpu-prof-interval" id="all_cli_--cpu-prof-interval">#</a></span><a aria-hidden="true" class="legacy" id="cli_cpu_prof_interval"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.16.0</td>
<td><p>The <code>--cpu-prof</code> flags are now stable.</p></td></tr>
<tr><td>v12.2.0</td>
<td><p><span>Added in: v12.2.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</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>
<h4><code>--cpu-prof-name</code><span><a class="mark" href="#all_cli_--cpu-prof-name" id="all_cli_--cpu-prof-name">#</a></span><a aria-hidden="true" class="legacy" id="cli_cpu_prof_name"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.16.0</td>
<td><p>The <code>--cpu-prof</code> flags are now stable.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p><span>Added in: v12.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p>Specify the file name of the CPU profile generated by <code>--cpu-prof</code>.</p>
<h4><code>--diagnostic-dir=directory</code><span><a class="mark" href="#all_cli_--diagnostic-dirdirectory" id="all_cli_--diagnostic-dirdirectory">#</a></span><a aria-hidden="true" class="legacy" id="cli_diagnostic_dir_directory"></a></h4>
<p>Set the directory to which all diagnostic output files are written.
Defaults to current working directory.</p>
<p>Affects the default output directory of:</p>
<ul>
<li><a href="#all_cli_--cpu-prof-dir"><code>--cpu-prof-dir</code></a></li>
<li><a href="#all_cli_--heap-prof-dir"><code>--heap-prof-dir</code></a></li>
<li><a href="#all_cli_--redirect-warningsfile"><code>--redirect-warnings</code></a></li>
</ul>
<h4><code>--disable-warning=code-or-type</code><span><a class="mark" href="#all_cli_--disable-warningcode-or-type" id="all_cli_--disable-warningcode-or-type">#</a></span><a aria-hidden="true" class="legacy" id="cli_disable_warning_code_or_type"></a></h4>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active development</div><p></p>
<div class="api_metadata">
<span>Added in: v20.11.0</span>
</div>
<p>Disable specific process warnings by <code>code</code> or <code>type</code>.</p>
<p>Warnings emitted from <a href="#all_process_processemitwarningwarning-options"><code>process.emitWarning()</code></a> may contain a
<code>code</code> and a <code>type</code>. This option will not-emit warnings that have a matching
<code>code</code> or <code>type</code>.</p>
<p>List of <a href="#all_deprecations_list-of-deprecated-apis">deprecation warnings</a>.</p>
<p>The Node.js core warning types are: <code>DeprecationWarning</code> and
<code>ExperimentalWarning</code></p>
<p>For example, the following script will not emit
<a href="#all_deprecations_dep0025-requirenodesys">DEP0025 <code>require('node:sys')</code></a> when executed with
<code>node --disable-warning=DEP0025</code>:</p>

<pre class="with-32-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> sys <span class="hljs-keyword">from</span> <span class="hljs-string">'node:sys'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> sys = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:sys'</span>);</code><button class="copy-button">copy</button></pre>
<p>For example, the following script will emit the
<a href="#all_deprecations_dep0025-requirenodesys">DEP0025 <code>require('node:sys')</code></a>, but not any Experimental
Warnings (such as
<a href="#all_vm_vmmeasurememoryoptions">ExperimentalWarning: <code>vm.measureMemory</code> is an experimental feature</a>
in &#x3C;=v21) when executed with <code>node --disable-warning=ExperimentalWarning</code>:</p>

<pre class="with-32-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> sys <span class="hljs-keyword">from</span> <span class="hljs-string">'node:sys'</span>;
<span class="hljs-keyword">import</span> vm <span class="hljs-keyword">from</span> <span class="hljs-string">'node:vm'</span>;

vm.<span class="hljs-title function_">measureMemory</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> sys = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:sys'</span>);
<span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

vm.<span class="hljs-title function_">measureMemory</span>();</code><button class="copy-button">copy</button></pre>
<h4><code>--disable-wasm-trap-handler</code><span><a class="mark" href="#all_cli_--disable-wasm-trap-handler" id="all_cli_--disable-wasm-trap-handler">#</a></span><a aria-hidden="true" class="legacy" id="cli_disable_wasm_trap_handler"></a></h4>
<div class="api_metadata">
<span>Added in: v20.15.0</span>
</div>
<p>By default, Node.js enables trap-handler-based WebAssembly bound
checks. As a result, V8 does not need to insert inline bound checks
int the code compiled from WebAssembly which may speedup WebAssembly
execution significantly, but this optimization requires allocating
a big virtual memory cage (currently 10GB). If the Node.js process
does not have access to a large enough virtual memory address space
due to system configurations or hardware limitations, users won't
be able to run any WebAssembly that involves allocation in this
virtual memory cage and will see an out-of-memory error.</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash"><span class="hljs-built_in">ulimit</span> -v 5000000</span>
<span class="hljs-meta prompt_">$ </span><span class="language-bash">node -p <span class="hljs-string">"new WebAssembly.Memory({ initial: 10, maximum: 100 });"</span></span>
[eval]:1
new WebAssembly.Memory({ initial: 10, maximum: 100 });
^

RangeError: WebAssembly.Memory(): could not allocate memory
    at [eval]:1:1
    at runScriptInThisContext (node:internal/vm:209:10)
    at node:internal/process/execution:118:14
    at [eval]-wrapper:6:24
    at runScript (node:internal/process/execution:101:62)
    at evalScript (node:internal/process/execution:136:3)
    at node:internal/main/eval_string:49:3
</code> <button class="copy-button">copy</button></pre>
<p><code>--disable-wasm-trap-handler</code> disables this optimization so that
users can at least run WebAssembly (with less optimal performance)
when the virtual memory address space available to their Node.js
process is lower than what the V8 WebAssembly memory cage needs.</p>
<h4><code>--disable-proto=mode</code><span><a class="mark" href="#all_cli_--disable-protomode" id="all_cli_--disable-protomode">#</a></span><a aria-hidden="true" class="legacy" id="cli_disable_proto_mode"></a></h4>
<div class="api_metadata">
<span>Added in: v13.12.0, v12.17.0</span>
</div>
<p>Disable the <code>Object.prototype.__proto__</code> property. If <code>mode</code> is <code>delete</code>, the
property is removed entirely. If <code>mode</code> is <code>throw</code>, accesses to the
property throw an exception with the code <code>ERR_PROTO_ACCESS</code>.</p>
<h4><code>--disallow-code-generation-from-strings</code><span><a class="mark" href="#all_cli_--disallow-code-generation-from-strings" id="all_cli_--disallow-code-generation-from-strings">#</a></span><a aria-hidden="true" class="legacy" id="cli_disallow_code_generation_from_strings"></a></h4>
<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>node:vm</code> module.</p>
<h4><code>--expose-gc</code><span><a class="mark" href="#all_cli_--expose-gc" id="all_cli_--expose-gc">#</a></span><a aria-hidden="true" class="legacy" id="cli_expose_gc"></a></h4>
<div class="api_metadata">
<span>Added in: v20.18.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental. This flag is inherited from V8 and is subject to
change upstream.</div><p></p>
<p>This flag will expose the gc extension from V8.</p>
<pre><code class="language-js"><span class="hljs-keyword">if</span> (globalThis.<span class="hljs-property">gc</span>) {
  globalThis.<span class="hljs-title function_">gc</span>();
}</code> <button class="copy-button">copy</button></pre>
<h4><code>--dns-result-order=order</code><span><a class="mark" href="#all_cli_--dns-result-orderorder" id="all_cli_--dns-result-orderorder">#</a></span><a aria-hidden="true" class="legacy" id="cli_dns_result_order_order"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.13.0</td>
<td><p>The <code>ipv6first</code> is supported now.</p></td></tr>
<tr><td>v17.0.0</td>
<td><p>Changed default value to <code>verbatim</code>.</p></td></tr>
<tr><td>v16.4.0, v14.18.0</td>
<td><p><span>Added in: v16.4.0, v14.18.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Set the default value of <code>order</code> in <a href="#all_dns_dnslookuphostname-options-callback"><code>dns.lookup()</code></a> and
<a href="#all_dns_dnspromiseslookuphostname-options"><code>dnsPromises.lookup()</code></a>. The value could be:</p>
<ul>
<li><code>ipv4first</code>: sets default <code>order</code> to <code>ipv4first</code>.</li>
<li><code>ipv6first</code>: sets default <code>order</code> to <code>ipv6first</code>.</li>
<li><code>verbatim</code>: sets default <code>order</code> to <code>verbatim</code>.</li>
</ul>
<p>The default is <code>verbatim</code> and <a href="#all_dns_dnssetdefaultresultorderorder"><code>dns.setDefaultResultOrder()</code></a> have higher
priority than <code>--dns-result-order</code>.</p>
<h4><code>--enable-fips</code><span><a class="mark" href="#all_cli_--enable-fips" id="all_cli_--enable-fips">#</a></span><a aria-hidden="true" class="legacy" id="cli_enable_fips"></a></h4>
<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
against FIPS-compatible OpenSSL.)</p>
<h4><code>--enable-source-maps</code><span><a class="mark" href="#all_cli_--enable-source-maps" id="all_cli_--enable-source-maps">#</a></span><a aria-hidden="true" class="legacy" id="cli_enable_source_maps"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.11.0, v14.18.0</td>
<td><p>This API is no longer experimental.</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>
<p>Enable <a href="https://sourcemaps.info/spec.html">Source Map v3</a> support for stack traces.</p>
<p>When using a transpiler, such as TypeScript, stack traces thrown by an
application reference the transpiled code, not the original source position.
<code>--enable-source-maps</code> enables caching of Source Maps and makes a best
effort to report stack traces relative to the original source file.</p>
<p>Overriding <code>Error.prepareStackTrace</code> may prevent <code>--enable-source-maps</code> from
modifying the stack trace. Call and return the results of the original
<code>Error.prepareStackTrace</code> in the overriding function to modify the stack trace
with source maps.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> originalPrepareStackTrace = <span class="hljs-title class_">Error</span>.<span class="hljs-property">prepareStackTrace</span>;
<span class="hljs-title class_">Error</span>.<span class="hljs-property">prepareStackTrace</span> = <span class="hljs-function">(<span class="hljs-params">error, trace</span>) =></span> {
  <span class="hljs-comment">// Modify error and trace and format stack trace with</span>
  <span class="hljs-comment">// original Error.prepareStackTrace.</span>
  <span class="hljs-keyword">return</span> <span class="hljs-title function_">originalPrepareStackTrace</span>(error, trace);
};</code> <button class="copy-button">copy</button></pre>
<p>Note, enabling source maps can introduce latency to your application
when <code>Error.stack</code> is accessed. If you access <code>Error.stack</code> frequently
in your application, take into account the performance implications
of <code>--enable-source-maps</code>.</p>
<h4><code>--env-file=config</code><span><a class="mark" href="#all_cli_--env-fileconfig" id="all_cli_--env-fileconfig">#</a></span><a aria-hidden="true" class="legacy" id="cli_env_file_config"></a></h4>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active development</div><p></p>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.12.0</td>
<td><p>Add support to multi-line values.</p></td></tr>
<tr><td>v20.6.0</td>
<td><p><span>Added in: v20.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Loads environment variables from a file relative to the current directory,
making them available to applications on <code>process.env</code>. The <a href="#all_cli_environment-variables">environment
variables which configure Node.js</a>, such as <code>NODE_OPTIONS</code>,
are parsed and applied. If the same variable is defined in the environment and
in the file, the value from the environment takes precedence.</p>
<p>You can pass multiple <code>--env-file</code> arguments. Subsequent files override
pre-existing variables defined in previous files.</p>
<pre><code class="language-bash">node --env-file=.<span class="hljs-built_in">env</span> --env-file=.development.env index.js</code> <button class="copy-button">copy</button></pre>
<p>The format of the file should be one line per key-value pair of environment
variable name and value separated by <code>=</code>:</p>
<pre><code class="language-text">PORT=3000</code> <button class="copy-button">copy</button></pre>
<p>Any text after a <code>#</code> is treated as a comment:</p>
<pre><code class="language-text"># This is a comment
PORT=3000 # This is also a comment</code> <button class="copy-button">copy</button></pre>
<p>Values can start and end with the following quotes: <code>`</code>, <code>"</code> or <code>'</code>.
They are omitted from the values.</p>
<pre><code class="language-text">USERNAME="nodejs" # will result in `nodejs` as the value.</code> <button class="copy-button">copy</button></pre>
<p>Multi-line values are supported:</p>
<pre><code class="language-text">MULTI_LINE="THIS IS
A MULTILINE"
# will result in `THIS IS\nA MULTILINE` as the value.</code> <button class="copy-button">copy</button></pre>
<p>Export keyword before a key is ignored:</p>
<pre><code class="language-text">export USERNAME="nodejs" # will result in `nodejs` as the value.</code> <button class="copy-button">copy</button></pre>
<h4><code>-e</code>, <code>--eval "script"</code><span><a class="mark" href="#all_cli_-e---eval-script" id="all_cli_-e---eval-script">#</a></span><a aria-hidden="true" class="legacy" id="cli_e_eval_script"></a></h4>
<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>
<h4><code>--experimental-default-type=type</code><span><a class="mark" href="#all_cli_--experimental-default-typetype" id="all_cli_--experimental-default-typetype">#</a></span><a aria-hidden="true" class="legacy" id="cli_experimental_default_type_type"></a></h4>
<div class="api_metadata">
<span>Added in: v20.10.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.0 - Early development</div><p></p>
<p>Define which module system, <code>module</code> or <code>commonjs</code>, to use for the following:</p>
<ul>
<li>
<p>String input provided via <code>--eval</code> or STDIN, if <code>--input-type</code> is unspecified.</p>
</li>
<li>
<p>Files ending in <code>.js</code> or with no extension, if there is no <code>package.json</code> file
present in the same folder or any parent folder.</p>
</li>
<li>
<p>Files ending in <code>.js</code> or with no extension, if the nearest parent
<code>package.json</code> field lacks a <code>"type"</code> field; unless the <code>package.json</code> folder
or any parent folder is inside a <code>node_modules</code> folder.</p>
</li>
</ul>
<p>In other words, <code>--experimental-default-type=module</code> flips all the places where
Node.js currently defaults to CommonJS to instead default to ECMAScript modules,
with the exception of folders and subfolders below <code>node_modules</code>, for backward
compatibility.</p>
<p>Under <code>--experimental-default-type=module</code> and <code>--experimental-wasm-modules</code>,
files with no extension will be treated as WebAssembly if they begin with the
WebAssembly magic number (<code>\0asm</code>); otherwise they will be treated as ES module
JavaScript.</p>
<h4><code>--experimental-detect-module</code><span><a class="mark" href="#all_cli_--experimental-detect-module" id="all_cli_--experimental-detect-module">#</a></span><a aria-hidden="true" class="legacy" id="cli_experimental_detect_module"></a></h4>
<div class="api_metadata">
<span>Added in: v20.10.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active development</div><p></p>
<p>Node.js will inspect the source code of ambiguous input to determine whether it
contains ES module syntax; if such syntax is detected, the input will be treated
as an ES module.</p>
<p>Ambiguous input is defined as:</p>
<ul>
<li>Files with a <code>.js</code> extension or no extension; and either no controlling
<code>package.json</code> file or one that lacks a <code>type</code> field; and
<code>--experimental-default-type</code> is not specified.</li>
<li>String input (<code>--eval</code> or STDIN) when neither <code>--input-type</code> nor
<code>--experimental-default-type</code> are specified.</li>
</ul>
<p>ES module syntax is defined as syntax that would throw when evaluated as
CommonJS. This includes the following:</p>
<ul>
<li><code>import</code> statements (but <em>not</em> <code>import()</code> expressions, which are valid in
CommonJS).</li>
<li><code>export</code> statements.</li>
<li><code>import.meta</code> references.</li>
<li><code>await</code> at the top level of a module.</li>
<li>Lexical redeclarations of the CommonJS wrapper variables (<code>require</code>, <code>module</code>,
<code>exports</code>, <code>__dirname</code>, <code>__filename</code>).</li>
</ul>
<h4><code>--experimental-eventsource</code><span><a class="mark" href="#all_cli_--experimental-eventsource" id="all_cli_--experimental-eventsource">#</a></span><a aria-hidden="true" class="legacy" id="cli_experimental_eventsource"></a></h4>
<div class="api_metadata">
<span>Added in: v20.18.0</span>
</div>
<p>Enable exposition of <a href="https://html.spec.whatwg.org/multipage/server-sent-events.html#server-sent-events">EventSource Web API</a> on the global scope.</p>
<h4><code>--experimental-import-meta-resolve</code><span><a class="mark" href="#all_cli_--experimental-import-meta-resolve" id="all_cli_--experimental-import-meta-resolve">#</a></span><a aria-hidden="true" class="legacy" id="cli_experimental_import_meta_resolve"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.6.0</td>
<td><p>synchronous import.meta.resolve made available by default, with the flag retained for enabling the experimental second argument as previously supported.</p></td></tr>
<tr><td>v13.9.0, v12.16.2</td>
<td><p><span>Added in: v13.9.0, v12.16.2</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Enable experimental <code>import.meta.resolve()</code> parent URL support, which allows
passing a second <code>parentURL</code> argument for contextual resolution.</p>
<p>Previously gated the entire <code>import.meta.resolve</code> feature.</p>
<h4><code>--experimental-loader=module</code><span><a class="mark" href="#all_cli_--experimental-loadermodule" id="all_cli_--experimental-loadermodule">#</a></span><a aria-hidden="true" class="legacy" id="cli_experimental_loader_module"></a></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.1</td>
<td><p>This flag was renamed from <code>--loader</code> to <code>--experimental-loader</code>.</p></td></tr>
<tr><td>v8.8.0</td>
<td><p><span>Added in: v8.8.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<blockquote>
<p>This flag is discouraged and may be removed in a future version of Node.js.
Please use
<a href="#all_module_enabling"><code>--import</code> with <code>register()</code></a> instead.</p>
</blockquote>
<p>Specify the <code>module</code> containing exported <a href="#all_module_customization-hooks">module customization hooks</a>.
<code>module</code> may be any string accepted as an <a href="#all_esm_import-specifiers"><code>import</code> specifier</a>.</p>
<h4><code>--experimental-network-imports</code><span><a class="mark" href="#all_cli_--experimental-network-imports" id="all_cli_--experimental-network-imports">#</a></span><a aria-hidden="true" class="legacy" id="cli_experimental_network_imports"></a></h4>
<div class="api_metadata">
<span>Added in: v17.6.0, v16.15.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Enable experimental support for the <code>https:</code> protocol in <code>import</code> specifiers.</p>
<h4><code>--experimental-network-inspection</code><span><a class="mark" href="#all_cli_--experimental-network-inspection" id="all_cli_--experimental-network-inspection">#</a></span><a aria-hidden="true" class="legacy" id="cli_experimental_network_inspection"></a></h4>
<div class="api_metadata">
<span>Added in: v20.18.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Enable experimental support for the network inspection with Chrome DevTools.</p>
<h4><code>--experimental-permission</code><span><a class="mark" href="#all_cli_--experimental-permission" id="all_cli_--experimental-permission">#</a></span><a aria-hidden="true" class="legacy" id="cli_experimental_permission"></a></h4>
<div class="api_metadata">
<span>Added in: v20.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active development</div><p></p>
<p>Enable the Permission Model for current process. When enabled, the
following permissions are restricted:</p>
<ul>
<li>File System - manageable through
<a href="#all_cli_--allow-fs-read"><code>--allow-fs-read</code></a>, <a href="#all_cli_--allow-fs-write"><code>--allow-fs-write</code></a> flags</li>
<li>Child Process - manageable through <a href="#all_cli_--allow-child-process"><code>--allow-child-process</code></a> flag</li>
<li>Worker Threads - manageable through <a href="#all_cli_--allow-worker"><code>--allow-worker</code></a> flag</li>
<li>WASI - manageable through <a href="#all_cli_--allow-wasi"><code>--allow-wasi</code></a> flag</li>
</ul>
<h4><code>--experimental-policy</code><span><a class="mark" href="#all_cli_--experimental-policy" id="all_cli_--experimental-policy">#</a></span><a aria-hidden="true" class="legacy" id="cli_experimental_policy"></a></h4>
<div class="api_metadata">
<span>Added in: v11.8.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Will be removed shortly.</div><p></p>
<p>Use the specified file as a security policy.</p>
<h4><code>--experimental-require-module</code><span><a class="mark" href="#all_cli_--experimental-require-module" id="all_cli_--experimental-require-module">#</a></span><a aria-hidden="true" class="legacy" id="cli_experimental_require_module"></a></h4>
<div class="api_metadata">
<span>Added in: v20.17.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active Development</div><p></p>
<p>Supports loading a synchronous ES module graph in <code>require()</code>.</p>
<p>See <a href="#all_modules_loading-ecmascript-modules-using-require">Loading ECMAScript modules using <code>require()</code></a>.</p>
<h4><code>--experimental-sea-config</code><span><a class="mark" href="#all_cli_--experimental-sea-config" id="all_cli_--experimental-sea-config">#</a></span><a aria-hidden="true" class="legacy" id="cli_experimental_sea_config"></a></h4>
<div class="api_metadata">
<span>Added in: v20.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Use this flag to generate a blob that can be injected into the Node.js
binary to produce a <a href="single-executable-applications.html">single executable application</a>. See the documentation
about <a href="#all_single-executable-applications_generating-single-executable-preparation-blobs">this configuration</a> for details.</p>
<h4><code>--experimental-shadow-realm</code><span><a class="mark" href="#all_cli_--experimental-shadow-realm" id="all_cli_--experimental-shadow-realm">#</a></span><a aria-hidden="true" class="legacy" id="cli_experimental_shadow_realm"></a></h4>
<div class="api_metadata">
<span>Added in: v19.0.0, v18.13.0</span>
</div>
<p>Use this flag to enable <a href="https://github.com/tc39/proposal-shadowrealm">ShadowRealm</a> support.</p>
<h4><code>--experimental-test-coverage</code><span><a class="mark" href="#all_cli_--experimental-test-coverage" id="all_cli_--experimental-test-coverage">#</a></span><a aria-hidden="true" class="legacy" id="cli_experimental_test_coverage"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.1.0</td>
<td><p>This option can be used with <code>--test</code>.</p></td></tr>
<tr><td>v19.7.0, v18.15.0</td>
<td><p><span>Added in: v19.7.0, v18.15.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>When used in conjunction with the <code>node:test</code> module, a code coverage report is
generated as part of the test runner output. If no tests are run, a coverage
report is not generated. See the documentation on
<a href="#all_test_collecting-code-coverage">collecting code coverage from tests</a> for more details.</p>
<h4><code>--experimental-test-module-mocks</code><span><a class="mark" href="#all_cli_--experimental-test-module-mocks" id="all_cli_--experimental-test-module-mocks">#</a></span><a aria-hidden="true" class="legacy" id="cli_experimental_test_module_mocks"></a></h4>
<div class="api_metadata">
<span>Added in: v20.18.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.0 - Early development</div><p></p>
<p>Enable module mocking in the test runner.</p>
<h4><code>--experimental-vm-modules</code><span><a class="mark" href="#all_cli_--experimental-vm-modules" id="all_cli_--experimental-vm-modules">#</a></span><a aria-hidden="true" class="legacy" id="cli_experimental_vm_modules"></a></h4>
<div class="api_metadata">
<span>Added in: v9.6.0</span>
</div>
<p>Enable experimental ES Module support in the <code>node:vm</code> module.</p>
<h4><code>--experimental-wasi-unstable-preview1</code><span><a class="mark" href="#all_cli_--experimental-wasi-unstable-preview1" id="all_cli_--experimental-wasi-unstable-preview1">#</a></span><a aria-hidden="true" class="legacy" id="cli_experimental_wasi_unstable_preview1"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>This option is no longer required as WASI is enabled by default, but can still be passed.</p></td></tr>
<tr><td>v13.6.0</td>
<td><p>changed from <code>--experimental-wasi-unstable-preview0</code> to <code>--experimental-wasi-unstable-preview1</code>.</p></td></tr>
<tr><td>v13.3.0, v12.16.0</td>
<td><p><span>Added in: v13.3.0, v12.16.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Enable experimental WebAssembly System Interface (WASI) support.</p>
<h4><code>--experimental-wasm-modules</code><span><a class="mark" href="#all_cli_--experimental-wasm-modules" id="all_cli_--experimental-wasm-modules">#</a></span><a aria-hidden="true" class="legacy" id="cli_experimental_wasm_modules"></a></h4>
<div class="api_metadata">
<span>Added in: v12.3.0</span>
</div>
<p>Enable experimental WebAssembly module support.</p>
<h4><code>--experimental-websocket</code><span><a class="mark" href="#all_cli_--experimental-websocket" id="all_cli_--experimental-websocket">#</a></span><a aria-hidden="true" class="legacy" id="cli_experimental_websocket"></a></h4>
<div class="api_metadata">
<span>Added in: v20.10.0</span>
</div>
<p>Enable experimental <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSocket"><code>WebSocket</code></a> support.</p>
<h4><code>--force-context-aware</code><span><a class="mark" href="#all_cli_--force-context-aware" id="all_cli_--force-context-aware">#</a></span><a aria-hidden="true" class="legacy" id="cli_force_context_aware"></a></h4>
<div class="api_metadata">
<span>Added in: v12.12.0</span>
</div>
<p>Disable loading native addons that are not <a href="#all_addons_context-aware-addons">context-aware</a>.</p>
<h4><code>--force-fips</code><span><a class="mark" href="#all_cli_--force-fips" id="all_cli_--force-fips">#</a></span><a aria-hidden="true" class="legacy" id="cli_force_fips"></a></h4>
<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>
<h4><code>--force-node-api-uncaught-exceptions-policy</code><span><a class="mark" href="#all_cli_--force-node-api-uncaught-exceptions-policy" id="all_cli_--force-node-api-uncaught-exceptions-policy">#</a></span><a aria-hidden="true" class="legacy" id="cli_force_node_api_uncaught_exceptions_policy"></a></h4>
<div class="api_metadata">
<span>Added in: v18.3.0, v16.17.0</span>
</div>
<p>Enforces <code>uncaughtException</code> event on Node-API asynchronous callbacks.</p>
<p>To prevent from an existing add-on from crashing the process, this flag is not
enabled by default. In the future, this flag will be enabled by default to
enforce the correct behavior.</p>
<h4><code>--frozen-intrinsics</code><span><a class="mark" href="#all_cli_--frozen-intrinsics" id="all_cli_--frozen-intrinsics">#</a></span><a aria-hidden="true" class="legacy" id="cli_frozen_intrinsics"></a></h4>
<div class="api_metadata">
<span>Added in: v11.12.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_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>Only the root context is supported. There is no guarantee that
<code>globalThis.Array</code> is indeed the default intrinsic reference. Code may break
under this flag.</p>
<p>To allow polyfills to be added,
<a href="#all_cli_-r---require-module"><code>--require</code></a> and <a href="#all_cli_--importmodule"><code>--import</code></a> both run before freezing intrinsics.</p>
<h4><code>--heap-prof</code><span><a class="mark" href="#all_cli_--heap-prof" id="all_cli_--heap-prof">#</a></span><a aria-hidden="true" class="legacy" id="cli_heap_prof"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.16.0</td>
<td><p>The <code>--heap-prof</code> flags are now stable.</p></td></tr>
<tr><td>v12.4.0</td>
<td><p><span>Added in: v12.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</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 is placed
in the current working directory.</p>
<p>If <code>--heap-prof-name</code> is not specified, the generated profile is
named <code>Heap.${yyyymmdd}.${hhmmss}.${pid}.${tid}.${seq}.heapprofile</code>.</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node --heap-prof index.js</span>
<span class="hljs-meta prompt_">$ </span><span class="language-bash"><span class="hljs-built_in">ls</span> *.heapprofile</span>
Heap.20190409.202950.15293.0.001.heapprofile</code> <button class="copy-button">copy</button></pre>
<h4><code>--heap-prof-dir</code><span><a class="mark" href="#all_cli_--heap-prof-dir" id="all_cli_--heap-prof-dir">#</a></span><a aria-hidden="true" class="legacy" id="cli_heap_prof_dir"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.16.0</td>
<td><p>The <code>--heap-prof</code> flags are now stable.</p></td></tr>
<tr><td>v12.4.0</td>
<td><p><span>Added in: v12.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p>Specify the directory where the heap profiles generated by <code>--heap-prof</code> will
be placed.</p>
<p>The default value is controlled by the
<a href="#all_cli_--diagnostic-dirdirectory"><code>--diagnostic-dir</code></a> command-line option.</p>
<h4><code>--heap-prof-interval</code><span><a class="mark" href="#all_cli_--heap-prof-interval" id="all_cli_--heap-prof-interval">#</a></span><a aria-hidden="true" class="legacy" id="cli_heap_prof_interval"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.16.0</td>
<td><p>The <code>--heap-prof</code> flags are now stable.</p></td></tr>
<tr><td>v12.4.0</td>
<td><p><span>Added in: v12.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</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>
<h4><code>--heap-prof-name</code><span><a class="mark" href="#all_cli_--heap-prof-name" id="all_cli_--heap-prof-name">#</a></span><a aria-hidden="true" class="legacy" id="cli_heap_prof_name"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.16.0</td>
<td><p>The <code>--heap-prof</code> flags are now stable.</p></td></tr>
<tr><td>v12.4.0</td>
<td><p><span>Added in: v12.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p>Specify the file name of the heap profile generated by <code>--heap-prof</code>.</p>
<h4><code>--heapsnapshot-near-heap-limit=max_count</code><span><a class="mark" href="#all_cli_--heapsnapshot-near-heap-limitmax_count" id="all_cli_--heapsnapshot-near-heap-limitmax_count">#</a></span><a aria-hidden="true" class="legacy" id="cli_heapsnapshot_near_heap_limit_max_count"></a></h4>
<div class="api_metadata">
<span>Added in: v15.1.0, v14.18.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Writes a V8 heap snapshot to disk when the V8 heap usage is approaching the
heap limit. <code>count</code> should be a non-negative integer (in which case
Node.js will write no more than <code>max_count</code> snapshots to disk).</p>
<p>When generating snapshots, garbage collection may be triggered and bring
the heap usage down. Therefore multiple snapshots may be written to disk
before the Node.js instance finally runs out of memory. These heap snapshots
can be compared to determine what objects are being allocated during the
time consecutive snapshots are taken. It's not guaranteed that Node.js will
write exactly <code>max_count</code> snapshots to disk, but it will try
its best to generate at least one and up to <code>max_count</code> snapshots before the
Node.js instance runs out of memory when <code>max_count</code> is greater than <code>0</code>.</p>
<p>Generating V8 snapshots takes time and memory (both memory managed by the
V8 heap and native memory outside the V8 heap). The bigger the heap is,
the more resources it needs. Node.js will adjust the V8 heap to accommodate
the additional V8 heap memory overhead, and try its best to avoid using up
all the memory available to the process. When the process uses
more memory than the system deems appropriate, the process may be terminated
abruptly by the system, depending on the system configuration.</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node --max-old-space-size=100 --heapsnapshot-near-heap-limit=3 index.js</span>
Wrote snapshot to Heap.20200430.100036.49580.0.001.heapsnapshot
Wrote snapshot to Heap.20200430.100037.49580.0.002.heapsnapshot
Wrote snapshot to Heap.20200430.100038.49580.0.003.heapsnapshot

&#x3C;--- Last few GCs --->

[49580:0x110000000]     4826 ms: Mark-sweep 130.6 (147.8) -> 130.5 (147.8) MB, 27.4 / 0.0 ms  (average mu = 0.126, current mu = 0.034) allocation failure scavenge might not succeed
[49580:0x110000000]     4845 ms: Mark-sweep 130.6 (147.8) -> 130.6 (147.8) MB, 18.8 / 0.0 ms  (average mu = 0.088, current mu = 0.031) allocation failure scavenge might not succeed


&#x3C;--- JS stacktrace --->

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
....</code> <button class="copy-button">copy</button></pre>
<h4><code>--heapsnapshot-signal=signal</code><span><a class="mark" href="#all_cli_--heapsnapshot-signalsignal" id="all_cli_--heapsnapshot-signalsignal">#</a></span><a aria-hidden="true" class="legacy" id="cli_heapsnapshot_signal_signal"></a></h4>
<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"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node --heapsnapshot-signal=SIGUSR2 index.js &#x26;</span>
<span class="hljs-meta prompt_">$ </span><span class="language-bash">ps aux</span>
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
<span class="hljs-meta prompt_">$ </span><span class="language-bash"><span class="hljs-built_in">kill</span> -USR2 1</span>
<span class="hljs-meta prompt_">$ </span><span class="language-bash"><span class="hljs-built_in">ls</span></span>
Heap.20190718.133405.15554.0.001.heapsnapshot</code> <button class="copy-button">copy</button></pre>
<h4><code>-h</code>, <code>--help</code><span><a class="mark" href="#all_cli_-h---help" id="all_cli_-h---help">#</a></span><a aria-hidden="true" class="legacy" id="cli_h_help"></a></h4>
<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>
<h4><code>--icu-data-dir=file</code><span><a class="mark" href="#all_cli_--icu-data-dirfile" id="all_cli_--icu-data-dirfile">#</a></span><a aria-hidden="true" class="legacy" id="cli_icu_data_dir_file"></a></h4>
<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>
<h4><code>--import=module</code><span><a class="mark" href="#all_cli_--importmodule" id="all_cli_--importmodule">#</a></span><a aria-hidden="true" class="legacy" id="cli_import_module"></a></h4>
<div class="api_metadata">
<span>Added in: v19.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Preload the specified module at startup. If the flag is provided several times,
each module will be executed sequentially in the order they appear, starting
with the ones provided in <a href="#all_cli_node_optionsoptions"><code>NODE_OPTIONS</code></a>.</p>
<p>Follows <a href="#all_esm_modules-ecmascript-modules">ECMAScript module</a> resolution rules.
Use <a href="#all_cli_-r---require-module"><code>--require</code></a> to load a <a href="modules.html">CommonJS module</a>.
Modules preloaded with <code>--require</code> will run before modules preloaded with <code>--import</code>.</p>
<h4><code>--input-type=type</code><span><a class="mark" href="#all_cli_--input-typetype" id="all_cli_--input-typetype">#</a></span><a aria-hidden="true" class="legacy" id="cli_input_type_type"></a></h4>
<div class="api_metadata">
<span>Added in: v12.0.0</span>
</div>
<p>This configures Node.js to interpret <code>--eval</code> or <code>STDIN</code> input as CommonJS or
as an ES module. Valid values are <code>"commonjs"</code> or <code>"module"</code>. The default is
<code>"commonjs"</code> unless <a href="#all_cli_--experimental-default-typetype"><code>--experimental-default-type=module</code></a> is used.</p>
<p>The REPL does not support this option. Usage of <code>--input-type=module</code> with
<a href="#all_cli_-p---print-script"><code>--print</code></a> will throw an error, as <code>--print</code> does not support ES module
syntax.</p>
<h4><code>--insecure-http-parser</code><span><a class="mark" href="#all_cli_--insecure-http-parser" id="all_cli_--insecure-http-parser">#</a></span><a aria-hidden="true" class="legacy" id="cli_insecure_http_parser"></a></h4>
<div class="api_metadata">
<span>Added in: v13.4.0, v12.15.0, v10.19.0</span>
</div>
<p>Use an insecure HTTP parser that accepts invalid HTTP headers. This may allow
interoperability with non-conformant HTTP implementations. It may also allow
request smuggling and other HTTP attacks that rely on invalid headers being
accepted. Avoid using this option.</p>
<h4><code>--inspect[=[host:]port]</code><span><a class="mark" href="#all_cli_--inspecthostport" id="all_cli_--inspecthostport">#</a></span><a aria-hidden="true" class="legacy" id="cli_inspect_host_port"></a></h4>
<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>. If port <code>0</code> is
specified, a random available port will be used.</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>.
See <a href="#all_debugger_v8-inspector-integration-for-nodejs">V8 Inspector integration for Node.js</a> for further explanation on Node.js debugger.</p>
<!-- Anchor to make sure old links find a target -->
<p><a id="inspector_security"></a></p>
<h5>Warning: binding inspector to a public IP:port combination is insecure<span><a class="mark" href="#all_cli_warning-binding-inspector-to-a-public-ipport-combination-is-insecure" id="all_cli_warning-binding-inspector-to-a-public-ipport-combination-is-insecure">#</a></span><a aria-hidden="true" class="legacy" id="cli_warning_binding_inspector_to_a_public_ip_port_combination_is_insecure"></a></h5>
<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>
<h4><code>--inspect-brk[=[host:]port]</code><span><a class="mark" href="#all_cli_--inspect-brkhostport" id="all_cli_--inspect-brkhostport">#</a></span><a aria-hidden="true" class="legacy" id="cli_inspect_brk_host_port"></a></h4>
<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>. If port <code>0</code> is specified,
a random available port will be used.</p>
<p>See <a href="#all_debugger_v8-inspector-integration-for-nodejs">V8 Inspector integration for Node.js</a> for further explanation on Node.js debugger.</p>
<h4><code>--inspect-port=[host:]port</code><span><a class="mark" href="#all_cli_--inspect-porthostport" id="all_cli_--inspect-porthostport">#</a></span><a aria-hidden="true" class="legacy" id="cli_inspect_port_host_port"></a></h4>
<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>. If port <code>0</code> is specified,
a random available port will be used.</p>
<p>See the <a href="#all_cli_warning-binding-inspector-to-a-public-ipport-combination-is-insecure">security warning</a> below regarding the <code>host</code>
parameter usage.</p>
<h4><code>--inspect-publish-uid=stderr,http</code><span><a class="mark" href="#all_cli_--inspect-publish-uidstderrhttp" id="all_cli_--inspect-publish-uidstderrhttp">#</a></span><a aria-hidden="true" class="legacy" id="cli_inspect_publish_uid_stderr_http"></a></h4>
<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>
<h4><code>--inspect-wait[=[host:]port]</code><span><a class="mark" href="#all_cli_--inspect-waithostport" id="all_cli_--inspect-waithostport">#</a></span><a aria-hidden="true" class="legacy" id="cli_inspect_wait_host_port"></a></h4>
<div class="api_metadata">
<span>Added in: v20.15.0</span>
</div>
<p>Activate inspector on <code>host:port</code> and wait for debugger to be attached.
Default <code>host:port</code> is <code>127.0.0.1:9229</code>. If port <code>0</code> is specified,
a random available port will be used.</p>
<p>See <a href="#all_debugger_v8-inspector-integration-for-nodejs">V8 Inspector integration for Node.js</a> for further explanation on Node.js debugger.</p>
<h4><code>-i</code>, <code>--interactive</code><span><a class="mark" href="#all_cli_-i---interactive" id="all_cli_-i---interactive">#</a></span><a aria-hidden="true" class="legacy" id="cli_i_interactive"></a></h4>
<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>
<h4><code>--jitless</code><span><a class="mark" href="#all_cli_--jitless" id="all_cli_--jitless">#</a></span><a aria-hidden="true" class="legacy" id="cli_jitless"></a></h4>
<div class="api_metadata">
<span>Added in: v12.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental. This flag is inherited from V8 and is subject to
change upstream.</div><p></p>
<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>
<h4><code>--max-http-header-size=size</code><span><a class="mark" href="#all_cli_--max-http-header-sizesize" id="all_cli_--max-http-header-sizesize">#</a></span><a aria-hidden="true" class="legacy" id="cli_max_http_header_size_size"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.13.0</td>
<td><p>Change maximum default size of HTTP headers from 8 KiB to 16 KiB.</p></td></tr>
<tr><td>v11.6.0, v10.15.0</td>
<td><p><span>Added in: v11.6.0, v10.15.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Specify the maximum size, in bytes, of HTTP headers. Defaults to 16 KiB.</p>
<h4><code>--napi-modules</code><span><a class="mark" href="#all_cli_--napi-modules" id="all_cli_--napi-modules">#</a></span><a aria-hidden="true" class="legacy" id="cli_napi_modules"></a></h4>
<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>
<h4><code>--network-family-autoselection-attempt-timeout</code><span><a class="mark" href="#all_cli_--network-family-autoselection-attempt-timeout" id="all_cli_--network-family-autoselection-attempt-timeout">#</a></span><a aria-hidden="true" class="legacy" id="cli_network_family_autoselection_attempt_timeout"></a></h4>
<div class="api_metadata">
<span>Added in: v20.13.0</span>
</div>
<p>Sets the default value for the network family autoselection attempt timeout.
For more information, see <a href="#all_net_netgetdefaultautoselectfamilyattempttimeout"><code>net.getDefaultAutoSelectFamilyAttemptTimeout()</code></a>.</p>
<h4><code>--no-addons</code><span><a class="mark" href="#all_cli_--no-addons" id="all_cli_--no-addons">#</a></span><a aria-hidden="true" class="legacy" id="cli_no_addons"></a></h4>
<div class="api_metadata">
<span>Added in: v16.10.0, v14.19.0</span>
</div>
<p>Disable the <code>node-addons</code> exports condition as well as disable loading
native addons. When <code>--no-addons</code> is specified, calling <code>process.dlopen</code> or
requiring a native C++ addon will fail and throw an exception.</p>
<h4><code>--no-deprecation</code><span><a class="mark" href="#all_cli_--no-deprecation" id="all_cli_--no-deprecation">#</a></span><a aria-hidden="true" class="legacy" id="cli_no_deprecation"></a></h4>
<div class="api_metadata">
<span>Added in: v0.8.0</span>
</div>
<p>Silence deprecation warnings.</p>
<h4><code>--no-experimental-fetch</code><span><a class="mark" href="#all_cli_--no-experimental-fetch" id="all_cli_--no-experimental-fetch">#</a></span><a aria-hidden="true" class="legacy" id="cli_no_experimental_fetch"></a></h4>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<p>Disable experimental support for the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API">Fetch API</a>.</p>
<h4><code>--no-experimental-global-customevent</code><span><a class="mark" href="#all_cli_--no-experimental-global-customevent" id="all_cli_--no-experimental-global-customevent">#</a></span><a aria-hidden="true" class="legacy" id="cli_no_experimental_global_customevent"></a></h4>
<div class="api_metadata">
<span>Added in: v19.0.0</span>
</div>
<p>Disable exposition of <a href="https://dom.spec.whatwg.org/#customevent">CustomEvent Web API</a> on the global scope.</p>
<h4><code>--no-experimental-global-webcrypto</code><span><a class="mark" href="#all_cli_--no-experimental-global-webcrypto" id="all_cli_--no-experimental-global-webcrypto">#</a></span><a aria-hidden="true" class="legacy" id="cli_no_experimental_global_webcrypto"></a></h4>
<div class="api_metadata">
<span>Added in: v19.0.0</span>
</div>
<p>Disable exposition of <a href="webcrypto.html">Web Crypto API</a> on the global scope.</p>
<h4><code>--no-experimental-repl-await</code><span><a class="mark" href="#all_cli_--no-experimental-repl-await" id="all_cli_--no-experimental-repl-await">#</a></span><a aria-hidden="true" class="legacy" id="cli_no_experimental_repl_await"></a></h4>
<div class="api_metadata">
<span>Added in: v16.6.0</span>
</div>
<p>Use this flag to disable top-level await in REPL.</p>
<h4><code>--no-extra-info-on-fatal-exception</code><span><a class="mark" href="#all_cli_--no-extra-info-on-fatal-exception" id="all_cli_--no-extra-info-on-fatal-exception">#</a></span><a aria-hidden="true" class="legacy" id="cli_no_extra_info_on_fatal_exception"></a></h4>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<p>Hide extra information on fatal exception that causes exit.</p>
<h4><code>--no-force-async-hooks-checks</code><span><a class="mark" href="#all_cli_--no-force-async-hooks-checks" id="all_cli_--no-force-async-hooks-checks">#</a></span><a aria-hidden="true" class="legacy" id="cli_no_force_async_hooks_checks"></a></h4>
<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>
<h4><code>--no-global-search-paths</code><span><a class="mark" href="#all_cli_--no-global-search-paths" id="all_cli_--no-global-search-paths">#</a></span><a aria-hidden="true" class="legacy" id="cli_no_global_search_paths"></a></h4>
<div class="api_metadata">
<span>Added in: v16.10.0</span>
</div>
<p>Do not search modules from global paths like <code>$HOME/.node_modules</code> and
<code>$NODE_PATH</code>.</p>
<h4><code>--no-network-family-autoselection</code><span><a class="mark" href="#all_cli_--no-network-family-autoselection" id="all_cli_--no-network-family-autoselection">#</a></span><a aria-hidden="true" class="legacy" id="cli_no_network_family_autoselection"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>The flag was renamed from <code>--no-enable-network-family-autoselection</code> to <code>--no-network-family-autoselection</code>. The old name can still work as an alias.</p></td></tr>
<tr><td>v19.4.0</td>
<td><p><span>Added in: v19.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Disables the family autoselection algorithm unless connection options explicitly
enables it.</p>
<h4><code>--no-warnings</code><span><a class="mark" href="#all_cli_--no-warnings" id="all_cli_--no-warnings">#</a></span><a aria-hidden="true" class="legacy" id="cli_no_warnings"></a></h4>
<div class="api_metadata">
<span>Added in: v6.0.0</span>
</div>
<p>Silence all process warnings (including deprecations).</p>
<h4><code>--node-memory-debug</code><span><a class="mark" href="#all_cli_--node-memory-debug" id="all_cli_--node-memory-debug">#</a></span><a aria-hidden="true" class="legacy" id="cli_node_memory_debug"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0, v14.18.0</span>
</div>
<p>Enable extra debug checks for memory leaks in Node.js internals. This is
usually only useful for developers debugging Node.js itself.</p>
<h4><code>--openssl-config=file</code><span><a class="mark" href="#all_cli_--openssl-configfile" id="all_cli_--openssl-configfile">#</a></span><a aria-hidden="true" class="legacy" id="cli_openssl_config_file"></a></h4>
<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
against FIPS-enabled OpenSSL.</p>
<h4><code>--openssl-legacy-provider</code><span><a class="mark" href="#all_cli_--openssl-legacy-provider" id="all_cli_--openssl-legacy-provider">#</a></span><a aria-hidden="true" class="legacy" id="cli_openssl_legacy_provider"></a></h4>
<div class="api_metadata">
<span>Added in: v17.0.0, v16.17.0</span>
</div>
<p>Enable OpenSSL 3.0 legacy provider. For more information please see
<a href="https://www.openssl.org/docs/man3.0/man7/OSSL_PROVIDER-legacy.html">OSSL_PROVIDER-legacy</a>.</p>
<h4><code>--openssl-shared-config</code><span><a class="mark" href="#all_cli_--openssl-shared-config" id="all_cli_--openssl-shared-config">#</a></span><a aria-hidden="true" class="legacy" id="cli_openssl_shared_config"></a></h4>
<div class="api_metadata">
<span>Added in: v18.5.0, v16.17.0, v14.21.0</span>
</div>
<p>Enable OpenSSL default configuration section, <code>openssl_conf</code> to be read from
the OpenSSL configuration file. The default configuration file is named
<code>openssl.cnf</code> but this can be changed using the environment variable
<code>OPENSSL_CONF</code>, or by using the command line option <code>--openssl-config</code>.
The location of the default OpenSSL configuration file depends on how OpenSSL
is being linked to Node.js. Sharing the OpenSSL configuration may have unwanted
implications and it is recommended to use a configuration section specific to
Node.js which is <code>nodejs_conf</code> and is default when this option is not used.</p>
<h4><code>--pending-deprecation</code><span><a class="mark" href="#all_cli_--pending-deprecation" id="all_cli_--pending-deprecation">#</a></span><a aria-hidden="true" class="legacy" id="cli_pending_deprecation"></a></h4>
<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>
<h4><code>--policy-integrity=sri</code><span><a class="mark" href="#all_cli_--policy-integritysri" id="all_cli_--policy-integritysri">#</a></span><a aria-hidden="true" class="legacy" id="cli_policy_integrity_sri"></a></h4>
<div class="api_metadata">
<span>Added in: v12.7.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Will be removed shortly.</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>
<h4><code>--preserve-symlinks</code><span><a class="mark" href="#all_cli_--preserve-symlinks" id="all_cli_--preserve-symlinks">#</a></span><a aria-hidden="true" class="legacy" id="cli_preserve_symlinks"></a></h4>
<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> <button class="copy-button">copy</button></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>
<h4><code>--preserve-symlinks-main</code><span><a class="mark" href="#all_cli_--preserve-symlinks-main" id="all_cli_--preserve-symlinks-main">#</a></span><a aria-hidden="true" class="legacy" id="cli_preserve_symlinks_main"></a></h4>
<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>; use
<code>--preserve-symlinks-main</code> in addition to
<code>--preserve-symlinks</code> when it is not desirable to follow symlinks before
resolving relative paths.</p>
<p>See <a href="#all_cli_--preserve-symlinks"><code>--preserve-symlinks</code></a> for more information.</p>
<h4><code>-p</code>, <code>--print "script"</code><span><a class="mark" href="#all_cli_-p---print-script" id="all_cli_-p---print-script">#</a></span><a aria-hidden="true" class="legacy" id="cli_p_print_script"></a></h4>
<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>
<h4><code>--experimental-print-required-tla</code><span><a class="mark" href="#all_cli_--experimental-print-required-tla" id="all_cli_--experimental-print-required-tla">#</a></span><a aria-hidden="true" class="legacy" id="cli_experimental_print_required_tla"></a></h4>
<div class="api_metadata">
<span>Added in: v20.17.0</span>
</div>
<p>This flag is only useful when <code>--experimental-require-module</code> is enabled.</p>
<p>If the ES module being <code>require()</code>'d contains top-level await, this flag
allows Node.js to evaluate the module, try to locate the
top-level awaits, and print their location to help users find them.</p>
<h4><code>--prof</code><span><a class="mark" href="#all_cli_--prof" id="all_cli_--prof">#</a></span><a aria-hidden="true" class="legacy" id="cli_prof"></a></h4>
<div class="api_metadata">
<span>Added in: v2.0.0</span>
</div>
<p>Generate V8 profiler output.</p>
<h4><code>--prof-process</code><span><a class="mark" href="#all_cli_--prof-process" id="all_cli_--prof-process">#</a></span><a aria-hidden="true" class="legacy" id="cli_prof_process"></a></h4>
<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>
<h4><code>--redirect-warnings=file</code><span><a class="mark" href="#all_cli_--redirect-warningsfile" id="all_cli_--redirect-warningsfile">#</a></span><a aria-hidden="true" class="legacy" id="cli_redirect_warnings_file"></a></h4>
<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>
<p>The <code>file</code> name may be an absolute path. If it is not, the default directory it
will be written to is controlled by the
<a href="#all_cli_--diagnostic-dirdirectory"><code>--diagnostic-dir</code></a> command-line option.</p>
<h4><code>--report-compact</code><span><a class="mark" href="#all_cli_--report-compact" id="all_cli_--report-compact">#</a></span><a aria-hidden="true" class="legacy" id="cli_report_compact"></a></h4>
<div class="api_metadata">
<span>Added in: v13.12.0, 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>
<h4><code>--report-dir=directory</code>, <code>report-directory=directory</code><span><a class="mark" href="#all_cli_--report-dirdirectory-report-directorydirectory" id="all_cli_--report-dirdirectory-report-directorydirectory">#</a></span><a aria-hidden="true" class="legacy" id="cli_report_dir_directory_report_directory_directory"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.12.0, v12.17.0</td>
<td><p>This option is no longer 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>
<h4><code>--report-filename=filename</code><span><a class="mark" href="#all_cli_--report-filenamefilename" id="all_cli_--report-filenamefilename">#</a></span><a aria-hidden="true" class="legacy" id="cli_report_filename_filename"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.12.0, v12.17.0</td>
<td><p>This option is no longer 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>
<p>If the filename is set to <code>'stdout'</code> or <code>'stderr'</code>, the report is written to
the stdout or stderr of the process respectively.</p>
<h4><code>--report-on-fatalerror</code><span><a class="mark" href="#all_cli_--report-on-fatalerror" id="all_cli_--report-on-fatalerror">#</a></span><a aria-hidden="true" class="legacy" id="cli_report_on_fatalerror"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.0.0, v13.14.0, v12.17.0</td>
<td><p>This option is no longer 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>
<h4><code>--report-on-signal</code><span><a class="mark" href="#all_cli_--report-on-signal" id="all_cli_--report-on-signal">#</a></span><a aria-hidden="true" class="legacy" id="cli_report_on_signal"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.12.0, v12.17.0</td>
<td><p>This option is no longer 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>
<h4><code>--report-signal=signal</code><span><a class="mark" href="#all_cli_--report-signalsignal" id="all_cli_--report-signalsignal">#</a></span><a aria-hidden="true" class="legacy" id="cli_report_signal_signal"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.12.0, v12.17.0</td>
<td><p>This option is no longer 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>
<h4><code>--report-uncaught-exception</code><span><a class="mark" href="#all_cli_--report-uncaught-exception" id="all_cli_--report-uncaught-exception">#</a></span><a aria-hidden="true" class="legacy" id="cli_report_uncaught_exception"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.8.0, v16.18.0</td>
<td><p>Report is not generated if the uncaught exception is handled.</p></td></tr>
<tr><td>v13.12.0, v12.17.0</td>
<td><p>This option is no longer 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 when the process exits due to an uncaught
exception. Useful when inspecting the JavaScript stack in conjunction with
native stack and other runtime environment data.</p>
<h4><code>--report-exclude-network</code><span><a class="mark" href="#all_cli_--report-exclude-network" id="all_cli_--report-exclude-network">#</a></span><a aria-hidden="true" class="legacy" id="cli_report_exclude_network"></a></h4>
<div class="api_metadata">
<span>Added in: v20.13.0</span>
</div>
<p>Exclude <code>header.networkInterfaces</code> from the diagnostic report. By default
this is not set and the network interfaces are included.</p>
<h4><code>-r</code>, <code>--require module</code><span><a class="mark" href="#all_cli_-r---require-module" id="all_cli_-r---require-module">#</a></span><a aria-hidden="true" class="legacy" id="cli_r_require_module"></a></h4>
<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>
<p>Only CommonJS modules are supported.
Use <a href="#all_cli_--importmodule"><code>--import</code></a> to preload an <a href="#all_esm_modules-ecmascript-modules">ECMAScript module</a>.
Modules preloaded with <code>--require</code> will run before modules preloaded with <code>--import</code>.</p>
<h4><code>--secure-heap=n</code><span><a class="mark" href="#all_cli_--secure-heapn" id="all_cli_--secure-heapn">#</a></span><a aria-hidden="true" class="legacy" id="cli_secure_heap_n"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<p>Initializes an OpenSSL secure heap of <code>n</code> bytes. When initialized, the
secure heap is used for selected types of allocations within OpenSSL
during key generation and other operations. This is useful, for instance,
to prevent sensitive information from leaking due to pointer overruns
or underruns.</p>
<p>The secure heap is a fixed size and cannot be resized at runtime so,
if used, it is important to select a large enough heap to cover all
application uses.</p>
<p>The heap size given must be a power of two. Any value less than 2
will disable the secure heap.</p>
<p>The secure heap is disabled by default.</p>
<p>The secure heap is not available on Windows.</p>
<p>See <a href="https://www.openssl.org/docs/man3.0/man3/CRYPTO_secure_malloc_init.html"><code>CRYPTO_secure_malloc_init</code></a> for more details.</p>
<h4><code>--secure-heap-min=n</code><span><a class="mark" href="#all_cli_--secure-heap-minn" id="all_cli_--secure-heap-minn">#</a></span><a aria-hidden="true" class="legacy" id="cli_secure_heap_min_n"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<p>When using <code>--secure-heap</code>, the <code>--secure-heap-min</code> flag specifies the
minimum allocation from the secure heap. The minimum value is <code>2</code>.
The maximum value is the lesser of <code>--secure-heap</code> or <code>2147483647</code>.
The value given must be a power of two.</p>
<h4><code>--snapshot-blob=path</code><span><a class="mark" href="#all_cli_--snapshot-blobpath" id="all_cli_--snapshot-blobpath">#</a></span><a aria-hidden="true" class="legacy" id="cli_snapshot_blob_path"></a></h4>
<div class="api_metadata">
<span>Added in: v18.8.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>When used with <code>--build-snapshot</code>, <code>--snapshot-blob</code> specifies the path
where the generated snapshot blob is written to. If not specified, the
generated blob is written to <code>snapshot.blob</code> in the current working directory.</p>
<p>When used without <code>--build-snapshot</code>, <code>--snapshot-blob</code> specifies the
path to the blob that is used to restore the application state.</p>
<p>When loading a snapshot, Node.js checks that:</p>
<ol>
<li>The version, architecture, and platform of the running Node.js binary
are exactly the same as that of the binary that generates the snapshot.</li>
<li>The V8 flags and CPU features are compatible with that of the binary
that generates the snapshot.</li>
</ol>
<p>If they don't match, Node.js refuses to load the snapshot and exits with
status code 1.</p>
<h4><code>--test</code><span><a class="mark" href="#all_cli_--test" id="all_cli_--test">#</a></span><a aria-hidden="true" class="legacy" id="cli_test"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>The test runner is now stable.</p></td></tr>
<tr><td>v19.2.0, v18.13.0</td>
<td><p>Test runner now supports running in watch mode.</p></td></tr>
<tr><td>v18.1.0, v16.17.0</td>
<td><p><span>Added in: v18.1.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Starts the Node.js command line test runner. This flag cannot be combined with
<code>--watch-path</code>, <code>--check</code>, <code>--eval</code>, <code>--interactive</code>, or the inspector.
See the documentation on <a href="#all_test_running-tests-from-the-command-line">running tests from the command line</a>
for more details.</p>
<h4><code>--test-concurrency</code><span><a class="mark" href="#all_cli_--test-concurrency" id="all_cli_--test-concurrency">#</a></span><a aria-hidden="true" class="legacy" id="cli_test_concurrency"></a></h4>
<div class="api_metadata">
<span>Added in: v20.10.0</span>
</div>
<p>The maximum number of test files that the test runner CLI will execute
concurrently. The default value is <code>os.availableParallelism() - 1</code>.</p>
<h4><code>--test-coverage-exclude</code><span><a class="mark" href="#all_cli_--test-coverage-exclude" id="all_cli_--test-coverage-exclude">#</a></span><a aria-hidden="true" class="legacy" id="cli_test_coverage_exclude"></a></h4>
<div class="api_metadata">
<span>Added in: v22.5.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Excludes specific files from code coverage using a glob pattern, which can match
both absolute and relative file paths.</p>
<p>This option may be specified multiple times to exclude multiple glob patterns.</p>
<p>If both <code>--test-coverage-exclude</code> and <code>--test-coverage-include</code> are provided,
files must meet <strong>both</strong> criteria to be included in the coverage report.</p>
<h4><code>--test-coverage-include</code><span><a class="mark" href="#all_cli_--test-coverage-include" id="all_cli_--test-coverage-include">#</a></span><a aria-hidden="true" class="legacy" id="cli_test_coverage_include"></a></h4>
<div class="api_metadata">
<span>Added in: v22.5.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Includes specific files in code coverage using a glob pattern, which can match
both absolute and relative file paths.</p>
<p>This option may be specified multiple times to include multiple glob patterns.</p>
<p>If both <code>--test-coverage-exclude</code> and <code>--test-coverage-include</code> are provided,
files must meet <strong>both</strong> criteria to be included in the coverage report.</p>
<h4><code>--test-force-exit</code><span><a class="mark" href="#all_cli_--test-force-exit" id="all_cli_--test-force-exit">#</a></span><a aria-hidden="true" class="legacy" id="cli_test_force_exit"></a></h4>
<div class="api_metadata">
<span>Added in: v20.14.0</span>
</div>
<p>Configures the test runner to exit the process once all known tests have
finished executing even if the event loop would otherwise remain active.</p>
<h4><code>--test-name-pattern</code><span><a class="mark" href="#all_cli_--test-name-pattern" id="all_cli_--test-name-pattern">#</a></span><a aria-hidden="true" class="legacy" id="cli_test_name_pattern"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>The test runner is now stable.</p></td></tr>
<tr><td>v18.11.0</td>
<td><p><span>Added in: v18.11.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>A regular expression that configures the test runner to only execute tests
whose name matches the provided pattern. See the documentation on
<a href="#all_test_filtering-tests-by-name">filtering tests by name</a> for more details.</p>
<h4><code>--test-only</code><span><a class="mark" href="#all_cli_--test-only" id="all_cli_--test-only">#</a></span><a aria-hidden="true" class="legacy" id="cli_test_only"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>The test runner is now stable.</p></td></tr>
<tr><td>v18.0.0, v16.17.0</td>
<td><p><span>Added in: v18.0.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Configures the test runner to only execute top level tests that have the <code>only</code>
option set.</p>
<h4><code>--test-reporter</code><span><a class="mark" href="#all_cli_--test-reporter" id="all_cli_--test-reporter">#</a></span><a aria-hidden="true" class="legacy" id="cli_test_reporter"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>The test runner is now stable.</p></td></tr>
<tr><td>v19.6.0, v18.15.0</td>
<td><p><span>Added in: v19.6.0, v18.15.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>A test reporter to use when running tests. See the documentation on
<a href="#all_test_test-reporters">test reporters</a> for more details.</p>
<h4><code>--test-reporter-destination</code><span><a class="mark" href="#all_cli_--test-reporter-destination" id="all_cli_--test-reporter-destination">#</a></span><a aria-hidden="true" class="legacy" id="cli_test_reporter_destination"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>The test runner is now stable.</p></td></tr>
<tr><td>v19.6.0, v18.15.0</td>
<td><p><span>Added in: v19.6.0, v18.15.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>The destination for the corresponding test reporter. See the documentation on
<a href="#all_test_test-reporters">test reporters</a> for more details.</p>
<h4><code>--test-shard</code><span><a class="mark" href="#all_cli_--test-shard" id="all_cli_--test-shard">#</a></span><a aria-hidden="true" class="legacy" id="cli_test_shard"></a></h4>
<div class="api_metadata">
<span>Added in: v20.5.0</span>
</div>
<p>Test suite shard to execute in a format of <code>&#x3C;index>/&#x3C;total></code>, where</p>
<p><code>index</code> is a positive integer, index of divided parts
<code>total</code> is a positive integer, total of divided part
This command will divide all tests files into <code>total</code> equal parts,
and will run only those that happen to be in an <code>index</code> part.</p>
<p>For example, to split your tests suite into three parts, use this:</p>
<pre><code class="language-bash">node --<span class="hljs-built_in">test</span> --test-shard=1/3
node --<span class="hljs-built_in">test</span> --test-shard=2/3
node --<span class="hljs-built_in">test</span> --test-shard=3/3</code> <button class="copy-button">copy</button></pre>
<h4><code>--test-timeout</code><span><a class="mark" href="#all_cli_--test-timeout" id="all_cli_--test-timeout">#</a></span><a aria-hidden="true" class="legacy" id="cli_test_timeout"></a></h4>
<div class="api_metadata">
<span>Added in: v20.11.0</span>
</div>
<p>A number of milliseconds the test execution will fail after. If unspecified,
subtests inherit this value from their parent. The default value is <code>Infinity</code>.</p>
<h4><code>--throw-deprecation</code><span><a class="mark" href="#all_cli_--throw-deprecation" id="all_cli_--throw-deprecation">#</a></span><a aria-hidden="true" class="legacy" id="cli_throw_deprecation"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.14</span>
</div>
<p>Throw errors for deprecations.</p>
<h4><code>--title=title</code><span><a class="mark" href="#all_cli_--titletitle" id="all_cli_--titletitle">#</a></span><a aria-hidden="true" class="legacy" id="cli_title_title"></a></h4>
<div class="api_metadata">
<span>Added in: v10.7.0</span>
</div>
<p>Set <code>process.title</code> on startup.</p>
<h4><code>--tls-cipher-list=list</code><span><a class="mark" href="#all_cli_--tls-cipher-listlist" id="all_cli_--tls-cipher-listlist">#</a></span><a aria-hidden="true" class="legacy" id="cli_tls_cipher_list_list"></a></h4>
<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>
<h4><code>--tls-keylog=file</code><span><a class="mark" href="#all_cli_--tls-keylogfile" id="all_cli_--tls-keylogfile">#</a></span><a aria-hidden="true" class="legacy" id="cli_tls_keylog_file"></a></h4>
<div class="api_metadata">
<span>Added in: v13.2.0, 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>
<h4><code>--tls-max-v1.2</code><span><a class="mark" href="#all_cli_--tls-max-v12" id="all_cli_--tls-max-v12">#</a></span><a aria-hidden="true" class="legacy" id="cli_tls_max_v1_2"></a></h4>
<div class="api_metadata">
<span>Added in: v12.0.0, v10.20.0</span>
</div>
<p>Set <a href="#all_tls_tlsdefault_max_version"><code>tls.DEFAULT_MAX_VERSION</code></a> to 'TLSv1.2'. Use to disable support for
TLSv1.3.</p>
<h4><code>--tls-max-v1.3</code><span><a class="mark" href="#all_cli_--tls-max-v13" id="all_cli_--tls-max-v13">#</a></span><a aria-hidden="true" class="legacy" id="cli_tls_max_v1_3"></a></h4>
<div class="api_metadata">
<span>Added in: v12.0.0</span>
</div>
<p>Set default <a href="#all_tls_tlsdefault_max_version"><code>tls.DEFAULT_MAX_VERSION</code></a> to 'TLSv1.3'. Use to enable support
for TLSv1.3.</p>
<h4><code>--tls-min-v1.0</code><span><a class="mark" href="#all_cli_--tls-min-v10" id="all_cli_--tls-min-v10">#</a></span><a aria-hidden="true" class="legacy" id="cli_tls_min_v1_0"></a></h4>
<div class="api_metadata">
<span>Added in: v12.0.0, v10.20.0</span>
</div>
<p>Set default <a href="#all_tls_tlsdefault_min_version"><code>tls.DEFAULT_MIN_VERSION</code></a> to 'TLSv1'. Use for compatibility with
old TLS clients or servers.</p>
<h4><code>--tls-min-v1.1</code><span><a class="mark" href="#all_cli_--tls-min-v11" id="all_cli_--tls-min-v11">#</a></span><a aria-hidden="true" class="legacy" id="cli_tls_min_v1_1"></a></h4>
<div class="api_metadata">
<span>Added in: v12.0.0, v10.20.0</span>
</div>
<p>Set default <a href="#all_tls_tlsdefault_min_version"><code>tls.DEFAULT_MIN_VERSION</code></a> to 'TLSv1.1'. Use for compatibility
with old TLS clients or servers.</p>
<h4><code>--tls-min-v1.2</code><span><a class="mark" href="#all_cli_--tls-min-v12" id="all_cli_--tls-min-v12">#</a></span><a aria-hidden="true" class="legacy" id="cli_tls_min_v1_2"></a></h4>
<div class="api_metadata">
<span>Added in: v12.2.0, v10.20.0</span>
</div>
<p>Set default <a href="#all_tls_tlsdefault_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>
<h4><code>--tls-min-v1.3</code><span><a class="mark" href="#all_cli_--tls-min-v13" id="all_cli_--tls-min-v13">#</a></span><a aria-hidden="true" class="legacy" id="cli_tls_min_v1_3"></a></h4>
<div class="api_metadata">
<span>Added in: v12.0.0</span>
</div>
<p>Set default <a href="#all_tls_tlsdefault_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>
<h4><code>--trace-atomics-wait</code><span><a class="mark" href="#all_cli_--trace-atomics-wait" id="all_cli_--trace-atomics-wait">#</a></span><a aria-hidden="true" class="legacy" id="cli_trace_atomics_wait"></a></h4>
<div class="api_metadata">
<span>Added in: v14.3.0</span><span>Deprecated since: v18.8.0, v16.18.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated</div><p></p>
<p>Print short summaries of calls to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Atomics/wait"><code>Atomics.wait()</code></a> to stderr.
The output could look like this:</p>
<pre><code class="language-text">(node:15701) [Thread 0] Atomics.wait(&#x26;lt;address> + 0, 1, inf) started
(node:15701) [Thread 0] Atomics.wait(&#x26;lt;address> + 0, 1, inf) did not wait because the values mismatched
(node:15701) [Thread 0] Atomics.wait(&#x26;lt;address> + 0, 0, 10) started
(node:15701) [Thread 0] Atomics.wait(&#x26;lt;address> + 0, 0, 10) timed out
(node:15701) [Thread 0] Atomics.wait(&#x26;lt;address> + 4, 0, inf) started
(node:15701) [Thread 1] Atomics.wait(&#x26;lt;address> + 4, -1, inf) started
(node:15701) [Thread 0] Atomics.wait(&#x26;lt;address> + 4, 0, inf) was woken up by another thread
(node:15701) [Thread 1] Atomics.wait(&#x26;lt;address> + 4, -1, inf) was woken up by another thread</code> <button class="copy-button">copy</button></pre>
<p>The fields here correspond to:</p>
<ul>
<li>The thread id as given by <a href="#all_worker_threads_workerthreadid"><code>worker_threads.threadId</code></a></li>
<li>The base address of the <code>SharedArrayBuffer</code> in question, as well as the
byte offset corresponding to the index passed to <code>Atomics.wait()</code></li>
<li>The expected value that was passed to <code>Atomics.wait()</code></li>
<li>The timeout passed to <code>Atomics.wait</code></li>
</ul>
<h4><code>--trace-deprecation</code><span><a class="mark" href="#all_cli_--trace-deprecation" id="all_cli_--trace-deprecation">#</a></span><a aria-hidden="true" class="legacy" id="cli_trace_deprecation"></a></h4>
<div class="api_metadata">
<span>Added in: v0.8.0</span>
</div>
<p>Print stack traces for deprecations.</p>
<h4><code>--trace-event-categories</code><span><a class="mark" href="#all_cli_--trace-event-categories" id="all_cli_--trace-event-categories">#</a></span><a aria-hidden="true" class="legacy" id="cli_trace_event_categories"></a></h4>
<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>
<h4><code>--trace-event-file-pattern</code><span><a class="mark" href="#all_cli_--trace-event-file-pattern" id="all_cli_--trace-event-file-pattern">#</a></span><a aria-hidden="true" class="legacy" id="cli_trace_event_file_pattern"></a></h4>
<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>
<h4><code>--trace-events-enabled</code><span><a class="mark" href="#all_cli_--trace-events-enabled" id="all_cli_--trace-events-enabled">#</a></span><a aria-hidden="true" class="legacy" id="cli_trace_events_enabled"></a></h4>
<div class="api_metadata">
<span>Added in: v7.7.0</span>
</div>
<p>Enables the collection of trace event tracing information.</p>
<h4><code>--trace-exit</code><span><a class="mark" href="#all_cli_--trace-exit" id="all_cli_--trace-exit">#</a></span><a aria-hidden="true" class="legacy" id="cli_trace_exit"></a></h4>
<div class="api_metadata">
<span>Added in: v13.5.0, v12.16.0</span>
</div>
<p>Prints a stack trace whenever an environment is exited proactively,
i.e. invoking <code>process.exit()</code>.</p>
<h4><code>--trace-sigint</code><span><a class="mark" href="#all_cli_--trace-sigint" id="all_cli_--trace-sigint">#</a></span><a aria-hidden="true" class="legacy" id="cli_trace_sigint"></a></h4>
<div class="api_metadata">
<span>Added in: v13.9.0, v12.17.0</span>
</div>
<p>Prints a stack trace on SIGINT.</p>
<h4><code>--trace-sync-io</code><span><a class="mark" href="#all_cli_--trace-sync-io" id="all_cli_--trace-sync-io">#</a></span><a aria-hidden="true" class="legacy" id="cli_trace_sync_io"></a></h4>
<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>
<h4><code>--trace-tls</code><span><a class="mark" href="#all_cli_--trace-tls" id="all_cli_--trace-tls">#</a></span><a aria-hidden="true" class="legacy" id="cli_trace_tls"></a></h4>
<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>
<h4><code>--trace-uncaught</code><span><a class="mark" href="#all_cli_--trace-uncaught" id="all_cli_--trace-uncaught">#</a></span><a aria-hidden="true" class="legacy" id="cli_trace_uncaught"></a></h4>
<div class="api_metadata">
<span>Added in: v13.1.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>
<h4><code>--trace-warnings</code><span><a class="mark" href="#all_cli_--trace-warnings" id="all_cli_--trace-warnings">#</a></span><a aria-hidden="true" class="legacy" id="cli_trace_warnings"></a></h4>
<div class="api_metadata">
<span>Added in: v6.0.0</span>
</div>
<p>Print stack traces for process warnings (including deprecations).</p>
<h4><code>--track-heap-objects</code><span><a class="mark" href="#all_cli_--track-heap-objects" id="all_cli_--track-heap-objects">#</a></span><a aria-hidden="true" class="legacy" id="cli_track_heap_objects"></a></h4>
<div class="api_metadata">
<span>Added in: v2.4.0</span>
</div>
<p>Track heap object allocations for heap snapshots.</p>
<h4><code>--unhandled-rejections=mode</code><span><a class="mark" href="#all_cli_--unhandled-rejectionsmode" id="all_cli_--unhandled-rejectionsmode">#</a></span><a aria-hidden="true" class="legacy" id="cli_unhandled_rejections_mode"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>Changed default mode to <code>throw</code>. Previously, a warning was emitted.</p></td></tr>
<tr><td>v12.0.0, v10.17.0</td>
<td><p><span>Added in: v12.0.0, v10.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Using this flag allows to change what should happen when an unhandled rejection
occurs. One of the following modes can be chosen:</p>
<ul>
<li><code>throw</code>: Emit <a href="#all_process_event-unhandledrejection"><code>unhandledRejection</code></a>. If this hook is not set, raise the
unhandled rejection as an uncaught exception. This is the default.</li>
<li><code>strict</code>: Raise the unhandled rejection as an uncaught exception. If the
exception is handled, <a href="#all_process_event-unhandledrejection"><code>unhandledRejection</code></a> is emitted.</li>
<li><code>warn</code>: Always trigger a warning, no matter if the <a href="#all_process_event-unhandledrejection"><code>unhandledRejection</code></a>
hook is set or not but do not print the deprecation warning.</li>
<li><code>warn-with-error-code</code>: Emit <a href="#all_process_event-unhandledrejection"><code>unhandledRejection</code></a>. If this hook is not
set, trigger a warning, and set the process exit code to 1.</li>
<li><code>none</code>: Silence all warnings.</li>
</ul>
<p>If a rejection happens during the command line entry point's ES module static
loading phase, it will always raise it as an uncaught exception.</p>
<h4><code>--use-bundled-ca</code>, <code>--use-openssl-ca</code><span><a class="mark" href="#all_cli_--use-bundled-ca---use-openssl-ca" id="all_cli_--use-bundled-ca---use-openssl-ca">#</a></span><a aria-hidden="true" class="legacy" id="cli_use_bundled_ca_use_openssl_ca"></a></h4>
<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>
<h4><code>--use-largepages=mode</code><span><a class="mark" href="#all_cli_--use-largepagesmode" id="all_cli_--use-largepagesmode">#</a></span><a aria-hidden="true" class="legacy" id="cli_use_largepages_mode"></a></h4>
<div class="api_metadata">
<span>Added in: v13.6.0, 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>
<h4><code>--v8-options</code><span><a class="mark" href="#all_cli_--v8-options" id="all_cli_--v8-options">#</a></span><a aria-hidden="true" class="legacy" id="cli_v8_options"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.3</span>
</div>
<p>Print V8 command-line options.</p>
<h4><code>--v8-pool-size=num</code><span><a class="mark" href="#all_cli_--v8-pool-sizenum" id="all_cli_--v8-pool-sizenum">#</a></span><a aria-hidden="true" class="legacy" id="cli_v8_pool_size_num"></a></h4>
<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 Node.js will choose an appropriate size of the thread pool
based on an estimate of the amount of parallelism.</p>
<p>The amount of parallelism refers to the number of computations that can be
carried out simultaneously in a given machine. In general, it's the same as the
amount of CPUs, but it may diverge in environments such as VMs or containers.</p>
<h4><code>-v</code>, <code>--version</code><span><a class="mark" href="#all_cli_-v---version" id="all_cli_-v---version">#</a></span><a aria-hidden="true" class="legacy" id="cli_v_version"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.3</span>
</div>
<p>Print node's version.</p>
<h4><code>--watch</code><span><a class="mark" href="#all_cli_--watch" id="all_cli_--watch">#</a></span><a aria-hidden="true" class="legacy" id="cli_watch"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.13.0</td>
<td><p>Watch mode is now stable.</p></td></tr>
<tr><td>v19.2.0, v18.13.0</td>
<td><p>Test runner now supports running in watch mode.</p></td></tr>
<tr><td>v18.11.0, v16.19.0</td>
<td><p><span>Added in: v18.11.0, v16.19.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p>Starts Node.js in watch mode.
When in watch mode, changes in the watched files cause the Node.js process to
restart.
By default, watch mode will watch the entry point
and any required or imported module.
Use <code>--watch-path</code> to specify what paths to watch.</p>
<p>This flag cannot be combined with
<code>--check</code>, <code>--eval</code>, <code>--interactive</code>, or the REPL.</p>
<pre><code class="language-bash">node --watch index.js</code> <button class="copy-button">copy</button></pre>
<h4><code>--watch-path</code><span><a class="mark" href="#all_cli_--watch-path" id="all_cli_--watch-path">#</a></span><a aria-hidden="true" class="legacy" id="cli_watch_path"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.13.0</td>
<td><p>Watch mode is now stable.</p></td></tr>
<tr><td>v18.11.0, v16.19.0</td>
<td><p><span>Added in: v18.11.0, v16.19.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p>Starts Node.js in watch mode and specifies what paths to watch.
When in watch mode, changes in the watched paths cause the Node.js process to
restart.
This will turn off watching of required or imported modules, even when used in
combination with <code>--watch</code>.</p>
<p>This flag cannot be combined with
<code>--check</code>, <code>--eval</code>, <code>--interactive</code>, <code>--test</code>, or the REPL.</p>
<pre><code class="language-bash">node --watch-path=./src --watch-path=./tests index.js</code> <button class="copy-button">copy</button></pre>
<p>This option is only supported on macOS and Windows.
An <code>ERR_FEATURE_UNAVAILABLE_ON_PLATFORM</code> exception will be thrown
when the option is used on a platform that does not support it.</p>
<h4><code>--watch-preserve-output</code><span><a class="mark" href="#all_cli_--watch-preserve-output" id="all_cli_--watch-preserve-output">#</a></span><a aria-hidden="true" class="legacy" id="cli_watch_preserve_output"></a></h4>
<div class="api_metadata">
<span>Added in: v19.3.0, v18.13.0</span>
</div>
<p>Disable the clearing of the console when watch mode restarts the process.</p>
<pre><code class="language-bash">node --watch --watch-preserve-output test.js</code> <button class="copy-button">copy</button></pre>
<h4><code>--zero-fill-buffers</code><span><a class="mark" href="#all_cli_--zero-fill-buffers" id="all_cli_--zero-fill-buffers">#</a></span><a aria-hidden="true" class="legacy" id="cli_zero_fill_buffers"></a></h4>
<div class="api_metadata">
<span>Added in: v6.0.0</span>
</div>
<p>Automatically zero-fills all newly allocated <a href="#all_buffer_class-buffer"><code>Buffer</code></a> and <a href="#all_buffer_class-slowbuffer"><code>SlowBuffer</code></a>
instances.</p>
</section><section><h3>Environment variables<span><a class="mark" href="#all_cli_environment-variables" id="all_cli_environment-variables">#</a></span><a aria-hidden="true" class="legacy" id="cli_environment_variables"></a></h3>
<h4><code>FORCE_COLOR=[1, 2, 3]</code><span><a class="mark" href="#all_cli_force_color1-2-3" id="all_cli_force_color1-2-3">#</a></span><a aria-hidden="true" class="legacy" id="cli_force_color_1_2_3"></a></h4>
<p>The <code>FORCE_COLOR</code> environment variable is used to
enable ANSI colorized output. The value may be:</p>
<ul>
<li><code>1</code>, <code>true</code>, or the empty string <code>''</code> indicate 16-color support,</li>
<li><code>2</code> to indicate 256-color support, or</li>
<li><code>3</code> to indicate 16 million-color support.</li>
</ul>
<p>When <code>FORCE_COLOR</code> is used and set to a supported value, both the <code>NO_COLOR</code>,
and <code>NODE_DISABLE_COLORS</code> environment variables are ignored.</p>
<p>Any other value will result in colorized output being disabled.</p>
<h4><code>NO_COLOR=&#x3C;any></code><span><a class="mark" href="#all_cli_no_colorany" id="all_cli_no_colorany">#</a></span><a aria-hidden="true" class="legacy" id="cli_no_color_any"></a></h4>
<p><a href="https://no-color.org"><code>NO_COLOR</code></a>  is an alias for <code>NODE_DISABLE_COLORS</code>. The value of the
environment variable is arbitrary.</p>
<h4><code>NODE_DEBUG=module[,…]</code><span><a class="mark" href="#all_cli_node_debugmodule" id="all_cli_node_debugmodule">#</a></span><a aria-hidden="true" class="legacy" id="cli_node_debug_module"></a></h4>
<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>
<h4><code>NODE_DEBUG_NATIVE=module[,…]</code><span><a class="mark" href="#all_cli_node_debug_nativemodule" id="all_cli_node_debug_nativemodule">#</a></span><a aria-hidden="true" class="legacy" id="cli_node_debug_native_module"></a></h4>
<p><code>','</code>-separated list of core C++ modules that should print debug information.</p>
<h4><code>NODE_DISABLE_COLORS=1</code><span><a class="mark" href="#all_cli_node_disable_colors1" id="all_cli_node_disable_colors1">#</a></span><a aria-hidden="true" class="legacy" id="cli_node_disable_colors_1"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div>
<p>When set, colors will not be used in the REPL.</p>
<h4><code>NODE_EXTRA_CA_CERTS=file</code><span><a class="mark" href="#all_cli_node_extra_ca_certsfile" id="all_cli_node_extra_ca_certsfile">#</a></span><a aria-hidden="true" class="legacy" id="cli_node_extra_ca_certs_file"></a></h4>
<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="#all_process_processemitwarningwarning-options"><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>
<p>The <code>NODE_EXTRA_CA_CERTS</code> environment variable is only read when the Node.js
process is first launched. Changing the value at runtime using
<code>process.env.NODE_EXTRA_CA_CERTS</code> has no effect on the current process.</p>
<h4><code>NODE_ICU_DATA=file</code><span><a class="mark" href="#all_cli_node_icu_datafile" id="all_cli_node_icu_datafile">#</a></span><a aria-hidden="true" class="legacy" id="cli_node_icu_data_file"></a></h4>
<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>
<h4><code>NODE_NO_WARNINGS=1</code><span><a class="mark" href="#all_cli_node_no_warnings1" id="all_cli_node_no_warnings1">#</a></span><a aria-hidden="true" class="legacy" id="cli_node_no_warnings_1"></a></h4>
<div class="api_metadata">
<span>Added in: v6.11.0</span>
</div>
<p>When set to <code>1</code>, process warnings are silenced.</p>
<h4><code>NODE_OPTIONS=options...</code><span><a class="mark" href="#all_cli_node_optionsoptions" id="all_cli_node_optionsoptions">#</a></span><a aria-hidden="true" class="legacy" id="cli_node_options_options"></a></h4>
<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>If an option value contains a space, it can be escaped using double quotes:</p>
<pre><code class="language-bash">NODE_OPTIONS=<span class="hljs-string">'--require "./my path/file.js"'</span></code> <button class="copy-button">copy</button></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"><span class="hljs-comment"># The inspector will be available on port 5555</span>
NODE_OPTIONS=<span class="hljs-string">'--inspect=localhost:4444'</span> node --inspect=localhost:5555</code> <button class="copy-button">copy</button></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=<span class="hljs-string">'--require "./a.js"'</span> node --require <span class="hljs-string">"./b.js"</span>
<span class="hljs-comment"># is equivalent to:</span>
node --require <span class="hljs-string">"./a.js"</span> --require <span class="hljs-string">"./b.js"</span></code> <button class="copy-button">copy</button></pre>
<p>Node.js options that are allowed are in the following list. If an option
supports both --XX and --no-XX variants, they are both supported but only
one is included in the list below.</p>
<!-- node-options-node start -->
<ul>
<li><code>--allow-addons</code></li>
<li><code>--allow-child-process</code></li>
<li><code>--allow-fs-read</code></li>
<li><code>--allow-fs-write</code></li>
<li><code>--allow-wasi</code></li>
<li><code>--allow-worker</code></li>
<li><code>--conditions</code>, <code>-C</code></li>
<li><code>--diagnostic-dir</code></li>
<li><code>--disable-proto</code></li>
<li><code>--disable-warning</code></li>
<li><code>--disable-wasm-trap-handler</code></li>
<li><code>--dns-result-order</code></li>
<li><code>--enable-fips</code></li>
<li><code>--enable-network-family-autoselection</code></li>
<li><code>--enable-source-maps</code></li>
<li><code>--experimental-abortcontroller</code></li>
<li><code>--experimental-default-type</code></li>
<li><code>--experimental-detect-module</code></li>
<li><code>--experimental-eventsource</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-network-imports</code></li>
<li><code>--experimental-permission</code></li>
<li><code>--experimental-policy</code></li>
<li><code>--experimental-print-required-tla</code></li>
<li><code>--experimental-require-module</code></li>
<li><code>--experimental-shadow-realm</code></li>
<li><code>--experimental-specifier-resolution</code></li>
<li><code>--experimental-top-level-await</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>--experimental-websocket</code></li>
<li><code>--force-context-aware</code></li>
<li><code>--force-fips</code></li>
<li><code>--force-node-api-uncaught-exceptions-policy</code></li>
<li><code>--frozen-intrinsics</code></li>
<li><code>--heapsnapshot-near-heap-limit</code></li>
<li><code>--heapsnapshot-signal</code></li>
<li><code>--http-parser</code></li>
<li><code>--icu-data-dir</code></li>
<li><code>--import</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-wait</code></li>
<li><code>--inspect</code></li>
<li><code>--max-http-header-size</code></li>
<li><code>--napi-modules</code></li>
<li><code>--network-family-autoselection-attempt-timeout</code></li>
<li><code>--no-addons</code></li>
<li><code>--no-deprecation</code></li>
<li><code>--no-experimental-fetch</code></li>
<li><code>--no-experimental-global-customevent</code></li>
<li><code>--no-experimental-global-webcrypto</code></li>
<li><code>--no-experimental-repl-await</code></li>
<li><code>--no-extra-info-on-fatal-exception</code></li>
<li><code>--no-force-async-hooks-checks</code></li>
<li><code>--no-global-search-paths</code></li>
<li><code>--no-network-family-autoselection</code></li>
<li><code>--no-warnings</code></li>
<li><code>--node-memory-debug</code></li>
<li><code>--openssl-config</code></li>
<li><code>--openssl-legacy-provider</code></li>
<li><code>--openssl-shared-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-dir</code>, <code>--report-directory</code></li>
<li><code>--report-exclude-network</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>--secure-heap-min</code></li>
<li><code>--secure-heap</code></li>
<li><code>--snapshot-blob</code></li>
<li><code>--test-only</code></li>
<li><code>--test-reporter-destination</code></li>
<li><code>--test-reporter</code></li>
<li><code>--test-shard</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-atomics-wait</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><code>--watch-path</code></li>
<li><code>--watch-preserve-output</code></li>
<li><code>--watch</code></li>
<li><code>--zero-fill-buffers</code></li>
</ul>
<!-- node-options-node end -->
<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>--enable-etw-stack-walking</code></li>
<li><code>--expose-gc</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>--max-semi-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><code>--stack-trace-limit</code></li>
</ul>
<!-- node-options-v8 end -->
<!-- node-options-others start -->
<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>
<p><code>--enable-etw-stack-walking</code> is only available on Windows.</p>
<!-- node-options-others end -->
<h4><code>NODE_PATH=path[:…]</code><span><a class="mark" href="#all_cli_node_pathpath" id="all_cli_node_pathpath">#</a></span><a aria-hidden="true" class="legacy" id="cli_node_path_path"></a></h4>
<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>
<h4><code>NODE_PENDING_DEPRECATION=1</code><span><a class="mark" href="#all_cli_node_pending_deprecation1" id="all_cli_node_pending_deprecation1">#</a></span><a aria-hidden="true" class="legacy" id="cli_node_pending_deprecation_1"></a></h4>
<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>
<h4><code>NODE_PENDING_PIPE_INSTANCES=instances</code><span><a class="mark" href="#all_cli_node_pending_pipe_instancesinstances" id="all_cli_node_pending_pipe_instancesinstances">#</a></span><a aria-hidden="true" class="legacy" id="cli_node_pending_pipe_instances_instances"></a></h4>
<p>Set the number of pending pipe instance handles when the pipe server is waiting
for connections. This setting applies to Windows only.</p>
<h4><code>NODE_PRESERVE_SYMLINKS=1</code><span><a class="mark" href="#all_cli_node_preserve_symlinks1" id="all_cli_node_preserve_symlinks1">#</a></span><a aria-hidden="true" class="legacy" id="cli_node_preserve_symlinks_1"></a></h4>
<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>
<h4><code>NODE_REDIRECT_WARNINGS=file</code><span><a class="mark" href="#all_cli_node_redirect_warningsfile" id="all_cli_node_redirect_warningsfile">#</a></span><a aria-hidden="true" class="legacy" id="cli_node_redirect_warnings_file"></a></h4>
<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>
<h4><code>NODE_REPL_EXTERNAL_MODULE=file</code><span><a class="mark" href="#all_cli_node_repl_external_modulefile" id="all_cli_node_repl_external_modulefile">#</a></span><a aria-hidden="true" class="legacy" id="cli_node_repl_external_module_file"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.16.0</td>
<td><p>Remove the possibility to use this env var with kDisableNodeOptionsEnv for embedders.</p></td></tr>
<tr><td>v13.0.0, v12.16.0</td>
<td><p><span>Added in: v13.0.0, v12.16.0</span></p></td></tr>
</tbody></table>
</details>
</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>
<h4><code>NODE_REPL_HISTORY=file</code><span><a class="mark" href="#all_cli_node_repl_historyfile" id="all_cli_node_repl_historyfile">#</a></span><a aria-hidden="true" class="legacy" id="cli_node_repl_history_file"></a></h4>
<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>
<h4><code>NODE_SKIP_PLATFORM_CHECK=value</code><span><a class="mark" href="#all_cli_node_skip_platform_checkvalue" id="all_cli_node_skip_platform_checkvalue">#</a></span><a aria-hidden="true" class="legacy" id="cli_node_skip_platform_check_value"></a></h4>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<p>If <code>value</code> equals <code>'1'</code>, the check for a supported platform is skipped during
Node.js startup. Node.js might not execute correctly. Any issues encountered
on unsupported platforms will not be fixed.</p>
<h4><code>NODE_TEST_CONTEXT=value</code><span><a class="mark" href="#all_cli_node_test_contextvalue" id="all_cli_node_test_contextvalue">#</a></span><a aria-hidden="true" class="legacy" id="cli_node_test_context_value"></a></h4>
<p>If <code>value</code> equals <code>'child'</code>, test reporter options will be overridden and test
output will be sent to stdout in the TAP format. If any other value is provided,
Node.js makes no guarantees about the reporter format used or its stability.</p>
<h4><code>NODE_TLS_REJECT_UNAUTHORIZED=value</code><span><a class="mark" href="#all_cli_node_tls_reject_unauthorizedvalue" id="all_cli_node_tls_reject_unauthorizedvalue">#</a></span><a aria-hidden="true" class="legacy" id="cli_node_tls_reject_unauthorized_value"></a></h4>
<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>
<h4><code>NODE_V8_COVERAGE=dir</code><span><a class="mark" href="#all_cli_node_v8_coveragedir" id="all_cli_node_v8_coveragedir">#</a></span><a aria-hidden="true" class="legacy" id="cli_node_v8_coverage_dir"></a></h4>
<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>
<h5>Coverage output<span><a class="mark" href="#all_cli_coverage-output" id="all_cli_coverage-output">#</a></span><a aria-hidden="true" class="legacy" id="cli_coverage_output"></a></h5>
<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"><span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"result"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
    <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"scriptId"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"67"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"url"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"internal/tty.js"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"functions"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span><span class="hljs-punctuation">]</span>
    <span class="hljs-punctuation">}</span>
  <span class="hljs-punctuation">]</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<h5>Source map cache<span><a class="mark" href="#all_cli_source-map-cache" id="all_cli_source-map-cache">#</a></span><a aria-hidden="true" class="legacy" id="cli_source_map_cache"></a></h5>
<p></p><div class="api_stability api_stability_1"><a href="#all_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"><span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"result"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
    <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"scriptId"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"68"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"url"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"file:///absolute/path/to/source.js"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"functions"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span><span class="hljs-punctuation">]</span>
    <span class="hljs-punctuation">}</span>
  <span class="hljs-punctuation">]</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"source-map-cache"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"file:///absolute/path/to/source.js"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"url"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./path-to-map.json"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"data"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
        <span class="hljs-attr">"version"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">3</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"sources"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
          <span class="hljs-string">"file:///absolute/path/to/original.js"</span>
        <span class="hljs-punctuation">]</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"names"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
          <span class="hljs-string">"Foo"</span><span class="hljs-punctuation">,</span>
          <span class="hljs-string">"console"</span><span class="hljs-punctuation">,</span>
          <span class="hljs-string">"info"</span>
        <span class="hljs-punctuation">]</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"mappings"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"MAAMA,IACJC,YAAaC"</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"sourceRoot"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./"</span>
      <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"lineLengths"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
        <span class="hljs-number">13</span><span class="hljs-punctuation">,</span>
        <span class="hljs-number">62</span><span class="hljs-punctuation">,</span>
        <span class="hljs-number">38</span><span class="hljs-punctuation">,</span>
        <span class="hljs-number">27</span>
      <span class="hljs-punctuation">]</span>
    <span class="hljs-punctuation">}</span>
  <span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<h4><code>OPENSSL_CONF=file</code><span><a class="mark" href="#all_cli_openssl_conffile" id="all_cli_openssl_conffile">#</a></span><a aria-hidden="true" class="legacy" id="cli_openssl_conf_file"></a></h4>
<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="#all_cli_--openssl-configfile"><code>--openssl-config</code></a> command-line option is used, the environment
variable is ignored.</p>
<h4><code>SSL_CERT_DIR=dir</code><span><a class="mark" href="#all_cli_ssl_cert_dirdir" id="all_cli_ssl_cert_dirdir">#</a></span><a aria-hidden="true" class="legacy" id="cli_ssl_cert_dir_dir"></a></h4>
<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>
<h4><code>SSL_CERT_FILE=file</code><span><a class="mark" href="#all_cli_ssl_cert_filefile" id="all_cli_ssl_cert_filefile">#</a></span><a aria-hidden="true" class="legacy" id="cli_ssl_cert_file_file"></a></h4>
<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>
<h4><code>TZ</code><span><a class="mark" href="#all_cli_tz" id="all_cli_tz">#</a></span><a aria-hidden="true" class="legacy" id="cli_tz"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.2.0</td>
<td><p>Changing the TZ variable using process.env.TZ = changes the timezone on Windows as well.</p></td></tr>
<tr><td>v13.0.0</td>
<td><p>Changing the TZ variable using process.env.TZ = changes the timezone on POSIX systems.</p></td></tr>
<tr><td>v0.0.1</td>
<td><p><span>Added in: v0.0.1</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>The <code>TZ</code> environment variable is used to specify the timezone configuration.</p>
<p>While Node.js does not support all of the various <a href="https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html">ways that <code>TZ</code> is handled in
other environments</a>, it does support basic <a href="https://en.wikipedia.org/wiki/List_of_tz_database_time_zones">timezone IDs</a> (such as
<code>'Etc/UTC'</code>, <code>'Europe/Paris'</code>, or <code>'America/New_York'</code>).
It may support a few other abbreviations or aliases, but these are strongly
discouraged and not guaranteed.</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">TZ=Europe/Dublin node -pe <span class="hljs-string">"new Date().toString()"</span></span>
Wed May 12 2021 20:30:48 GMT+0100 (Irish Standard Time)</code> <button class="copy-button">copy</button></pre>
<h4><code>UV_THREADPOOL_SIZE=size</code><span><a class="mark" href="#all_cli_uv_threadpool_sizesize" id="all_cli_uv_threadpool_sizesize">#</a></span><a aria-hidden="true" class="legacy" id="cli_uv_threadpool_size_size"></a></h4>
<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="https://docs.libuv.org/en/latest/threadpool.html">libuv threadpool documentation</a>.</p>
<h4><code>UV_USE_IO_URING=value</code><span><a class="mark" href="#all_cli_uv_use_io_uringvalue" id="all_cli_uv_use_io_uringvalue">#</a></span><a aria-hidden="true" class="legacy" id="cli_uv_use_io_uring_value"></a></h4>
<p>Enable or disable libuv's use of <code>io_uring</code> on supported platforms.</p>
<p>On supported platforms, <code>io_uring</code> can significantly improve the performance of
various asynchronous I/O operations.</p>
<p><code>io_uring</code> is disabled by default due to security concerns. When <code>io_uring</code>
is enabled, applications must not change the user identity of the process at
runtime. In this case, JavaScript functions such as <a href="#all_process_processsetuidid"><code>process.setuid()</code></a> are
unavailable, and native addons must not invoke system functions such as
<a href="https://man7.org/linux/man-pages/man2/setuid.2.html"><code>setuid(2)</code></a>.</p>
<p>This environment variable is implemented by a dependency of Node.js and may be
removed in future versions of Node.js. No stability guarantees are provided for
the behavior of this environment variable.</p>
</section><section><h3>Useful V8 options<span><a class="mark" href="#all_cli_useful-v8-options" id="all_cli_useful-v8-options">#</a></span><a aria-hidden="true" class="legacy" id="cli_useful_v8_options"></a></h3>
<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>
<!-- v8-options start -->
<h4><code>--abort-on-uncaught-exception</code><span><a class="mark" href="#all_cli_--abort-on-uncaught-exception_1" id="all_cli_--abort-on-uncaught-exception_1">#</a></span><a aria-hidden="true" class="legacy" id="cli_abort_on_uncaught_exception_1"></a></h4>
<h4><code>--disallow-code-generation-from-strings</code><span><a class="mark" href="#all_cli_--disallow-code-generation-from-strings_1" id="all_cli_--disallow-code-generation-from-strings_1">#</a></span><a aria-hidden="true" class="legacy" id="cli_disallow_code_generation_from_strings_1"></a></h4>
<h4><code>--enable-etw-stack-walking</code><span><a class="mark" href="#all_cli_--enable-etw-stack-walking" id="all_cli_--enable-etw-stack-walking">#</a></span><a aria-hidden="true" class="legacy" id="cli_enable_etw_stack_walking"></a></h4>
<h4><code>--expose-gc</code><span><a class="mark" href="#all_cli_--expose-gc_1" id="all_cli_--expose-gc_1">#</a></span><a aria-hidden="true" class="legacy" id="cli_expose_gc_1"></a></h4>
<h4><code>--harmony-shadow-realm</code><span><a class="mark" href="#all_cli_--harmony-shadow-realm" id="all_cli_--harmony-shadow-realm">#</a></span><a aria-hidden="true" class="legacy" id="cli_harmony_shadow_realm"></a></h4>
<h4><code>--huge-max-old-generation-size</code><span><a class="mark" href="#all_cli_--huge-max-old-generation-size" id="all_cli_--huge-max-old-generation-size">#</a></span><a aria-hidden="true" class="legacy" id="cli_huge_max_old_generation_size"></a></h4>
<h4><code>--jitless</code><span><a class="mark" href="#all_cli_--jitless_1" id="all_cli_--jitless_1">#</a></span><a aria-hidden="true" class="legacy" id="cli_jitless_1"></a></h4>
<h4><code>--interpreted-frames-native-stack</code><span><a class="mark" href="#all_cli_--interpreted-frames-native-stack" id="all_cli_--interpreted-frames-native-stack">#</a></span><a aria-hidden="true" class="legacy" id="cli_interpreted_frames_native_stack"></a></h4>
<h4><code>--prof</code><span><a class="mark" href="#all_cli_--prof_1" id="all_cli_--prof_1">#</a></span><a aria-hidden="true" class="legacy" id="cli_prof_1"></a></h4>
<h4><code>--perf-basic-prof</code><span><a class="mark" href="#all_cli_--perf-basic-prof" id="all_cli_--perf-basic-prof">#</a></span><a aria-hidden="true" class="legacy" id="cli_perf_basic_prof"></a></h4>
<h4><code>--perf-basic-prof-only-functions</code><span><a class="mark" href="#all_cli_--perf-basic-prof-only-functions" id="all_cli_--perf-basic-prof-only-functions">#</a></span><a aria-hidden="true" class="legacy" id="cli_perf_basic_prof_only_functions"></a></h4>
<h4><code>--perf-prof</code><span><a class="mark" href="#all_cli_--perf-prof" id="all_cli_--perf-prof">#</a></span><a aria-hidden="true" class="legacy" id="cli_perf_prof"></a></h4>
<h4><code>--perf-prof-unwinding-info</code><span><a class="mark" href="#all_cli_--perf-prof-unwinding-info" id="all_cli_--perf-prof-unwinding-info">#</a></span><a aria-hidden="true" class="legacy" id="cli_perf_prof_unwinding_info"></a></h4>
<!-- Anchor to make sure old links find a target -->
<p><a id="--max-old-space-sizesize-in-megabytes"></a></p>
<h4><code>--max-old-space-size=SIZE</code> (in MiB)<span><a class="mark" href="#all_cli_--max-old-space-sizesize-in-mib" id="all_cli_--max-old-space-sizesize-in-mib">#</a></span><a aria-hidden="true" class="legacy" id="cli_max_old_space_size_size_in_mib"></a></h4>
<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 2 GiB of memory, consider setting this to
1536 (1.5 GiB) to leave some memory for other uses and avoid swapping.</p>
<pre><code class="language-bash">node --max-old-space-size=1536 index.js</code> <button class="copy-button">copy</button></pre>
<!-- Anchor to make sure old links find a target -->
<p><a id="--max-semi-space-sizesize-in-megabytes"></a></p>
<h4><code>--max-semi-space-size=SIZE</code> (in MiB)<span><a class="mark" href="#all_cli_--max-semi-space-sizesize-in-mib" id="all_cli_--max-semi-space-sizesize-in-mib">#</a></span><a aria-hidden="true" class="legacy" id="cli_max_semi_space_size_size_in_mib"></a></h4>
<p>Sets the maximum <a href="https://www.memorymanagement.org/glossary/s.html#semi.space">semi-space</a> size for V8's <a href="https://v8.dev/blog/orinoco-parallel-scavenger">scavenge garbage collector</a> in
MiB (mebibytes).
Increasing the max size of a semi-space may improve throughput for Node.js at
the cost of more memory consumption.</p>
<p>Since the young generation size of the V8 heap is three times (see
<a href="https://chromium.googlesource.com/v8/v8.git/+/refs/tags/10.3.129/src/heap/heap.cc#328"><code>YoungGenerationSizeFromSemiSpaceSize</code></a> in V8) the size of the semi-space,
an increase of 1 MiB to semi-space applies to each of the three individual
semi-spaces and causes the heap size to increase by 3 MiB. The throughput
improvement depends on your workload (see <a href="https://github.com/nodejs/node/issues/42511">#42511</a>).</p>
<p>The default value is 16 MiB for 64-bit systems and 8 MiB for 32-bit systems. To
get the best configuration for your application, you should try different
max-semi-space-size values when running benchmarks for your application.</p>
<p>For example, benchmark on a 64-bit systems:</p>
<pre><code class="language-bash"><span class="hljs-keyword">for</span> MiB <span class="hljs-keyword">in</span> 16 32 64 128; <span class="hljs-keyword">do</span>
    node --max-semi-space-size=<span class="hljs-variable">$MiB</span> index.js
<span class="hljs-keyword">done</span></code> <button class="copy-button">copy</button></pre>
<h4><code>--security-revert</code><span><a class="mark" href="#all_cli_--security-revert" id="all_cli_--security-revert">#</a></span><a aria-hidden="true" class="legacy" id="cli_security_revert"></a></h4>
<h4><code>--stack-trace-limit=limit</code><span><a class="mark" href="#all_cli_--stack-trace-limitlimit" id="all_cli_--stack-trace-limitlimit">#</a></span><a aria-hidden="true" class="legacy" id="cli_stack_trace_limit_limit"></a></h4>
<p>The maximum number of stack frames to collect in an error's stack trace.
Setting it to 0 disables stack trace collection. The default value is 10.</p>
<pre><code class="language-bash">node --stack-trace-limit=12 -p -e <span class="hljs-string">"Error.stackTraceLimit"</span> <span class="hljs-comment"># prints 12</span></code> <button class="copy-button">copy</button></pre>
<!-- v8-options end --></section>
        </section>
<section><h2>Console<span><a class="mark" href="#all_console_console" id="all_console_console">#</a></span><a aria-hidden="true" class="legacy" id="console_console"></a></h2>

<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/console.js">lib/console.js</a></p>
<p>The <code>node: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="#all_process_processstdout"><code>process.stdout</code></a> and
<a href="#all_process_processstderr"><code>process.stderr</code></a>. The global <code>console</code> can be used without calling
<code>require('node:console')</code>.</li>
</ul>
<p><em><strong>Warning</strong></em>: 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="#all_process_a-note-on-process-io">note on process I/O</a> for
more information.</p>
<p>Example using the global <code>console</code>:</p>
<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'hello world'</span>);
<span class="hljs-comment">// Prints: hello world, to stdout</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'hello %s'</span>, <span class="hljs-string">'world'</span>);
<span class="hljs-comment">// Prints: hello world, to stdout</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Whoops, something bad happened'</span>));
<span class="hljs-comment">// Prints error message and stack trace to stderr:</span>
<span class="hljs-comment">//   Error: Whoops, something bad happened</span>
<span class="hljs-comment">//     at [eval]:5:15</span>
<span class="hljs-comment">//     at Script.runInThisContext (node:vm:132:18)</span>
<span class="hljs-comment">//     at Object.runInThisContext (node:vm:309:38)</span>
<span class="hljs-comment">//     at node:internal/process/execution:77:19</span>
<span class="hljs-comment">//     at [eval]-wrapper:6:22</span>
<span class="hljs-comment">//     at evalScript (node:internal/process/execution:76:60)</span>
<span class="hljs-comment">//     at node:internal/main/eval_string:23:3</span>

<span class="hljs-keyword">const</span> name = <span class="hljs-string">'Will Robinson'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(<span class="hljs-string">`Danger <span class="hljs-subst">${name}</span>! Danger!`</span>);
<span class="hljs-comment">// Prints: Danger Will Robinson! Danger!, to stderr</span></code> <button class="copy-button">copy</button></pre>
<p>Example using the <code>Console</code> class:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> out = <span class="hljs-title function_">getStreamSomehow</span>();
<span class="hljs-keyword">const</span> err = <span class="hljs-title function_">getStreamSomehow</span>();
<span class="hljs-keyword">const</span> myConsole = <span class="hljs-keyword">new</span> <span class="hljs-variable language_">console</span>.<span class="hljs-title class_">Console</span>(out, err);

myConsole.<span class="hljs-title function_">log</span>(<span class="hljs-string">'hello world'</span>);
<span class="hljs-comment">// Prints: hello world, to out</span>
myConsole.<span class="hljs-title function_">log</span>(<span class="hljs-string">'hello %s'</span>, <span class="hljs-string">'world'</span>);
<span class="hljs-comment">// Prints: hello world, to out</span>
myConsole.<span class="hljs-title function_">error</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Whoops, something bad happened'</span>));
<span class="hljs-comment">// Prints: [Error: Whoops, something bad happened], to err</span>

<span class="hljs-keyword">const</span> name = <span class="hljs-string">'Will Robinson'</span>;
myConsole.<span class="hljs-title function_">warn</span>(<span class="hljs-string">`Danger <span class="hljs-subst">${name}</span>! Danger!`</span>);
<span class="hljs-comment">// Prints: Danger Will Robinson! Danger!, to err</span></code> <button class="copy-button">copy</button></pre>
<section><h3>Class: <code>Console</code><span><a class="mark" href="#all_console_class-console" id="all_console_class-console">#</a></span><a aria-hidden="true" class="legacy" id="console_class_console"></a></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>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('node:console').Console</code>
or <code>console.Console</code> (or their destructured counterparts):</p>

<pre class="with-44-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Console</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:console'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Console</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:console'</span>);</code><button class="copy-button">copy</button></pre>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Console</span> } = <span class="hljs-variable language_">console</span>;</code> <button class="copy-button">copy</button></pre>
<h4><code>new Console(stdout[, stderr][, ignoreErrors])</code><span><a class="mark" href="#all_console_new-consolestdout-stderr-ignoreerrors" id="all_console_new-consolestdout-stderr-ignoreerrors">#</a></span><a aria-hidden="true" class="legacy" id="console_new_console_stdout_stderr_ignoreerrors"></a></h4>
<h4><code>new Console(options)</code><span><a class="mark" href="#all_console_new-consoleoptions" id="all_console_new-consoleoptions">#</a></span><a aria-hidden="true" class="legacy" id="console_new_console_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.2.0, 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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>stdout</code> <a href="#all_stream_class-streamwritable" class="type">&#x3C;stream.Writable></a></li>
<li><code>stderr</code> <a href="#all_stream_class-streamwritable" 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="#all_util_utilinspectobject-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 class="with-44-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createWriteStream } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Console</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:console'</span>;
<span class="hljs-comment">// Alternatively</span>
<span class="hljs-comment">// const { Console } = console;</span>

<span class="hljs-keyword">const</span> output = <span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'./stdout.log'</span>);
<span class="hljs-keyword">const</span> errorOutput = <span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'./stderr.log'</span>);
<span class="hljs-comment">// Custom simple logger</span>
<span class="hljs-keyword">const</span> logger = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Console</span>({ <span class="hljs-attr">stdout</span>: output, <span class="hljs-attr">stderr</span>: errorOutput });
<span class="hljs-comment">// use it like console</span>
<span class="hljs-keyword">const</span> count = <span class="hljs-number">5</span>;
logger.<span class="hljs-title function_">log</span>(<span class="hljs-string">'count: %d'</span>, count);
<span class="hljs-comment">// In stdout.log: count 5</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Console</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:console'</span>);
<span class="hljs-comment">// Alternatively</span>
<span class="hljs-comment">// const { Console } = console;</span>

<span class="hljs-keyword">const</span> output = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'./stdout.log'</span>);
<span class="hljs-keyword">const</span> errorOutput = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'./stderr.log'</span>);
<span class="hljs-comment">// Custom simple logger</span>
<span class="hljs-keyword">const</span> logger = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Console</span>({ <span class="hljs-attr">stdout</span>: output, <span class="hljs-attr">stderr</span>: errorOutput });
<span class="hljs-comment">// use it like console</span>
<span class="hljs-keyword">const</span> count = <span class="hljs-number">5</span>;
logger.<span class="hljs-title function_">log</span>(<span class="hljs-string">'count: %d'</span>, count);
<span class="hljs-comment">// In stdout.log: count 5</span></code><button class="copy-button">copy</button></pre>
<p>The global <code>console</code> is a special <code>Console</code> whose output is sent to
<a href="#all_process_processstdout"><code>process.stdout</code></a> and <a href="#all_process_processstderr"><code>process.stderr</code></a>. It is equivalent to calling:</p>
<pre><code class="language-js"><span class="hljs-keyword">new</span> <span class="hljs-title class_">Console</span>({ <span class="hljs-attr">stdout</span>: process.<span class="hljs-property">stdout</span>, <span class="hljs-attr">stderr</span>: process.<span class="hljs-property">stderr</span> });</code> <button class="copy-button">copy</button></pre>
<h4><code>console.assert(value[, ...message])</code><span><a class="mark" href="#all_console_consoleassertvalue-message" id="all_console_consoleassertvalue-message">#</a></span><a aria-hidden="true" class="legacy" id="console_console_assert_value_message"></a></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>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><code>console.assert()</code> writes a message if <code>value</code> is <a href="https://developer.mozilla.org/en-US/docs/Glossary/Falsy">falsy</a> or omitted. It only
writes a message and does not otherwise affect execution. The output always
starts with <code>"Assertion failed"</code>. If provided, <code>message</code> is formatted using
<a href="#all_util_utilformatformat-args"><code>util.format()</code></a>.</p>
<p>If <code>value</code> is <a href="https://developer.mozilla.org/en-US/docs/Glossary/Truthy">truthy</a>, nothing happens.</p>
<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">assert</span>(<span class="hljs-literal">true</span>, <span class="hljs-string">'does nothing'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">assert</span>(<span class="hljs-literal">false</span>, <span class="hljs-string">'Whoops %s work'</span>, <span class="hljs-string">'didn\'t'</span>);
<span class="hljs-comment">// Assertion failed: Whoops didn't work</span>

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">assert</span>();
<span class="hljs-comment">// Assertion failed</span></code> <button class="copy-button">copy</button></pre>
<h4><code>console.clear()</code><span><a class="mark" href="#all_console_consoleclear" id="all_console_consoleclear">#</a></span><a aria-hidden="true" class="legacy" id="console_console_clear"></a></h4>
<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>
<h4><code>console.count([label])</code><span><a class="mark" href="#all_console_consolecountlabel" id="all_console_consolecountlabel">#</a></span><a aria-hidden="true" class="legacy" id="console_console_count_label"></a></h4>
<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">> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">count</span>()
<span class="hljs-attr">default</span>: <span class="hljs-number">1</span>
<span class="hljs-literal">undefined</span>
> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">count</span>(<span class="hljs-string">'default'</span>)
<span class="hljs-attr">default</span>: <span class="hljs-number">2</span>
<span class="hljs-literal">undefined</span>
> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">count</span>(<span class="hljs-string">'abc'</span>)
<span class="hljs-attr">abc</span>: <span class="hljs-number">1</span>
<span class="hljs-literal">undefined</span>
> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">count</span>(<span class="hljs-string">'xyz'</span>)
<span class="hljs-attr">xyz</span>: <span class="hljs-number">1</span>
<span class="hljs-literal">undefined</span>
> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">count</span>(<span class="hljs-string">'abc'</span>)
<span class="hljs-attr">abc</span>: <span class="hljs-number">2</span>
<span class="hljs-literal">undefined</span>
> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">count</span>()
<span class="hljs-attr">default</span>: <span class="hljs-number">3</span>
<span class="hljs-literal">undefined</span>
></code> <button class="copy-button">copy</button></pre>
<h4><code>console.countReset([label])</code><span><a class="mark" href="#all_console_consolecountresetlabel" id="all_console_consolecountresetlabel">#</a></span><a aria-hidden="true" class="legacy" id="console_console_countreset_label"></a></h4>
<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">> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">count</span>(<span class="hljs-string">'abc'</span>);
<span class="hljs-attr">abc</span>: <span class="hljs-number">1</span>
<span class="hljs-literal">undefined</span>
> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">countReset</span>(<span class="hljs-string">'abc'</span>);
<span class="hljs-literal">undefined</span>
> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">count</span>(<span class="hljs-string">'abc'</span>);
<span class="hljs-attr">abc</span>: <span class="hljs-number">1</span>
<span class="hljs-literal">undefined</span>
></code> <button class="copy-button">copy</button></pre>
<h4><code>console.debug(data[, ...args])</code><span><a class="mark" href="#all_console_consoledebugdata-args" id="all_console_consoledebugdata-args">#</a></span><a aria-hidden="true" class="legacy" id="console_console_debug_data_args"></a></h4>
<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="#all_console_consolelogdata-args"><code>console.log()</code></a>.</p>
<h4><code>console.dir(obj[, options])</code><span><a class="mark" href="#all_console_consoledirobj-options" id="all_console_consoledirobj-options">#</a></span><a aria-hidden="true" class="legacy" id="console_console_dir_obj_options"></a></h4>
<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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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="#all_util_utilinspectobject-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="#all_util_customizing-utilinspect-colors">customizing <code>util.inspect()</code> colors</a>. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
</ul>
<p>Uses <a href="#all_util_utilinspectobject-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>
<h4><code>console.dirxml(...data)</code><span><a class="mark" href="#all_console_consoledirxmldata" id="all_console_consoledirxmldata">#</a></span><a aria-hidden="true" class="legacy" id="console_console_dirxml_data"></a></h4>
<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>
<h4><code>console.error([data][, ...args])</code><span><a class="mark" href="#all_console_consoleerrordata-args" id="all_console_consoleerrordata-args">#</a></span><a aria-hidden="true" class="legacy" id="console_console_error_data_args"></a></h4>
<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="#all_util_utilformatformat-args"><code>util.format()</code></a>).</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> code = <span class="hljs-number">5</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'error #%d'</span>, code);
<span class="hljs-comment">// Prints: error #5, to stderr</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'error'</span>, code);
<span class="hljs-comment">// Prints: error 5, to stderr</span></code> <button class="copy-button">copy</button></pre>
<p>If formatting elements (e.g. <code>%d</code>) are not found in the first string then
<a href="#all_util_utilinspectobject-options"><code>util.inspect()</code></a> is called on each argument and the resulting string
values are concatenated. See <a href="#all_util_utilformatformat-args"><code>util.format()</code></a> for more information.</p>
<h4><code>console.group([...label])</code><span><a class="mark" href="#all_console_consolegrouplabel" id="all_console_consolegrouplabel">#</a></span><a aria-hidden="true" class="legacy" id="console_console_group_label"></a></h4>
<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>
<h4><code>console.groupCollapsed()</code><span><a class="mark" href="#all_console_consolegroupcollapsed" id="all_console_consolegroupcollapsed">#</a></span><a aria-hidden="true" class="legacy" id="console_console_groupcollapsed"></a></h4>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div>
<p>An alias for <a href="#all_console_consolegrouplabel"><code>console.group()</code></a>.</p>
<h4><code>console.groupEnd()</code><span><a class="mark" href="#all_console_consolegroupend" id="all_console_consolegroupend">#</a></span><a aria-hidden="true" class="legacy" id="console_console_groupend"></a></h4>
<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>
<h4><code>console.info([data][, ...args])</code><span><a class="mark" href="#all_console_consoleinfodata-args" id="all_console_consoleinfodata-args">#</a></span><a aria-hidden="true" class="legacy" id="console_console_info_data_args"></a></h4>
<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="#all_console_consolelogdata-args"><code>console.log()</code></a>.</p>
<h4><code>console.log([data][, ...args])</code><span><a class="mark" href="#all_console_consolelogdata-args" id="all_console_consolelogdata-args">#</a></span><a aria-hidden="true" class="legacy" id="console_console_log_data_args"></a></h4>
<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="#all_util_utilformatformat-args"><code>util.format()</code></a>).</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> count = <span class="hljs-number">5</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'count: %d'</span>, count);
<span class="hljs-comment">// Prints: count: 5, to stdout</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'count:'</span>, count);
<span class="hljs-comment">// Prints: count: 5, to stdout</span></code> <button class="copy-button">copy</button></pre>
<p>See <a href="#all_util_utilformatformat-args"><code>util.format()</code></a> for more information.</p>
<h4><code>console.table(tabularData[, properties])</code><span><a class="mark" href="#all_console_consoletabletabulardata-properties" id="all_console_consoletabletabulardata-properties">#</a></span><a aria-hidden="true" class="legacy" id="console_console_table_tabulardata_properties"></a></h4>
<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"><span class="hljs-comment">// These can't be parsed as tabular data</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">table</span>(<span class="hljs-title class_">Symbol</span>());
<span class="hljs-comment">// Symbol()</span>

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">table</span>(<span class="hljs-literal">undefined</span>);
<span class="hljs-comment">// undefined</span>

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">table</span>([{ <span class="hljs-attr">a</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">b</span>: <span class="hljs-string">'Y'</span> }, { <span class="hljs-attr">a</span>: <span class="hljs-string">'Z'</span>, <span class="hljs-attr">b</span>: <span class="hljs-number">2</span> }]);
<span class="hljs-comment">// ┌─────────┬─────┬─────┐</span>
<span class="hljs-comment">// │ (index) │ a   │ b   │</span>
<span class="hljs-comment">// ├─────────┼─────┼─────┤</span>
<span class="hljs-comment">// │ 0       │ 1   │ 'Y' │</span>
<span class="hljs-comment">// │ 1       │ 'Z' │ 2   │</span>
<span class="hljs-comment">// └─────────┴─────┴─────┘</span>

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">table</span>([{ <span class="hljs-attr">a</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">b</span>: <span class="hljs-string">'Y'</span> }, { <span class="hljs-attr">a</span>: <span class="hljs-string">'Z'</span>, <span class="hljs-attr">b</span>: <span class="hljs-number">2</span> }], [<span class="hljs-string">'a'</span>]);
<span class="hljs-comment">// ┌─────────┬─────┐</span>
<span class="hljs-comment">// │ (index) │ a   │</span>
<span class="hljs-comment">// ├─────────┼─────┤</span>
<span class="hljs-comment">// │ 0       │ 1   │</span>
<span class="hljs-comment">// │ 1       │ 'Z' │</span>
<span class="hljs-comment">// └─────────┴─────┘</span></code> <button class="copy-button">copy</button></pre>
<h4><code>console.time([label])</code><span><a class="mark" href="#all_console_consoletimelabel" id="all_console_consoletimelabel">#</a></span><a aria-hidden="true" class="legacy" id="console_console_time_label"></a></h4>
<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="#all_console_consoletimeendlabel"><code>console.timeEnd()</code></a> to stop the timer and output the elapsed time in
suitable time units to <code>stdout</code>. For example, if the elapsed
time is 3869ms, <code>console.timeEnd()</code> displays "3.869s".</p>
<h4><code>console.timeEnd([label])</code><span><a class="mark" href="#all_console_consoletimeendlabel" id="all_console_consoletimeendlabel">#</a></span><a aria-hidden="true" class="legacy" id="console_console_timeend_label"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.0.0</td>
<td><p>The elapsed time is displayed with a suitable time unit.</p></td></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="#all_console_consoletimelabel"><code>console.time()</code></a> and
prints the result to <code>stdout</code>:</p>
<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">time</span>(<span class="hljs-string">'bunch-of-stuff'</span>);
<span class="hljs-comment">// Do a bunch of stuff.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">timeEnd</span>(<span class="hljs-string">'bunch-of-stuff'</span>);
<span class="hljs-comment">// Prints: bunch-of-stuff: 225.438ms</span></code> <button class="copy-button">copy</button></pre>
<h4><code>console.timeLog([label][, ...data])</code><span><a class="mark" href="#all_console_consoletimeloglabel-data" id="all_console_consoletimeloglabel-data">#</a></span><a aria-hidden="true" class="legacy" id="console_console_timelog_label_data"></a></h4>
<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="#all_console_consoletimelabel"><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"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">time</span>(<span class="hljs-string">'process'</span>);
<span class="hljs-keyword">const</span> value = <span class="hljs-title function_">expensiveProcess1</span>(); <span class="hljs-comment">// Returns 42</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">timeLog</span>(<span class="hljs-string">'process'</span>, value);
<span class="hljs-comment">// Prints "process: 365.227ms 42".</span>
<span class="hljs-title function_">doExpensiveProcess2</span>(value);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">timeEnd</span>(<span class="hljs-string">'process'</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>console.trace([message][, ...args])</code><span><a class="mark" href="#all_console_consoletracemessage-args" id="all_console_consoletracemessage-args">#</a></span><a aria-hidden="true" class="legacy" id="console_console_trace_message_args"></a></h4>
<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="#all_util_utilformatformat-args"><code>util.format()</code></a>
formatted message and stack trace to the current position in the code.</p>
<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">trace</span>(<span class="hljs-string">'Show me'</span>);
<span class="hljs-comment">// Prints: (stack trace will vary based on where trace is called)</span>
<span class="hljs-comment">//  Trace: Show me</span>
<span class="hljs-comment">//    at repl:2:9</span>
<span class="hljs-comment">//    at REPLServer.defaultEval (repl.js:248:27)</span>
<span class="hljs-comment">//    at bound (domain.js:287:14)</span>
<span class="hljs-comment">//    at REPLServer.runBound [as eval] (domain.js:300:12)</span>
<span class="hljs-comment">//    at REPLServer.&#x3C;anonymous> (repl.js:412:12)</span>
<span class="hljs-comment">//    at emitOne (events.js:82:20)</span>
<span class="hljs-comment">//    at REPLServer.emit (events.js:169:7)</span>
<span class="hljs-comment">//    at REPLServer.Interface._onLine (readline.js:210:10)</span>
<span class="hljs-comment">//    at REPLServer.Interface._line (readline.js:549:8)</span>
<span class="hljs-comment">//    at REPLServer.Interface._ttyWrite (readline.js:826:14)</span></code> <button class="copy-button">copy</button></pre>
<h4><code>console.warn([data][, ...args])</code><span><a class="mark" href="#all_console_consolewarndata-args" id="all_console_consolewarndata-args">#</a></span><a aria-hidden="true" class="legacy" id="console_console_warn_data_args"></a></h4>
<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="#all_console_consoleerrordata-args"><code>console.error()</code></a>.</p>
</section><section><h3>Inspector only methods<span><a class="mark" href="#all_console_inspector-only-methods" id="all_console_inspector-only-methods">#</a></span><a aria-hidden="true" class="legacy" id="console_inspector_only_methods"></a></h3>
<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>
<h4><code>console.profile([label])</code><span><a class="mark" href="#all_console_consoleprofilelabel" id="all_console_consoleprofilelabel">#</a></span><a aria-hidden="true" class="legacy" id="console_console_profile_label"></a></h4>
<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="#all_console_consoleprofileendlabel"><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"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">profile</span>(<span class="hljs-string">'MyLabel'</span>);
<span class="hljs-comment">// Some code</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">profileEnd</span>(<span class="hljs-string">'MyLabel'</span>);
<span class="hljs-comment">// Adds the profile 'MyLabel' to the Profiles panel of the inspector.</span></code> <button class="copy-button">copy</button></pre>
<h4><code>console.profileEnd([label])</code><span><a class="mark" href="#all_console_consoleprofileendlabel" id="all_console_consoleprofileendlabel">#</a></span><a aria-hidden="true" class="legacy" id="console_console_profileend_label"></a></h4>
<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="#all_console_consoleprofilelabel"><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>
<h4><code>console.timeStamp([label])</code><span><a class="mark" href="#all_console_consoletimestamplabel" id="all_console_consoletimestamplabel">#</a></span><a aria-hidden="true" class="legacy" id="console_console_timestamp_label"></a></h4>
<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></section>
        </section>
<section><h2>Corepack<span><a class="mark" href="#all_corepack_corepack" id="all_corepack_corepack">#</a></span><a aria-hidden="true" class="legacy" id="corepack_corepack"></a></h2>


<div class="api_metadata">
<span>Added in: v16.9.0, v14.19.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p><em><a href="https://github.com/nodejs/corepack">Corepack</a></em> is an experimental tool to help with
managing versions of your package managers. It exposes binary proxies for
each <a href="#all_corepack_supported-package-managers">supported package manager</a> that, when called, will identify whatever
package manager is configured for the current project, download it if needed,
and finally run it.</p>
<p>Despite Corepack being distributed with default installs of Node.js, the package
managers managed by Corepack are not part of the Node.js distribution and:</p>
<ul>
<li>Upon first use, Corepack downloads the latest version from the network.</li>
<li>Any required updates (related to security vulnerabilities or otherwise) are
out of scope of the Node.js project. If necessary end users must figure out
how to update on their own.</li>
</ul>
<p>This feature simplifies two core workflows:</p>
<ul>
<li>
<p>It eases new contributor onboarding, since they won't have to follow
system-specific installation processes anymore just to have the package
manager you want them to.</p>
</li>
<li>
<p>It allows you to ensure that everyone in your team will use exactly the
package manager version you intend them to, without them having to
manually synchronize it each time you need to make an update.</p>
</li>
</ul>
<section><h3>Workflows<span><a class="mark" href="#all_corepack_workflows" id="all_corepack_workflows">#</a></span><a aria-hidden="true" class="legacy" id="corepack_workflows"></a></h3>
<h4>Enabling the feature<span><a class="mark" href="#all_corepack_enabling-the-feature" id="all_corepack_enabling-the-feature">#</a></span><a aria-hidden="true" class="legacy" id="corepack_enabling_the_feature"></a></h4>
<p>Due to its experimental status, Corepack currently needs to be explicitly
enabled to have any effect. To do that, run <a href="https://github.com/nodejs/corepack#corepack-enable--name"><code>corepack enable</code></a>, which
will set up the symlinks in your environment next to the <code>node</code> binary
(and overwrite the existing symlinks if necessary).</p>
<p>From this point forward, any call to the <a href="#all_corepack_supported-package-managers">supported binaries</a> will work
without further setup. Should you experience a problem, run
<a href="https://github.com/nodejs/corepack#corepack-disable--name"><code>corepack disable</code></a> to remove the proxies from your system (and consider
opening an issue on the <a href="https://github.com/nodejs/corepack">Corepack repository</a> to let us know).</p>
<h4>Configuring a package<span><a class="mark" href="#all_corepack_configuring-a-package" id="all_corepack_configuring-a-package">#</a></span><a aria-hidden="true" class="legacy" id="corepack_configuring_a_package"></a></h4>
<p>The Corepack proxies will find the closest <a href="#all_packages_nodejs-packagejson-field-definitions"><code>package.json</code></a> file in your
current directory hierarchy to extract its <a href="#all_packages_packagemanager"><code>"packageManager"</code></a> property.</p>
<p>If the value corresponds to a <a href="#all_corepack_supported-package-managers">supported package manager</a>, Corepack will make
sure that all calls to the relevant binaries are run against the requested
version, downloading it on demand if needed, and aborting if it cannot be
successfully retrieved.</p>
<p>You can use <a href="https://github.com/nodejs/corepack#corepack-use-nameversion"><code>corepack use</code></a> to ask Corepack to update your local
<code>package.json</code> to use the package manager of your choice:</p>
<pre><code class="language-bash">corepack use pnpm@7.x <span class="hljs-comment"># sets the latest 7.x version in the package.json</span>
corepack use yarn@* <span class="hljs-comment"># sets the latest version in the package.json</span></code> <button class="copy-button">copy</button></pre>
<h4>Upgrading the global versions<span><a class="mark" href="#all_corepack_upgrading-the-global-versions" id="all_corepack_upgrading-the-global-versions">#</a></span><a aria-hidden="true" class="legacy" id="corepack_upgrading_the_global_versions"></a></h4>
<p>When running outside of an existing project (for example when running
<code>yarn init</code>), Corepack will by default use predefined versions roughly
corresponding to the latest stable releases from each tool. Those versions can
be overridden by running the <a href="https://github.com/nodejs/corepack#corepack-install--g--global---all--nameversion"><code>corepack install</code></a> command along with the
package manager version you wish to set:</p>
<pre><code class="language-bash">corepack install --global yarn@x.y.z</code> <button class="copy-button">copy</button></pre>
<p>Alternately, a tag or range may be used:</p>
<pre><code class="language-bash">corepack install --global pnpm@*
corepack install --global yarn@stable</code> <button class="copy-button">copy</button></pre>
<h4>Offline workflow<span><a class="mark" href="#all_corepack_offline-workflow" id="all_corepack_offline-workflow">#</a></span><a aria-hidden="true" class="legacy" id="corepack_offline_workflow"></a></h4>
<p>Many production environments don't have network access. Since Corepack
usually downloads the package manager releases straight from their registries,
it can conflict with such environments. To avoid that happening, call the
<a href="https://github.com/nodejs/corepack#corepack-pack---all--nameversion"><code>corepack pack</code></a> command while you still have network access (typically at
the same time you're preparing your deploy image). This will ensure that the
required package managers are available even without network access.</p>
<p>The <code>pack</code> command has <a href="https://github.com/nodejs/corepack#utility-commands">various flags</a>. Consult the detailed
<a href="https://github.com/nodejs/corepack#readme">Corepack documentation</a> for more information.</p>
</section><section><h3>Supported package managers<span><a class="mark" href="#all_corepack_supported-package-managers" id="all_corepack_supported-package-managers">#</a></span><a aria-hidden="true" class="legacy" id="corepack_supported_package_managers"></a></h3>
<p>The following binaries are provided through Corepack:</p>

















<table><thead><tr><th>Package manager</th><th>Binary names</th></tr></thead><tbody><tr><td><a href="https://yarnpkg.com">Yarn</a></td><td><code>yarn</code>, <code>yarnpkg</code></td></tr><tr><td><a href="https://pnpm.io">pnpm</a></td><td><code>pnpm</code>, <code>pnpx</code></td></tr></tbody></table>
</section><section><h3>Common questions<span><a class="mark" href="#all_corepack_common-questions" id="all_corepack_common-questions">#</a></span><a aria-hidden="true" class="legacy" id="corepack_common_questions"></a></h3>
<h4>How does Corepack interact with npm?<span><a class="mark" href="#all_corepack_how-does-corepack-interact-with-npm" id="all_corepack_how-does-corepack-interact-with-npm">#</a></span><a aria-hidden="true" class="legacy" id="corepack_how_does_corepack_interact_with_npm"></a></h4>
<p>While Corepack could support npm like any other package manager, its
shims aren't enabled by default. This has a few consequences:</p>
<ul>
<li>
<p>It's always possible to run a <code>npm</code> command within a project configured to
be used with another package manager, since Corepack cannot intercept it.</p>
</li>
<li>
<p>While <code>npm</code> is a valid option in the <a href="#all_packages_packagemanager"><code>"packageManager"</code></a> property, the
lack of shim will cause the global npm to be used.</p>
</li>
</ul>
<h4>Running <code>npm install -g yarn</code> doesn't work<span><a class="mark" href="#all_corepack_running-npm-install--g-yarn-doesnt-work" id="all_corepack_running-npm-install--g-yarn-doesnt-work">#</a></span><a aria-hidden="true" class="legacy" id="corepack_running_npm_install_g_yarn_doesn_t_work"></a></h4>
<p>npm prevents accidentally overriding the Corepack binaries when doing a global
install. To avoid this problem, consider one of the following options:</p>
<ul>
<li>
<p>Don't run this command; Corepack will provide the package manager
binaries anyway and will ensure that the requested versions are always
available, so installing the package managers explicitly isn't needed.</p>
</li>
<li>
<p>Add the <code>--force</code> flag to <code>npm install</code>; this will tell npm that it's fine to
override binaries, but you'll erase the Corepack ones in the process. (Run
<a href="https://github.com/nodejs/corepack#corepack-enable--name"><code>corepack enable</code></a> to add them back.)</p>
</li>
</ul></section>
        </section>
<section><h2>Crypto<span><a class="mark" href="#all_crypto_crypto" id="all_crypto_crypto">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto"></a></h2>

<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/crypto.js">lib/crypto.js</a></p>
<p>The <code>node:crypto</code> module provides cryptographic functionality that includes a
set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify
functions.</p>

<pre class="with-51-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">const</span> { createHmac } = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> secret = <span class="hljs-string">'abcdefg'</span>;
<span class="hljs-keyword">const</span> hash = <span class="hljs-title function_">createHmac</span>(<span class="hljs-string">'sha256'</span>, secret)
               .<span class="hljs-title function_">update</span>(<span class="hljs-string">'I love cupcakes'</span>)
               .<span class="hljs-title function_">digest</span>(<span class="hljs-string">'hex'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(hash);
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { createHmac } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> secret = <span class="hljs-string">'abcdefg'</span>;
<span class="hljs-keyword">const</span> hash = <span class="hljs-title function_">createHmac</span>(<span class="hljs-string">'sha256'</span>, secret)
               .<span class="hljs-title function_">update</span>(<span class="hljs-string">'I love cupcakes'</span>)
               .<span class="hljs-title function_">digest</span>(<span class="hljs-string">'hex'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(hash);
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e</span></code><button class="copy-button">copy</button></pre>
<section><h3>Determining if crypto support is unavailable<span><a class="mark" href="#all_crypto_determining-if-crypto-support-is-unavailable" id="all_crypto_determining-if-crypto-support-is-unavailable">#</a></span><a aria-hidden="true" class="legacy" id="crypto_determining_if_crypto_support_is_unavailable"></a></h3>
<p>It is possible for Node.js to be built without including support for the
<code>node:crypto</code> module. In such cases, attempting to <code>import</code> from <code>crypto</code> or
calling <code>require('node:crypto')</code> will result in an error being thrown.</p>
<p>When using CommonJS, the error thrown can be caught using try/catch:</p>
<!-- eslint-disable no-global-assign -->
<pre><code class="language-js cjs"><span class="hljs-keyword">let</span> crypto;
<span class="hljs-keyword">try</span> {
  crypto = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'crypto support is disabled!'</span>);
}</code> <button class="copy-button">copy</button></pre>
<!-- eslint-enable no-global-assign -->
<p>When using the lexical ESM <code>import</code> keyword, the error can only be
caught if a handler for <code>process.on('uncaughtException')</code> is registered
<em>before</em> any attempt to load the module is made (using, for instance,
a preload module).</p>
<p>When using ESM, if there is a chance that the code may be run on a build
of Node.js where crypto support is not enabled, consider using the
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import"><code>import()</code></a> function instead of the lexical <code>import</code> keyword:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">let</span> crypto;
<span class="hljs-keyword">try</span> {
  crypto = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'crypto support is disabled!'</span>);
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>Certificate</code><span><a class="mark" href="#all_crypto_class-certificate" id="all_crypto_class-certificate">#</a></span><a aria-hidden="true" class="legacy" id="crypto_class_certificate"></a></h3>
<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 HTML5's <code>keygen</code> element.</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>node: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/man3.0/man1/openssl-spkac.html">OpenSSL's SPKAC implementation</a> internally.</p>
<h4>Static method: <code>Certificate.exportChallenge(spkac[, encoding])</code><span><a class="mark" href="#all_crypto_static-method-certificateexportchallengespkac-encoding" id="all_crypto_static-method-certificateexportchallengespkac-encoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_static_method_certificate_exportchallenge_spkac_encoding"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>The spkac argument can be an ArrayBuffer. Limited the size of the spkac argument to a maximum of 2**31 - 1 bytes.</p></td></tr>
<tr><td>v9.0.0</td>
<td><p><span>Added in: v9.0.0</span></p></td></tr>
</tbody></table>
</details>
</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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_buffer_buffers-and-character-encodings">encoding</a> of the <code>spkac</code> string.</li>
<li>Returns: <a href="#all_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 class="with-52-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Certificate</span> } = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> spkac = <span class="hljs-title function_">getSpkacSomehow</span>();
<span class="hljs-keyword">const</span> challenge = <span class="hljs-title class_">Certificate</span>.<span class="hljs-title function_">exportChallenge</span>(spkac);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(challenge.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'utf8'</span>));
<span class="hljs-comment">// Prints: the challenge as a UTF8 string</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Certificate</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> spkac = <span class="hljs-title function_">getSpkacSomehow</span>();
<span class="hljs-keyword">const</span> challenge = <span class="hljs-title class_">Certificate</span>.<span class="hljs-title function_">exportChallenge</span>(spkac);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(challenge.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'utf8'</span>));
<span class="hljs-comment">// Prints: the challenge as a UTF8 string</span></code><button class="copy-button">copy</button></pre>
<h4>Static method: <code>Certificate.exportPublicKey(spkac[, encoding])</code><span><a class="mark" href="#all_crypto_static-method-certificateexportpublickeyspkac-encoding" id="all_crypto_static-method-certificateexportpublickeyspkac-encoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_static_method_certificate_exportpublickey_spkac_encoding"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>The spkac argument can be an ArrayBuffer. Limited the size of the spkac argument to a maximum of 2**31 - 1 bytes.</p></td></tr>
<tr><td>v9.0.0</td>
<td><p><span>Added in: v9.0.0</span></p></td></tr>
</tbody></table>
</details>
</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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_buffer_buffers-and-character-encodings">encoding</a> of the <code>spkac</code> string.</li>
<li>Returns: <a href="#all_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 class="with-52-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Certificate</span> } = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> spkac = <span class="hljs-title function_">getSpkacSomehow</span>();
<span class="hljs-keyword">const</span> publicKey = <span class="hljs-title class_">Certificate</span>.<span class="hljs-title function_">exportPublicKey</span>(spkac);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(publicKey);
<span class="hljs-comment">// Prints: the public key as &#x3C;Buffer ...></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Certificate</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> spkac = <span class="hljs-title function_">getSpkacSomehow</span>();
<span class="hljs-keyword">const</span> publicKey = <span class="hljs-title class_">Certificate</span>.<span class="hljs-title function_">exportPublicKey</span>(spkac);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(publicKey);
<span class="hljs-comment">// Prints: the public key as &#x3C;Buffer ...></span></code><button class="copy-button">copy</button></pre>
<h4>Static method: <code>Certificate.verifySpkac(spkac[, encoding])</code><span><a class="mark" href="#all_crypto_static-method-certificateverifyspkacspkac-encoding" id="all_crypto_static-method-certificateverifyspkacspkac-encoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_static_method_certificate_verifyspkac_spkac_encoding"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>The spkac argument can be an ArrayBuffer. Added encoding. Limited the size of the spkac argument to a maximum of 2**31 - 1 bytes.</p></td></tr>
<tr><td>v9.0.0</td>
<td><p><span>Added in: v9.0.0</span></p></td></tr>
</tbody></table>
</details>
</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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_buffer_buffers-and-character-encodings">encoding</a> of the <code>spkac</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> if the given <code>spkac</code> data structure is valid,
<code>false</code> otherwise.</li>
</ul>

<pre class="with-52-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Certificate</span> } = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> spkac = <span class="hljs-title function_">getSpkacSomehow</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Certificate</span>.<span class="hljs-title function_">verifySpkac</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(spkac)));
<span class="hljs-comment">// Prints: true or false</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Certificate</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> spkac = <span class="hljs-title function_">getSpkacSomehow</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Certificate</span>.<span class="hljs-title function_">verifySpkac</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(spkac)));
<span class="hljs-comment">// Prints: true or false</span></code><button class="copy-button">copy</button></pre>
<h4>Legacy API<span><a class="mark" href="#all_crypto_legacy-api" id="all_crypto_legacy-api">#</a></span><a aria-hidden="true" class="legacy" id="crypto_legacy_api"></a></h4>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated</div><p></p>
<p>As a legacy interface, it is possible to create new instances of
the <code>crypto.Certificate</code> class as illustrated in the examples below.</p>
<h5><code>new crypto.Certificate()</code><span><a class="mark" href="#all_crypto_new-cryptocertificate" id="all_crypto_new-cryptocertificate">#</a></span><a aria-hidden="true" class="legacy" id="crypto_new_crypto_certificate"></a></h5>
<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 class="with-52-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Certificate</span> } = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> cert1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Certificate</span>();
<span class="hljs-keyword">const</span> cert2 = <span class="hljs-title class_">Certificate</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Certificate</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> cert1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Certificate</span>();
<span class="hljs-keyword">const</span> cert2 = <span class="hljs-title class_">Certificate</span>();</code><button class="copy-button">copy</button></pre>
<h5><code>certificate.exportChallenge(spkac[, encoding])</code><span><a class="mark" href="#all_crypto_certificateexportchallengespkac-encoding" id="all_crypto_certificateexportchallengespkac-encoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_certificate_exportchallenge_spkac_encoding"></a></h5>
<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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_buffer_buffers-and-character-encodings">encoding</a> of the <code>spkac</code> string.</li>
<li>Returns: <a href="#all_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 class="with-52-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Certificate</span> } = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> cert = <span class="hljs-title class_">Certificate</span>();
<span class="hljs-keyword">const</span> spkac = <span class="hljs-title function_">getSpkacSomehow</span>();
<span class="hljs-keyword">const</span> challenge = cert.<span class="hljs-title function_">exportChallenge</span>(spkac);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(challenge.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'utf8'</span>));
<span class="hljs-comment">// Prints: the challenge as a UTF8 string</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Certificate</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> cert = <span class="hljs-title class_">Certificate</span>();
<span class="hljs-keyword">const</span> spkac = <span class="hljs-title function_">getSpkacSomehow</span>();
<span class="hljs-keyword">const</span> challenge = cert.<span class="hljs-title function_">exportChallenge</span>(spkac);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(challenge.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'utf8'</span>));
<span class="hljs-comment">// Prints: the challenge as a UTF8 string</span></code><button class="copy-button">copy</button></pre>
<h5><code>certificate.exportPublicKey(spkac[, encoding])</code><span><a class="mark" href="#all_crypto_certificateexportpublickeyspkac-encoding" id="all_crypto_certificateexportpublickeyspkac-encoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_certificate_exportpublickey_spkac_encoding"></a></h5>
<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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_buffer_buffers-and-character-encodings">encoding</a> of the <code>spkac</code> string.</li>
<li>Returns: <a href="#all_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 class="with-52-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Certificate</span> } = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> cert = <span class="hljs-title class_">Certificate</span>();
<span class="hljs-keyword">const</span> spkac = <span class="hljs-title function_">getSpkacSomehow</span>();
<span class="hljs-keyword">const</span> publicKey = cert.<span class="hljs-title function_">exportPublicKey</span>(spkac);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(publicKey);
<span class="hljs-comment">// Prints: the public key as &#x3C;Buffer ...></span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Certificate</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> cert = <span class="hljs-title class_">Certificate</span>();
<span class="hljs-keyword">const</span> spkac = <span class="hljs-title function_">getSpkacSomehow</span>();
<span class="hljs-keyword">const</span> publicKey = cert.<span class="hljs-title function_">exportPublicKey</span>(spkac);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(publicKey);
<span class="hljs-comment">// Prints: the public key as &#x3C;Buffer ...></span></code><button class="copy-button">copy</button></pre>
<h5><code>certificate.verifySpkac(spkac[, encoding])</code><span><a class="mark" href="#all_crypto_certificateverifyspkacspkac-encoding" id="all_crypto_certificateverifyspkacspkac-encoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_certificate_verifyspkac_spkac_encoding"></a></h5>
<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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_buffer_buffers-and-character-encodings">encoding</a> of the <code>spkac</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> if the given <code>spkac</code> data structure is valid,
<code>false</code> otherwise.</li>
</ul>

<pre class="with-52-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Certificate</span> } = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> cert = <span class="hljs-title class_">Certificate</span>();
<span class="hljs-keyword">const</span> spkac = <span class="hljs-title function_">getSpkacSomehow</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(cert.<span class="hljs-title function_">verifySpkac</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(spkac)));
<span class="hljs-comment">// Prints: true or false</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Certificate</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> cert = <span class="hljs-title class_">Certificate</span>();
<span class="hljs-keyword">const</span> spkac = <span class="hljs-title function_">getSpkacSomehow</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(cert.<span class="hljs-title function_">verifySpkac</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(spkac)));
<span class="hljs-comment">// Prints: true or false</span></code><button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>Cipher</code><span><a class="mark" href="#all_crypto_class-cipher" id="all_crypto_class-cipher">#</a></span><a aria-hidden="true" class="legacy" id="crypto_class_cipher"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.94</span>
</div>
<ul>
<li>Extends: <a href="#all_stream_class-streamtransform" 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="#all_crypto_cipherupdatedata-inputencoding-outputencoding"><code>cipher.update()</code></a> and <a href="#all_crypto_cipherfinaloutputencoding"><code>cipher.final()</code></a> methods to produce
the encrypted data.</li>
</ul>
<p>The <a href="#all_crypto_cryptocreatecipheralgorithm-password-options"><code>crypto.createCipher()</code></a> or <a href="#all_crypto_cryptocreatecipherivalgorithm-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 class="with-9-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">const</span> {
  scrypt,
  randomFill,
  createCipheriv,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> algorithm = <span class="hljs-string">'aes-192-cbc'</span>;
<span class="hljs-keyword">const</span> password = <span class="hljs-string">'Password used to generate key'</span>;

<span class="hljs-comment">// First, we'll generate the key. The key length is dependent on the algorithm.</span>
<span class="hljs-comment">// In this case for aes192, it is 24 bytes (192 bits).</span>
<span class="hljs-title function_">scrypt</span>(password, <span class="hljs-string">'salt'</span>, <span class="hljs-number">24</span>, <span class="hljs-function">(<span class="hljs-params">err, key</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-comment">// Then, we'll generate a random initialization vector</span>
  <span class="hljs-title function_">randomFill</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(<span class="hljs-number">16</span>), <span class="hljs-function">(<span class="hljs-params">err, iv</span>) =></span> {
    <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;

    <span class="hljs-comment">// Once we have the key and iv, we can create and use the cipher...</span>
    <span class="hljs-keyword">const</span> cipher = <span class="hljs-title function_">createCipheriv</span>(algorithm, key, iv);

    <span class="hljs-keyword">let</span> encrypted = <span class="hljs-string">''</span>;
    cipher.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'hex'</span>);

    cipher.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> encrypted += chunk);
    cipher.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(encrypted));

    cipher.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some clear text data'</span>);
    cipher.<span class="hljs-title function_">end</span>();
  });
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
  scrypt,
  randomFill,
  createCipheriv,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> algorithm = <span class="hljs-string">'aes-192-cbc'</span>;
<span class="hljs-keyword">const</span> password = <span class="hljs-string">'Password used to generate key'</span>;

<span class="hljs-comment">// First, we'll generate the key. The key length is dependent on the algorithm.</span>
<span class="hljs-comment">// In this case for aes192, it is 24 bytes (192 bits).</span>
<span class="hljs-title function_">scrypt</span>(password, <span class="hljs-string">'salt'</span>, <span class="hljs-number">24</span>, <span class="hljs-function">(<span class="hljs-params">err, key</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-comment">// Then, we'll generate a random initialization vector</span>
  <span class="hljs-title function_">randomFill</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(<span class="hljs-number">16</span>), <span class="hljs-function">(<span class="hljs-params">err, iv</span>) =></span> {
    <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;

    <span class="hljs-comment">// Once we have the key and iv, we can create and use the cipher...</span>
    <span class="hljs-keyword">const</span> cipher = <span class="hljs-title function_">createCipheriv</span>(algorithm, key, iv);

    <span class="hljs-keyword">let</span> encrypted = <span class="hljs-string">''</span>;
    cipher.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'hex'</span>);

    cipher.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> encrypted += chunk);
    cipher.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(encrypted));

    cipher.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some clear text data'</span>);
    cipher.<span class="hljs-title function_">end</span>();
  });
});</code><button class="copy-button">copy</button></pre>
<p>Example: Using <code>Cipher</code> and piped streams:</p>

<pre class="with-19-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> {
  createReadStream,
  createWriteStream,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-keyword">import</span> {
  pipeline,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;

<span class="hljs-keyword">const</span> {
  scrypt,
  randomFill,
  createCipheriv,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> algorithm = <span class="hljs-string">'aes-192-cbc'</span>;
<span class="hljs-keyword">const</span> password = <span class="hljs-string">'Password used to generate key'</span>;

<span class="hljs-comment">// First, we'll generate the key. The key length is dependent on the algorithm.</span>
<span class="hljs-comment">// In this case for aes192, it is 24 bytes (192 bits).</span>
<span class="hljs-title function_">scrypt</span>(password, <span class="hljs-string">'salt'</span>, <span class="hljs-number">24</span>, <span class="hljs-function">(<span class="hljs-params">err, key</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-comment">// Then, we'll generate a random initialization vector</span>
  <span class="hljs-title function_">randomFill</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(<span class="hljs-number">16</span>), <span class="hljs-function">(<span class="hljs-params">err, iv</span>) =></span> {
    <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;

    <span class="hljs-keyword">const</span> cipher = <span class="hljs-title function_">createCipheriv</span>(algorithm, key, iv);

    <span class="hljs-keyword">const</span> input = <span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'test.js'</span>);
    <span class="hljs-keyword">const</span> output = <span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'test.enc'</span>);

    <span class="hljs-title function_">pipeline</span>(input, cipher, output, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
      <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
    });
  });
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
  createReadStream,
  createWriteStream,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);

<span class="hljs-keyword">const</span> {
  pipeline,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);

<span class="hljs-keyword">const</span> {
  scrypt,
  randomFill,
  createCipheriv,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> algorithm = <span class="hljs-string">'aes-192-cbc'</span>;
<span class="hljs-keyword">const</span> password = <span class="hljs-string">'Password used to generate key'</span>;

<span class="hljs-comment">// First, we'll generate the key. The key length is dependent on the algorithm.</span>
<span class="hljs-comment">// In this case for aes192, it is 24 bytes (192 bits).</span>
<span class="hljs-title function_">scrypt</span>(password, <span class="hljs-string">'salt'</span>, <span class="hljs-number">24</span>, <span class="hljs-function">(<span class="hljs-params">err, key</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-comment">// Then, we'll generate a random initialization vector</span>
  <span class="hljs-title function_">randomFill</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(<span class="hljs-number">16</span>), <span class="hljs-function">(<span class="hljs-params">err, iv</span>) =></span> {
    <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;

    <span class="hljs-keyword">const</span> cipher = <span class="hljs-title function_">createCipheriv</span>(algorithm, key, iv);

    <span class="hljs-keyword">const</span> input = <span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'test.js'</span>);
    <span class="hljs-keyword">const</span> output = <span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'test.enc'</span>);

    <span class="hljs-title function_">pipeline</span>(input, cipher, output, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
      <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
    });
  });
});</code><button class="copy-button">copy</button></pre>
<p>Example: Using the <a href="#all_crypto_cipherupdatedata-inputencoding-outputencoding"><code>cipher.update()</code></a> and <a href="#all_crypto_cipherfinaloutputencoding"><code>cipher.final()</code></a> methods:</p>

<pre class="with-9-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">const</span> {
  scrypt,
  randomFill,
  createCipheriv,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> algorithm = <span class="hljs-string">'aes-192-cbc'</span>;
<span class="hljs-keyword">const</span> password = <span class="hljs-string">'Password used to generate key'</span>;

<span class="hljs-comment">// First, we'll generate the key. The key length is dependent on the algorithm.</span>
<span class="hljs-comment">// In this case for aes192, it is 24 bytes (192 bits).</span>
<span class="hljs-title function_">scrypt</span>(password, <span class="hljs-string">'salt'</span>, <span class="hljs-number">24</span>, <span class="hljs-function">(<span class="hljs-params">err, key</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-comment">// Then, we'll generate a random initialization vector</span>
  <span class="hljs-title function_">randomFill</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(<span class="hljs-number">16</span>), <span class="hljs-function">(<span class="hljs-params">err, iv</span>) =></span> {
    <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;

    <span class="hljs-keyword">const</span> cipher = <span class="hljs-title function_">createCipheriv</span>(algorithm, key, iv);

    <span class="hljs-keyword">let</span> encrypted = cipher.<span class="hljs-title function_">update</span>(<span class="hljs-string">'some clear text data'</span>, <span class="hljs-string">'utf8'</span>, <span class="hljs-string">'hex'</span>);
    encrypted += cipher.<span class="hljs-title function_">final</span>(<span class="hljs-string">'hex'</span>);
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(encrypted);
  });
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
  scrypt,
  randomFill,
  createCipheriv,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> algorithm = <span class="hljs-string">'aes-192-cbc'</span>;
<span class="hljs-keyword">const</span> password = <span class="hljs-string">'Password used to generate key'</span>;

<span class="hljs-comment">// First, we'll generate the key. The key length is dependent on the algorithm.</span>
<span class="hljs-comment">// In this case for aes192, it is 24 bytes (192 bits).</span>
<span class="hljs-title function_">scrypt</span>(password, <span class="hljs-string">'salt'</span>, <span class="hljs-number">24</span>, <span class="hljs-function">(<span class="hljs-params">err, key</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-comment">// Then, we'll generate a random initialization vector</span>
  <span class="hljs-title function_">randomFill</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(<span class="hljs-number">16</span>), <span class="hljs-function">(<span class="hljs-params">err, iv</span>) =></span> {
    <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;

    <span class="hljs-keyword">const</span> cipher = <span class="hljs-title function_">createCipheriv</span>(algorithm, key, iv);

    <span class="hljs-keyword">let</span> encrypted = cipher.<span class="hljs-title function_">update</span>(<span class="hljs-string">'some clear text data'</span>, <span class="hljs-string">'utf8'</span>, <span class="hljs-string">'hex'</span>);
    encrypted += cipher.<span class="hljs-title function_">final</span>(<span class="hljs-string">'hex'</span>);
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(encrypted);
  });
});</code><button class="copy-button">copy</button></pre>
<h4><code>cipher.final([outputEncoding])</code><span><a class="mark" href="#all_crypto_cipherfinaloutputencoding" id="all_crypto_cipherfinaloutputencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_cipher_final_outputencoding"></a></h4>
<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="#all_buffer_buffers-and-character-encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#all_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>
<h4><code>cipher.getAuthTag()</code><span><a class="mark" href="#all_crypto_ciphergetauthtag" id="all_crypto_ciphergetauthtag">#</a></span><a aria-hidden="true" class="legacy" id="crypto_cipher_getauthtag"></a></h4>
<div class="api_metadata">
<span>Added in: v1.0.0</span>
</div>
<ul>
<li>Returns: <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> When using an authenticated encryption mode (<code>GCM</code>, <code>CCM</code>,
<code>OCB</code>, and <code>chacha20-poly1305</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="#all_crypto_cipherfinaloutputencoding"><code>cipher.final()</code></a> method.</p>
<p>If the <code>authTagLength</code> option was set during the <code>cipher</code> instance's creation,
this function will return exactly <code>authTagLength</code> bytes.</p>
<h4><code>cipher.setAAD(buffer[, options])</code><span><a class="mark" href="#all_crypto_ciphersetaadbuffer-options" id="all_crypto_ciphersetaadbuffer-options">#</a></span><a aria-hidden="true" class="legacy" id="crypto_cipher_setaad_buffer_options"></a></h4>
<div class="api_metadata">
<span>Added in: v1.0.0</span>
</div>
<ul>
<li><code>buffer</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/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_stream_new-streamtransformoptions"><code>stream.transform</code> options</a>
<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>
<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 string encoding to use when <code>buffer</code> is a string.</li>
</ul>
</li>
<li>Returns: <a href="#all_crypto_class-cipher" class="type">&#x3C;Cipher></a> The same <code>Cipher</code> instance for method chaining.</li>
</ul>
<p>When using an authenticated encryption mode (<code>GCM</code>, <code>CCM</code>, <code>OCB</code>, and
<code>chacha20-poly1305</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>plaintextLength</code> option 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="#all_crypto_ccm-mode">CCM mode</a>.</p>
<p>The <code>cipher.setAAD()</code> method must be called before <a href="#all_crypto_cipherupdatedata-inputencoding-outputencoding"><code>cipher.update()</code></a>.</p>
<h4><code>cipher.setAutoPadding([autoPadding])</code><span><a class="mark" href="#all_crypto_ciphersetautopaddingautopadding" id="all_crypto_ciphersetautopaddingautopadding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_cipher_setautopadding_autopadding"></a></h4>
<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="#all_crypto_class-cipher" class="type">&#x3C;Cipher></a> The same <code>Cipher</code> instance 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="#all_crypto_cipherfinaloutputencoding"><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="#all_crypto_cipherfinaloutputencoding"><code>cipher.final()</code></a>.</p>
<h4><code>cipher.update(data[, inputEncoding][, outputEncoding])</code><span><a class="mark" href="#all_crypto_cipherupdatedata-inputencoding-outputencoding" id="all_crypto_cipherupdatedata-inputencoding-outputencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_cipher_update_data_inputencoding_outputencoding"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.0.0</td>
<td><p>The 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="#all_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="#all_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="#all_buffer_buffers-and-character-encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#all_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="#all_crypto_cipherfinaloutputencoding"><code>cipher.final()</code></a> is called. Calling <code>cipher.update()</code> after
<a href="#all_crypto_cipherfinaloutputencoding"><code>cipher.final()</code></a> will result in an error being thrown.</p>
</section><section><h3>Class: <code>Decipher</code><span><a class="mark" href="#all_crypto_class-decipher" id="all_crypto_class-decipher">#</a></span><a aria-hidden="true" class="legacy" id="crypto_class_decipher"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.94</span>
</div>
<ul>
<li>Extends: <a href="#all_stream_class-streamtransform" 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="#all_crypto_decipherupdatedata-inputencoding-outputencoding"><code>decipher.update()</code></a> and <a href="#all_crypto_decipherfinaloutputencoding"><code>decipher.final()</code></a> methods to
produce the unencrypted data.</li>
</ul>
<p>The <a href="#all_crypto_cryptocreatedecipheralgorithm-password-options"><code>crypto.createDecipher()</code></a> or <a href="#all_crypto_cryptocreatedecipherivalgorithm-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 class="with-37-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> {
  scryptSync,
  createDecipheriv,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

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

<span class="hljs-keyword">const</span> decipher = <span class="hljs-title function_">createDecipheriv</span>(algorithm, key, iv);

<span class="hljs-keyword">let</span> decrypted = <span class="hljs-string">''</span>;
decipher.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-keyword">let</span> chunk;
  <span class="hljs-keyword">while</span> (<span class="hljs-literal">null</span> !== (chunk = decipher.<span class="hljs-title function_">read</span>())) {
    decrypted += chunk.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'utf8'</span>);
  }
});
decipher.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(decrypted);
  <span class="hljs-comment">// Prints: some clear text data</span>
});

<span class="hljs-comment">// Encrypted with same algorithm, key and iv.</span>
<span class="hljs-keyword">const</span> encrypted =
  <span class="hljs-string">'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'</span>;
decipher.<span class="hljs-title function_">write</span>(encrypted, <span class="hljs-string">'hex'</span>);
decipher.<span class="hljs-title function_">end</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
  scryptSync,
  createDecipheriv,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

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

<span class="hljs-keyword">const</span> decipher = <span class="hljs-title function_">createDecipheriv</span>(algorithm, key, iv);

<span class="hljs-keyword">let</span> decrypted = <span class="hljs-string">''</span>;
decipher.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-keyword">let</span> chunk;
  <span class="hljs-keyword">while</span> (<span class="hljs-literal">null</span> !== (chunk = decipher.<span class="hljs-title function_">read</span>())) {
    decrypted += chunk.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'utf8'</span>);
  }
});
decipher.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(decrypted);
  <span class="hljs-comment">// Prints: some clear text data</span>
});

<span class="hljs-comment">// Encrypted with same algorithm, key and iv.</span>
<span class="hljs-keyword">const</span> encrypted =
  <span class="hljs-string">'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'</span>;
decipher.<span class="hljs-title function_">write</span>(encrypted, <span class="hljs-string">'hex'</span>);
decipher.<span class="hljs-title function_">end</span>();</code><button class="copy-button">copy</button></pre>
<p>Example: Using <code>Decipher</code> and piped streams:</p>

<pre class="with-19-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> {
  createReadStream,
  createWriteStream,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> {
  scryptSync,
  createDecipheriv,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> algorithm = <span class="hljs-string">'aes-192-cbc'</span>;
<span class="hljs-keyword">const</span> password = <span class="hljs-string">'Password used to generate key'</span>;
<span class="hljs-comment">// Use the async `crypto.scrypt()` instead.</span>
<span class="hljs-keyword">const</span> key = <span class="hljs-title function_">scryptSync</span>(password, <span class="hljs-string">'salt'</span>, <span class="hljs-number">24</span>);
<span class="hljs-comment">// The IV is usually passed along with the ciphertext.</span>
<span class="hljs-keyword">const</span> iv = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">16</span>, <span class="hljs-number">0</span>); <span class="hljs-comment">// Initialization vector.</span>

<span class="hljs-keyword">const</span> decipher = <span class="hljs-title function_">createDecipheriv</span>(algorithm, key, iv);

<span class="hljs-keyword">const</span> input = <span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'test.enc'</span>);
<span class="hljs-keyword">const</span> output = <span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'test.js'</span>);

input.<span class="hljs-title function_">pipe</span>(decipher).<span class="hljs-title function_">pipe</span>(output);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
  createReadStream,
  createWriteStream,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> {
  scryptSync,
  createDecipheriv,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> algorithm = <span class="hljs-string">'aes-192-cbc'</span>;
<span class="hljs-keyword">const</span> password = <span class="hljs-string">'Password used to generate key'</span>;
<span class="hljs-comment">// Use the async `crypto.scrypt()` instead.</span>
<span class="hljs-keyword">const</span> key = <span class="hljs-title function_">scryptSync</span>(password, <span class="hljs-string">'salt'</span>, <span class="hljs-number">24</span>);
<span class="hljs-comment">// The IV is usually passed along with the ciphertext.</span>
<span class="hljs-keyword">const</span> iv = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">16</span>, <span class="hljs-number">0</span>); <span class="hljs-comment">// Initialization vector.</span>

<span class="hljs-keyword">const</span> decipher = <span class="hljs-title function_">createDecipheriv</span>(algorithm, key, iv);

<span class="hljs-keyword">const</span> input = <span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'test.enc'</span>);
<span class="hljs-keyword">const</span> output = <span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'test.js'</span>);

input.<span class="hljs-title function_">pipe</span>(decipher).<span class="hljs-title function_">pipe</span>(output);</code><button class="copy-button">copy</button></pre>
<p>Example: Using the <a href="#all_crypto_decipherupdatedata-inputencoding-outputencoding"><code>decipher.update()</code></a> and <a href="#all_crypto_decipherfinaloutputencoding"><code>decipher.final()</code></a> methods:</p>

<pre class="with-37-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> {
  scryptSync,
  createDecipheriv,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> algorithm = <span class="hljs-string">'aes-192-cbc'</span>;
<span class="hljs-keyword">const</span> password = <span class="hljs-string">'Password used to generate key'</span>;
<span class="hljs-comment">// Use the async `crypto.scrypt()` instead.</span>
<span class="hljs-keyword">const</span> key = <span class="hljs-title function_">scryptSync</span>(password, <span class="hljs-string">'salt'</span>, <span class="hljs-number">24</span>);
<span class="hljs-comment">// The IV is usually passed along with the ciphertext.</span>
<span class="hljs-keyword">const</span> iv = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">16</span>, <span class="hljs-number">0</span>); <span class="hljs-comment">// Initialization vector.</span>

<span class="hljs-keyword">const</span> decipher = <span class="hljs-title function_">createDecipheriv</span>(algorithm, key, iv);

<span class="hljs-comment">// Encrypted using same algorithm, key and iv.</span>
<span class="hljs-keyword">const</span> encrypted =
  <span class="hljs-string">'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'</span>;
<span class="hljs-keyword">let</span> decrypted = decipher.<span class="hljs-title function_">update</span>(encrypted, <span class="hljs-string">'hex'</span>, <span class="hljs-string">'utf8'</span>);
decrypted += decipher.<span class="hljs-title function_">final</span>(<span class="hljs-string">'utf8'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(decrypted);
<span class="hljs-comment">// Prints: some clear text data</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
  scryptSync,
  createDecipheriv,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> algorithm = <span class="hljs-string">'aes-192-cbc'</span>;
<span class="hljs-keyword">const</span> password = <span class="hljs-string">'Password used to generate key'</span>;
<span class="hljs-comment">// Use the async `crypto.scrypt()` instead.</span>
<span class="hljs-keyword">const</span> key = <span class="hljs-title function_">scryptSync</span>(password, <span class="hljs-string">'salt'</span>, <span class="hljs-number">24</span>);
<span class="hljs-comment">// The IV is usually passed along with the ciphertext.</span>
<span class="hljs-keyword">const</span> iv = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">16</span>, <span class="hljs-number">0</span>); <span class="hljs-comment">// Initialization vector.</span>

<span class="hljs-keyword">const</span> decipher = <span class="hljs-title function_">createDecipheriv</span>(algorithm, key, iv);

<span class="hljs-comment">// Encrypted using same algorithm, key and iv.</span>
<span class="hljs-keyword">const</span> encrypted =
  <span class="hljs-string">'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'</span>;
<span class="hljs-keyword">let</span> decrypted = decipher.<span class="hljs-title function_">update</span>(encrypted, <span class="hljs-string">'hex'</span>, <span class="hljs-string">'utf8'</span>);
decrypted += decipher.<span class="hljs-title function_">final</span>(<span class="hljs-string">'utf8'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(decrypted);
<span class="hljs-comment">// Prints: some clear text data</span></code><button class="copy-button">copy</button></pre>
<h4><code>decipher.final([outputEncoding])</code><span><a class="mark" href="#all_crypto_decipherfinaloutputencoding" id="all_crypto_decipherfinaloutputencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_decipher_final_outputencoding"></a></h4>
<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="#all_buffer_buffers-and-character-encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#all_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>
<h4><code>decipher.setAAD(buffer[, options])</code><span><a class="mark" href="#all_crypto_deciphersetaadbuffer-options" id="all_crypto_deciphersetaadbuffer-options">#</a></span><a aria-hidden="true" class="legacy" id="crypto_decipher_setaad_buffer_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>The buffer argument can be a string or ArrayBuffer and is limited to no more than 2 ** 31 - 1 bytes.</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="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/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_stream_new-streamtransformoptions"><code>stream.transform</code> options</a>
<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>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> String encoding to use when <code>buffer</code> is a string.</li>
</ul>
</li>
<li>Returns: <a href="#all_crypto_class-decipher" class="type">&#x3C;Decipher></a> The same Decipher for method chaining.</li>
</ul>
<p>When using an authenticated encryption mode (<code>GCM</code>, <code>CCM</code>, <code>OCB</code>, and
<code>chacha20-poly1305</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="#all_crypto_ccm-mode">CCM mode</a>.</p>
<p>The <code>decipher.setAAD()</code> method must be called before <a href="#all_crypto_decipherupdatedata-inputencoding-outputencoding"><code>decipher.update()</code></a>.</p>
<p>When passing a string as the <code>buffer</code>, please consider
<a href="#all_crypto_using-strings-as-inputs-to-cryptographic-apis">caveats when using strings as inputs to cryptographic APIs</a>.</p>
<h4><code>decipher.setAuthTag(buffer[, encoding])</code><span><a class="mark" href="#all_crypto_deciphersetauthtagbuffer-encoding" id="all_crypto_deciphersetauthtagbuffer-encoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_decipher_setauthtag_buffer_encoding"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.13.0</td>
<td><p>Using GCM tag lengths other than 128 bits without specifying the <code>authTagLength</code> option when creating <code>decipher</code> is deprecated.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p>The buffer argument can be a string or ArrayBuffer and is limited to no more than 2 ** 31 - 1 bytes.</p></td></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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></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/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> String encoding to use when <code>buffer</code> is a string.</li>
<li>Returns: <a href="#all_crypto_class-decipher" class="type">&#x3C;Decipher></a> The same Decipher for method chaining.</li>
</ul>
<p>When using an authenticated encryption mode (<code>GCM</code>, <code>CCM</code>, <code>OCB</code>, and
<code>chacha20-poly1305</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="#all_crypto_decipherfinaloutputencoding"><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="#all_crypto_decipherupdatedata-inputencoding-outputencoding"><code>decipher.update()</code></a>
for <code>CCM</code> mode or before <a href="#all_crypto_decipherfinaloutputencoding"><code>decipher.final()</code></a> for <code>GCM</code> and <code>OCB</code> modes and
<code>chacha20-poly1305</code>.
<code>decipher.setAuthTag()</code> can only be called once.</p>
<p>When passing a string as the authentication tag, please consider
<a href="#all_crypto_using-strings-as-inputs-to-cryptographic-apis">caveats when using strings as inputs to cryptographic APIs</a>.</p>
<h4><code>decipher.setAutoPadding([autoPadding])</code><span><a class="mark" href="#all_crypto_deciphersetautopaddingautopadding" id="all_crypto_deciphersetautopaddingautopadding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_decipher_setautopadding_autopadding"></a></h4>
<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="#all_crypto_class-decipher" class="type">&#x3C;Decipher></a> The same Decipher 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="#all_crypto_decipherfinaloutputencoding"><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="#all_crypto_decipherfinaloutputencoding"><code>decipher.final()</code></a>.</p>
<h4><code>decipher.update(data[, inputEncoding][, outputEncoding])</code><span><a class="mark" href="#all_crypto_decipherupdatedata-inputencoding-outputencoding" id="all_crypto_decipherupdatedata-inputencoding-outputencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_decipher_update_data_inputencoding_outputencoding"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.0.0</td>
<td><p>The 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="#all_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="#all_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="#all_buffer_buffers-and-character-encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#all_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="#all_crypto_decipherfinaloutputencoding"><code>decipher.final()</code></a> is called. Calling <code>decipher.update()</code> after
<a href="#all_crypto_decipherfinaloutputencoding"><code>decipher.final()</code></a> will result in an error being thrown.</p>
<p>Even if the underlying cipher implements authentication, the authenticity and
integrity of the plaintext returned from this function may be uncertain at this
time. For authenticated encryption algorithms, authenticity is generally only
established when the application calls <a href="#all_crypto_decipherfinaloutputencoding"><code>decipher.final()</code></a>.</p>
</section><section><h3>Class: <code>DiffieHellman</code><span><a class="mark" href="#all_crypto_class-diffiehellman" id="all_crypto_class-diffiehellman">#</a></span><a aria-hidden="true" class="legacy" id="crypto_class_diffiehellman"></a></h3>
<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="#all_crypto_cryptocreatediffiehellmanprime-primeencoding-generator-generatorencoding"><code>crypto.createDiffieHellman()</code></a> function.</p>

<pre class="with-38-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;

<span class="hljs-keyword">const</span> {
  createDiffieHellman,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-comment">// Generate Alice's keys...</span>
<span class="hljs-keyword">const</span> alice = <span class="hljs-title function_">createDiffieHellman</span>(<span class="hljs-number">2048</span>);
<span class="hljs-keyword">const</span> aliceKey = alice.<span class="hljs-title function_">generateKeys</span>();

<span class="hljs-comment">// Generate Bob's keys...</span>
<span class="hljs-keyword">const</span> bob = <span class="hljs-title function_">createDiffieHellman</span>(alice.<span class="hljs-title function_">getPrime</span>(), alice.<span class="hljs-title function_">getGenerator</span>());
<span class="hljs-keyword">const</span> bobKey = bob.<span class="hljs-title function_">generateKeys</span>();

<span class="hljs-comment">// Exchange and generate the secret...</span>
<span class="hljs-keyword">const</span> aliceSecret = alice.<span class="hljs-title function_">computeSecret</span>(bobKey);
<span class="hljs-keyword">const</span> bobSecret = bob.<span class="hljs-title function_">computeSecret</span>(aliceKey);

<span class="hljs-comment">// OK</span>
assert.<span class="hljs-title function_">strictEqual</span>(aliceSecret.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>), bobSecret.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);

<span class="hljs-keyword">const</span> {
  createDiffieHellman,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-comment">// Generate Alice's keys...</span>
<span class="hljs-keyword">const</span> alice = <span class="hljs-title function_">createDiffieHellman</span>(<span class="hljs-number">2048</span>);
<span class="hljs-keyword">const</span> aliceKey = alice.<span class="hljs-title function_">generateKeys</span>();

<span class="hljs-comment">// Generate Bob's keys...</span>
<span class="hljs-keyword">const</span> bob = <span class="hljs-title function_">createDiffieHellman</span>(alice.<span class="hljs-title function_">getPrime</span>(), alice.<span class="hljs-title function_">getGenerator</span>());
<span class="hljs-keyword">const</span> bobKey = bob.<span class="hljs-title function_">generateKeys</span>();

<span class="hljs-comment">// Exchange and generate the secret...</span>
<span class="hljs-keyword">const</span> aliceSecret = alice.<span class="hljs-title function_">computeSecret</span>(bobKey);
<span class="hljs-keyword">const</span> bobSecret = bob.<span class="hljs-title function_">computeSecret</span>(aliceKey);

<span class="hljs-comment">// OK</span>
assert.<span class="hljs-title function_">strictEqual</span>(aliceSecret.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>), bobSecret.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));</code><button class="copy-button">copy</button></pre>
<h4><code>diffieHellman.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])</code><span><a class="mark" href="#all_crypto_diffiehellmancomputesecretotherpublickey-inputencoding-outputencoding" id="all_crypto_diffiehellmancomputesecretotherpublickey-inputencoding-outputencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_diffiehellman_computesecret_otherpublickey_inputencoding_outputencoding"></a></h4>
<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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_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="#all_buffer_buffers-and-character-encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#all_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>
<h4><code>diffieHellman.generateKeys([encoding])</code><span><a class="mark" href="#all_crypto_diffiehellmangeneratekeysencoding" id="all_crypto_diffiehellmangeneratekeysencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_diffiehellman_generatekeys_encoding"></a></h4>
<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="#all_buffer_buffers-and-character-encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#all_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 unless they have been
generated or computed already, 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>
<p>This function is a thin wrapper around <a href="https://www.openssl.org/docs/man3.0/man3/DH_generate_key.html"><code>DH_generate_key()</code></a>. In particular,
once a private key has been generated or set, calling this function only updates
the public key but does not generate a new private key.</p>
<h4><code>diffieHellman.getGenerator([encoding])</code><span><a class="mark" href="#all_crypto_diffiehellmangetgeneratorencoding" id="all_crypto_diffiehellmangetgeneratorencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_diffiehellman_getgenerator_encoding"></a></h4>
<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="#all_buffer_buffers-and-character-encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#all_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>
<h4><code>diffieHellman.getPrime([encoding])</code><span><a class="mark" href="#all_crypto_diffiehellmangetprimeencoding" id="all_crypto_diffiehellmangetprimeencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_diffiehellman_getprime_encoding"></a></h4>
<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="#all_buffer_buffers-and-character-encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#all_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>
<h4><code>diffieHellman.getPrivateKey([encoding])</code><span><a class="mark" href="#all_crypto_diffiehellmangetprivatekeyencoding" id="all_crypto_diffiehellmangetprivatekeyencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_diffiehellman_getprivatekey_encoding"></a></h4>
<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="#all_buffer_buffers-and-character-encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#all_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>
<h4><code>diffieHellman.getPublicKey([encoding])</code><span><a class="mark" href="#all_crypto_diffiehellmangetpublickeyencoding" id="all_crypto_diffiehellmangetpublickeyencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_diffiehellman_getpublickey_encoding"></a></h4>
<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="#all_buffer_buffers-and-character-encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#all_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>
<h4><code>diffieHellman.setPrivateKey(privateKey[, encoding])</code><span><a class="mark" href="#all_crypto_diffiehellmansetprivatekeyprivatekey-encoding" id="all_crypto_diffiehellmansetprivatekeyprivatekey-encoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_diffiehellman_setprivatekey_privatekey_encoding"></a></h4>
<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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_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>
<p>This function does not automatically compute the associated public key. Either
<a href="#all_crypto_diffiehellmansetpublickeypublickey-encoding"><code>diffieHellman.setPublicKey()</code></a> or <a href="#all_crypto_diffiehellmangeneratekeysencoding"><code>diffieHellman.generateKeys()</code></a> can be
used to manually provide the public key or to automatically derive it.</p>
<h4><code>diffieHellman.setPublicKey(publicKey[, encoding])</code><span><a class="mark" href="#all_crypto_diffiehellmansetpublickeypublickey-encoding" id="all_crypto_diffiehellmansetpublickeypublickey-encoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_diffiehellman_setpublickey_publickey_encoding"></a></h4>
<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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_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>
<h4><code>diffieHellman.verifyError</code><span><a class="mark" href="#all_crypto_diffiehellmanverifyerror" id="all_crypto_diffiehellmanverifyerror">#</a></span><a aria-hidden="true" class="legacy" id="crypto_diffiehellman_verifyerror"></a></h4>
<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>node: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>
</section><section><h3>Class: <code>DiffieHellmanGroup</code><span><a class="mark" href="#all_crypto_class-diffiehellmangroup" id="all_crypto_class-diffiehellmangroup">#</a></span><a aria-hidden="true" class="legacy" id="crypto_class_diffiehellmangroup"></a></h3>
<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.
It works the same as <code>DiffieHellman</code>, except that it does not allow changing
its keys after creation. In other words, it does not implement <code>setPublicKey()</code>
or <code>setPrivateKey()</code> methods.</p>

<pre class="with-65-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">const</span> { createDiffieHellmanGroup } = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> dh = <span class="hljs-title function_">createDiffieHellmanGroup</span>(<span class="hljs-string">'modp16'</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { createDiffieHellmanGroup } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> dh = <span class="hljs-title function_">createDiffieHellmanGroup</span>(<span class="hljs-string">'modp16'</span>);</code><button class="copy-button">copy</button></pre>
<p>The following groups are supported:</p>
<ul>
<li><code>'modp14'</code> (2048 bits, <a href="https://www.rfc-editor.org/rfc/rfc3526.txt">RFC 3526</a> Section 3)</li>
<li><code>'modp15'</code> (3072 bits, <a href="https://www.rfc-editor.org/rfc/rfc3526.txt">RFC 3526</a> Section 4)</li>
<li><code>'modp16'</code> (4096 bits, <a href="https://www.rfc-editor.org/rfc/rfc3526.txt">RFC 3526</a> Section 5)</li>
<li><code>'modp17'</code> (6144 bits, <a href="https://www.rfc-editor.org/rfc/rfc3526.txt">RFC 3526</a> Section 6)</li>
<li><code>'modp18'</code> (8192 bits, <a href="https://www.rfc-editor.org/rfc/rfc3526.txt">RFC 3526</a> Section 7)</li>
</ul>
<p>The following groups are still supported but deprecated (see <a href="#all_crypto_support-for-weak-or-compromised-algorithms">Caveats</a>):</p>
<ul>
<li><code>'modp1'</code> (768 bits, <a href="https://www.rfc-editor.org/rfc/rfc2409.txt">RFC 2409</a> Section 6.1) <span class="deprecated-inline"></span></li>
<li><code>'modp2'</code> (1024 bits, <a href="https://www.rfc-editor.org/rfc/rfc2409.txt">RFC 2409</a> Section 6.2) <span class="deprecated-inline"></span></li>
<li><code>'modp5'</code> (1536 bits, <a href="https://www.rfc-editor.org/rfc/rfc3526.txt">RFC 3526</a> Section 2) <span class="deprecated-inline"></span></li>
</ul>
<p>These deprecated groups might be removed in future versions of Node.js.</p>
</section><section><h3>Class: <code>ECDH</code><span><a class="mark" href="#all_crypto_class-ecdh" id="all_crypto_class-ecdh">#</a></span><a aria-hidden="true" class="legacy" id="crypto_class_ecdh"></a></h3>
<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="#all_crypto_cryptocreateecdhcurvename"><code>crypto.createECDH()</code></a> function.</p>

<pre class="with-38-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;

<span class="hljs-keyword">const</span> {
  createECDH,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-comment">// Generate Alice's keys...</span>
<span class="hljs-keyword">const</span> alice = <span class="hljs-title function_">createECDH</span>(<span class="hljs-string">'secp521r1'</span>);
<span class="hljs-keyword">const</span> aliceKey = alice.<span class="hljs-title function_">generateKeys</span>();

<span class="hljs-comment">// Generate Bob's keys...</span>
<span class="hljs-keyword">const</span> bob = <span class="hljs-title function_">createECDH</span>(<span class="hljs-string">'secp521r1'</span>);
<span class="hljs-keyword">const</span> bobKey = bob.<span class="hljs-title function_">generateKeys</span>();

<span class="hljs-comment">// Exchange and generate the secret...</span>
<span class="hljs-keyword">const</span> aliceSecret = alice.<span class="hljs-title function_">computeSecret</span>(bobKey);
<span class="hljs-keyword">const</span> bobSecret = bob.<span class="hljs-title function_">computeSecret</span>(aliceKey);

assert.<span class="hljs-title function_">strictEqual</span>(aliceSecret.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>), bobSecret.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// OK</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);

<span class="hljs-keyword">const</span> {
  createECDH,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-comment">// Generate Alice's keys...</span>
<span class="hljs-keyword">const</span> alice = <span class="hljs-title function_">createECDH</span>(<span class="hljs-string">'secp521r1'</span>);
<span class="hljs-keyword">const</span> aliceKey = alice.<span class="hljs-title function_">generateKeys</span>();

<span class="hljs-comment">// Generate Bob's keys...</span>
<span class="hljs-keyword">const</span> bob = <span class="hljs-title function_">createECDH</span>(<span class="hljs-string">'secp521r1'</span>);
<span class="hljs-keyword">const</span> bobKey = bob.<span class="hljs-title function_">generateKeys</span>();

<span class="hljs-comment">// Exchange and generate the secret...</span>
<span class="hljs-keyword">const</span> aliceSecret = alice.<span class="hljs-title function_">computeSecret</span>(bobKey);
<span class="hljs-keyword">const</span> bobSecret = bob.<span class="hljs-title function_">computeSecret</span>(aliceKey);

assert.<span class="hljs-title function_">strictEqual</span>(aliceSecret.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>), bobSecret.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// OK</span></code><button class="copy-button">copy</button></pre>
<h4>Static method: <code>ECDH.convertKey(key, curve[, inputEncoding[, outputEncoding[, format]]])</code><span><a class="mark" href="#all_crypto_static-method-ecdhconvertkeykey-curve-inputencoding-outputencoding-format" id="all_crypto_static-method-ecdhconvertkeykey-curve-inputencoding-outputencoding-format">#</a></span><a aria-hidden="true" class="legacy" id="crypto_static_method_ecdh_convertkey_key_curve_inputencoding_outputencoding_format"></a></h4>
<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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_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="#all_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="#all_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="#all_crypto_cryptogetcurves"><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 class="with-13-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">const</span> {
  createECDH,
  <span class="hljs-variable constant_">ECDH</span>,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> ecdh = <span class="hljs-title function_">createECDH</span>(<span class="hljs-string">'secp256k1'</span>);
ecdh.<span class="hljs-title function_">generateKeys</span>();

<span class="hljs-keyword">const</span> compressedKey = ecdh.<span class="hljs-title function_">getPublicKey</span>(<span class="hljs-string">'hex'</span>, <span class="hljs-string">'compressed'</span>);

<span class="hljs-keyword">const</span> uncompressedKey = <span class="hljs-variable constant_">ECDH</span>.<span class="hljs-title function_">convertKey</span>(compressedKey,
                                        <span class="hljs-string">'secp256k1'</span>,
                                        <span class="hljs-string">'hex'</span>,
                                        <span class="hljs-string">'hex'</span>,
                                        <span class="hljs-string">'uncompressed'</span>);

<span class="hljs-comment">// The converted key and the uncompressed public key should be the same</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(uncompressedKey === ecdh.<span class="hljs-title function_">getPublicKey</span>(<span class="hljs-string">'hex'</span>));</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
  createECDH,
  <span class="hljs-variable constant_">ECDH</span>,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> ecdh = <span class="hljs-title function_">createECDH</span>(<span class="hljs-string">'secp256k1'</span>);
ecdh.<span class="hljs-title function_">generateKeys</span>();

<span class="hljs-keyword">const</span> compressedKey = ecdh.<span class="hljs-title function_">getPublicKey</span>(<span class="hljs-string">'hex'</span>, <span class="hljs-string">'compressed'</span>);

<span class="hljs-keyword">const</span> uncompressedKey = <span class="hljs-variable constant_">ECDH</span>.<span class="hljs-title function_">convertKey</span>(compressedKey,
                                        <span class="hljs-string">'secp256k1'</span>,
                                        <span class="hljs-string">'hex'</span>,
                                        <span class="hljs-string">'hex'</span>,
                                        <span class="hljs-string">'uncompressed'</span>);

<span class="hljs-comment">// The converted key and the uncompressed public key should be the same</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(uncompressedKey === ecdh.<span class="hljs-title function_">getPublicKey</span>(<span class="hljs-string">'hex'</span>));</code><button class="copy-button">copy</button></pre>
<h4><code>ecdh.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])</code><span><a class="mark" href="#all_crypto_ecdhcomputesecretotherpublickey-inputencoding-outputencoding" id="all_crypto_ecdhcomputesecretotherpublickey-inputencoding-outputencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_ecdh_computesecret_otherpublickey_inputencoding_outputencoding"></a></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>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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_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="#all_buffer_buffers-and-character-encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#all_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,
be sure to handle this exception accordingly.</p>
<h4><code>ecdh.generateKeys([encoding[, format]])</code><span><a class="mark" href="#all_crypto_ecdhgeneratekeysencoding-format" id="all_crypto_ecdhgeneratekeysencoding-format">#</a></span><a aria-hidden="true" class="legacy" id="crypto_ecdh_generatekeys_encoding_format"></a></h4>
<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="#all_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="#all_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>
<h4><code>ecdh.getPrivateKey([encoding])</code><span><a class="mark" href="#all_crypto_ecdhgetprivatekeyencoding" id="all_crypto_ecdhgetprivatekeyencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_ecdh_getprivatekey_encoding"></a></h4>
<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="#all_buffer_buffers-and-character-encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#all_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>
<h4><code>ecdh.getPublicKey([encoding][, format])</code><span><a class="mark" href="#all_crypto_ecdhgetpublickeyencoding-format" id="all_crypto_ecdhgetpublickeyencoding-format">#</a></span><a aria-hidden="true" class="legacy" id="crypto_ecdh_getpublickey_encoding_format"></a></h4>
<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="#all_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="#all_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>
<h4><code>ecdh.setPrivateKey(privateKey[, encoding])</code><span><a class="mark" href="#all_crypto_ecdhsetprivatekeyprivatekey-encoding" id="all_crypto_ecdhsetprivatekeyprivatekey-encoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_ecdh_setprivatekey_privatekey_encoding"></a></h4>
<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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_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>
<h4><code>ecdh.setPublicKey(publicKey[, encoding])</code><span><a class="mark" href="#all_crypto_ecdhsetpublickeypublickey-encoding" id="all_crypto_ecdhsetpublickeypublickey-encoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_ecdh_setpublickey_publickey_encoding"></a></h4>
<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="#all_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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_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="#all_crypto_ecdhgeneratekeysencoding-format"><code>ecdh.generateKeys()</code></a> or
<a href="#all_crypto_ecdhsetprivatekeyprivatekey-encoding"><code>ecdh.setPrivateKey()</code></a> will be called. The <a href="#all_crypto_ecdhsetprivatekeyprivatekey-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 class="with-13-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">const</span> {
  createECDH,
  createHash,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> alice = <span class="hljs-title function_">createECDH</span>(<span class="hljs-string">'secp256k1'</span>);
<span class="hljs-keyword">const</span> bob = <span class="hljs-title function_">createECDH</span>(<span class="hljs-string">'secp256k1'</span>);

<span class="hljs-comment">// This is a shortcut way of specifying one of Alice's previous private</span>
<span class="hljs-comment">// keys. It would be unwise to use such a predictable private key in a real</span>
<span class="hljs-comment">// application.</span>
alice.<span class="hljs-title function_">setPrivateKey</span>(
  <span class="hljs-title function_">createHash</span>(<span class="hljs-string">'sha256'</span>).<span class="hljs-title function_">update</span>(<span class="hljs-string">'alice'</span>, <span class="hljs-string">'utf8'</span>).<span class="hljs-title function_">digest</span>(),
);

<span class="hljs-comment">// Bob uses a newly generated cryptographically strong</span>
<span class="hljs-comment">// pseudorandom key pair</span>
bob.<span class="hljs-title function_">generateKeys</span>();

<span class="hljs-keyword">const</span> aliceSecret = alice.<span class="hljs-title function_">computeSecret</span>(bob.<span class="hljs-title function_">getPublicKey</span>(), <span class="hljs-literal">null</span>, <span class="hljs-string">'hex'</span>);
<span class="hljs-keyword">const</span> bobSecret = bob.<span class="hljs-title function_">computeSecret</span>(alice.<span class="hljs-title function_">getPublicKey</span>(), <span class="hljs-literal">null</span>, <span class="hljs-string">'hex'</span>);

<span class="hljs-comment">// aliceSecret and bobSecret should be the same shared secret value</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(aliceSecret === bobSecret);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
  createECDH,
  createHash,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> alice = <span class="hljs-title function_">createECDH</span>(<span class="hljs-string">'secp256k1'</span>);
<span class="hljs-keyword">const</span> bob = <span class="hljs-title function_">createECDH</span>(<span class="hljs-string">'secp256k1'</span>);

<span class="hljs-comment">// This is a shortcut way of specifying one of Alice's previous private</span>
<span class="hljs-comment">// keys. It would be unwise to use such a predictable private key in a real</span>
<span class="hljs-comment">// application.</span>
alice.<span class="hljs-title function_">setPrivateKey</span>(
  <span class="hljs-title function_">createHash</span>(<span class="hljs-string">'sha256'</span>).<span class="hljs-title function_">update</span>(<span class="hljs-string">'alice'</span>, <span class="hljs-string">'utf8'</span>).<span class="hljs-title function_">digest</span>(),
);

<span class="hljs-comment">// Bob uses a newly generated cryptographically strong</span>
<span class="hljs-comment">// pseudorandom key pair</span>
bob.<span class="hljs-title function_">generateKeys</span>();

<span class="hljs-keyword">const</span> aliceSecret = alice.<span class="hljs-title function_">computeSecret</span>(bob.<span class="hljs-title function_">getPublicKey</span>(), <span class="hljs-literal">null</span>, <span class="hljs-string">'hex'</span>);
<span class="hljs-keyword">const</span> bobSecret = bob.<span class="hljs-title function_">computeSecret</span>(alice.<span class="hljs-title function_">getPublicKey</span>(), <span class="hljs-literal">null</span>, <span class="hljs-string">'hex'</span>);

<span class="hljs-comment">// aliceSecret and bobSecret should be the same shared secret value</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(aliceSecret === bobSecret);</code><button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>Hash</code><span><a class="mark" href="#all_crypto_class-hash" id="all_crypto_class-hash">#</a></span><a aria-hidden="true" class="legacy" id="crypto_class_hash"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.92</span>
</div>
<ul>
<li>Extends: <a href="#all_stream_class-streamtransform" 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="#all_crypto_hashupdatedata-inputencoding"><code>hash.update()</code></a> and <a href="#all_crypto_hashdigestencoding"><code>hash.digest()</code></a> methods to produce the
computed hash.</li>
</ul>
<p>The <a href="#all_crypto_cryptocreatehashalgorithm-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 class="with-13-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">const</span> {
  createHash,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> hash = <span class="hljs-title function_">createHash</span>(<span class="hljs-string">'sha256'</span>);

hash.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-comment">// Only one element is going to be produced by the</span>
  <span class="hljs-comment">// hash stream.</span>
  <span class="hljs-keyword">const</span> data = hash.<span class="hljs-title function_">read</span>();
  <span class="hljs-keyword">if</span> (data) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
    <span class="hljs-comment">// Prints:</span>
    <span class="hljs-comment">//   6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50</span>
  }
});

hash.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some data to hash'</span>);
hash.<span class="hljs-title function_">end</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
  createHash,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> hash = <span class="hljs-title function_">createHash</span>(<span class="hljs-string">'sha256'</span>);

hash.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-comment">// Only one element is going to be produced by the</span>
  <span class="hljs-comment">// hash stream.</span>
  <span class="hljs-keyword">const</span> data = hash.<span class="hljs-title function_">read</span>();
  <span class="hljs-keyword">if</span> (data) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
    <span class="hljs-comment">// Prints:</span>
    <span class="hljs-comment">//   6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50</span>
  }
});

hash.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some data to hash'</span>);
hash.<span class="hljs-title function_">end</span>();</code><button class="copy-button">copy</button></pre>
<p>Example: Using <code>Hash</code> and piped streams:</p>

<pre class="with-48-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createReadStream } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">import</span> { stdout } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">const</span> { createHash } = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> hash = <span class="hljs-title function_">createHash</span>(<span class="hljs-string">'sha256'</span>);

<span class="hljs-keyword">const</span> input = <span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'test.js'</span>);
input.<span class="hljs-title function_">pipe</span>(hash).<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'hex'</span>).<span class="hljs-title function_">pipe</span>(stdout);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { createReadStream } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> { createHash } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> { stdout } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-keyword">const</span> hash = <span class="hljs-title function_">createHash</span>(<span class="hljs-string">'sha256'</span>);

<span class="hljs-keyword">const</span> input = <span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'test.js'</span>);
input.<span class="hljs-title function_">pipe</span>(hash).<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'hex'</span>).<span class="hljs-title function_">pipe</span>(stdout);</code><button class="copy-button">copy</button></pre>
<p>Example: Using the <a href="#all_crypto_hashupdatedata-inputencoding"><code>hash.update()</code></a> and <a href="#all_crypto_hashdigestencoding"><code>hash.digest()</code></a> methods:</p>

<pre class="with-13-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">const</span> {
  createHash,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> hash = <span class="hljs-title function_">createHash</span>(<span class="hljs-string">'sha256'</span>);

hash.<span class="hljs-title function_">update</span>(<span class="hljs-string">'some data to hash'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(hash.<span class="hljs-title function_">digest</span>(<span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
  createHash,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> hash = <span class="hljs-title function_">createHash</span>(<span class="hljs-string">'sha256'</span>);

hash.<span class="hljs-title function_">update</span>(<span class="hljs-string">'some data to hash'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(hash.<span class="hljs-title function_">digest</span>(<span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50</span></code><button class="copy-button">copy</button></pre>
<h4><code>hash.copy([options])</code><span><a class="mark" href="#all_crypto_hashcopyoptions" id="all_crypto_hashcopyoptions">#</a></span><a aria-hidden="true" class="legacy" id="crypto_hash_copy_options"></a></h4>
<div class="api_metadata">
<span>Added in: v13.1.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="#all_stream_new-streamtransformoptions"><code>stream.transform</code> options</a></li>
<li>Returns: <a href="#all_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="#all_crypto_hashdigestencoding"><code>hash.digest()</code></a> method has been called.</p>

<pre class="with-28-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// Calculate a rolling hash.</span>
<span class="hljs-keyword">const</span> {
  createHash,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> hash = <span class="hljs-title function_">createHash</span>(<span class="hljs-string">'sha256'</span>);

hash.<span class="hljs-title function_">update</span>(<span class="hljs-string">'one'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(hash.<span class="hljs-title function_">copy</span>().<span class="hljs-title function_">digest</span>(<span class="hljs-string">'hex'</span>));

hash.<span class="hljs-title function_">update</span>(<span class="hljs-string">'two'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(hash.<span class="hljs-title function_">copy</span>().<span class="hljs-title function_">digest</span>(<span class="hljs-string">'hex'</span>));

hash.<span class="hljs-title function_">update</span>(<span class="hljs-string">'three'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(hash.<span class="hljs-title function_">copy</span>().<span class="hljs-title function_">digest</span>(<span class="hljs-string">'hex'</span>));

<span class="hljs-comment">// Etc.</span></code><code class="language-js cjs"><span class="hljs-comment">// Calculate a rolling hash.</span>
<span class="hljs-keyword">const</span> {
  createHash,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> hash = <span class="hljs-title function_">createHash</span>(<span class="hljs-string">'sha256'</span>);

hash.<span class="hljs-title function_">update</span>(<span class="hljs-string">'one'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(hash.<span class="hljs-title function_">copy</span>().<span class="hljs-title function_">digest</span>(<span class="hljs-string">'hex'</span>));

hash.<span class="hljs-title function_">update</span>(<span class="hljs-string">'two'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(hash.<span class="hljs-title function_">copy</span>().<span class="hljs-title function_">digest</span>(<span class="hljs-string">'hex'</span>));

hash.<span class="hljs-title function_">update</span>(<span class="hljs-string">'three'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(hash.<span class="hljs-title function_">copy</span>().<span class="hljs-title function_">digest</span>(<span class="hljs-string">'hex'</span>));

<span class="hljs-comment">// Etc.</span></code><button class="copy-button">copy</button></pre>
<h4><code>hash.digest([encoding])</code><span><a class="mark" href="#all_crypto_hashdigestencoding" id="all_crypto_hashdigestencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_hash_digest_encoding"></a></h4>
<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="#all_buffer_buffers-and-character-encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#all_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="#all_crypto_hashupdatedata-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>
<h4><code>hash.update(data[, inputEncoding])</code><span><a class="mark" href="#all_crypto_hashupdatedata-inputencoding" id="all_crypto_hashupdatedata-inputencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_hash_update_data_inputencoding"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.0.0</td>
<td><p>The 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="#all_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="#all_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>
</section><section><h3>Class: <code>Hmac</code><span><a class="mark" href="#all_crypto_class-hmac" id="all_crypto_class-hmac">#</a></span><a aria-hidden="true" class="legacy" id="crypto_class_hmac"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.94</span>
</div>
<ul>
<li>Extends: <a href="#all_stream_class-streamtransform" 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="#all_crypto_hmacupdatedata-inputencoding"><code>hmac.update()</code></a> and <a href="#all_crypto_hmacdigestencoding"><code>hmac.digest()</code></a> methods to produce the
computed HMAC digest.</li>
</ul>
<p>The <a href="#all_crypto_cryptocreatehmacalgorithm-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 class="with-13-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">const</span> {
  createHmac,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> hmac = <span class="hljs-title function_">createHmac</span>(<span class="hljs-string">'sha256'</span>, <span class="hljs-string">'a secret'</span>);

hmac.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-comment">// Only one element is going to be produced by the</span>
  <span class="hljs-comment">// hash stream.</span>
  <span class="hljs-keyword">const</span> data = hmac.<span class="hljs-title function_">read</span>();
  <span class="hljs-keyword">if</span> (data) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
    <span class="hljs-comment">// Prints:</span>
    <span class="hljs-comment">//   7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e</span>
  }
});

hmac.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some data to hash'</span>);
hmac.<span class="hljs-title function_">end</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
  createHmac,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> hmac = <span class="hljs-title function_">createHmac</span>(<span class="hljs-string">'sha256'</span>, <span class="hljs-string">'a secret'</span>);

hmac.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-comment">// Only one element is going to be produced by the</span>
  <span class="hljs-comment">// hash stream.</span>
  <span class="hljs-keyword">const</span> data = hmac.<span class="hljs-title function_">read</span>();
  <span class="hljs-keyword">if</span> (data) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
    <span class="hljs-comment">// Prints:</span>
    <span class="hljs-comment">//   7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e</span>
  }
});

hmac.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some data to hash'</span>);
hmac.<span class="hljs-title function_">end</span>();</code><button class="copy-button">copy</button></pre>
<p>Example: Using <code>Hmac</code> and piped streams:</p>

<pre class="with-43-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createReadStream } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">import</span> { stdout } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">const</span> {
  createHmac,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> hmac = <span class="hljs-title function_">createHmac</span>(<span class="hljs-string">'sha256'</span>, <span class="hljs-string">'a secret'</span>);

<span class="hljs-keyword">const</span> input = <span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'test.js'</span>);
input.<span class="hljs-title function_">pipe</span>(hmac).<span class="hljs-title function_">pipe</span>(stdout);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
  createReadStream,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> {
  createHmac,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> { stdout } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-keyword">const</span> hmac = <span class="hljs-title function_">createHmac</span>(<span class="hljs-string">'sha256'</span>, <span class="hljs-string">'a secret'</span>);

<span class="hljs-keyword">const</span> input = <span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'test.js'</span>);
input.<span class="hljs-title function_">pipe</span>(hmac).<span class="hljs-title function_">pipe</span>(stdout);</code><button class="copy-button">copy</button></pre>
<p>Example: Using the <a href="#all_crypto_hmacupdatedata-inputencoding"><code>hmac.update()</code></a> and <a href="#all_crypto_hmacdigestencoding"><code>hmac.digest()</code></a> methods:</p>

<pre class="with-13-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">const</span> {
  createHmac,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> hmac = <span class="hljs-title function_">createHmac</span>(<span class="hljs-string">'sha256'</span>, <span class="hljs-string">'a secret'</span>);

hmac.<span class="hljs-title function_">update</span>(<span class="hljs-string">'some data to hash'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(hmac.<span class="hljs-title function_">digest</span>(<span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
  createHmac,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> hmac = <span class="hljs-title function_">createHmac</span>(<span class="hljs-string">'sha256'</span>, <span class="hljs-string">'a secret'</span>);

hmac.<span class="hljs-title function_">update</span>(<span class="hljs-string">'some data to hash'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(hmac.<span class="hljs-title function_">digest</span>(<span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e</span></code><button class="copy-button">copy</button></pre>
<h4><code>hmac.digest([encoding])</code><span><a class="mark" href="#all_crypto_hmacdigestencoding" id="all_crypto_hmacdigestencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_hmac_digest_encoding"></a></h4>
<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="#all_buffer_buffers-and-character-encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#all_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="#all_crypto_hmacupdatedata-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>
<h4><code>hmac.update(data[, inputEncoding])</code><span><a class="mark" href="#all_crypto_hmacupdatedata-inputencoding" id="all_crypto_hmacupdatedata-inputencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_hmac_update_data_inputencoding"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.0.0</td>
<td><p>The 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="#all_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="#all_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>
</section><section><h3>Class: <code>KeyObject</code><span><a class="mark" href="#all_crypto_class-keyobject" id="all_crypto_class-keyobject">#</a></span><a aria-hidden="true" class="legacy" id="crypto_class_keyobject"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.5.0, v12.19.0</td>
<td><p>Instances of this class can now be passed to worker threads using <code>postMessage</code>.</p></td></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="#all_crypto_cryptocreatesecretkeykey-encoding"><code>crypto.createSecretKey()</code></a>, <a href="#all_crypto_cryptocreatepublickeykey"><code>crypto.createPublicKey()</code></a> and
<a href="#all_crypto_cryptocreateprivatekeykey"><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>
<p><code>KeyObject</code> instances can be passed to other threads via <a href="#all_worker_threads_portpostmessagevalue-transferlist"><code>postMessage()</code></a>.
The receiver obtains a cloned <code>KeyObject</code>, and the <code>KeyObject</code> does not need to
be listed in the <code>transferList</code> argument.</p>
<h4>Static method: <code>KeyObject.from(key)</code><span><a class="mark" href="#all_crypto_static-method-keyobjectfromkey" id="all_crypto_static-method-keyobjectfromkey">#</a></span><a aria-hidden="true" class="legacy" id="crypto_static_method_keyobject_from_key"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li><code>key</code> <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></a></li>
<li>Returns: <a href="#all_crypto_class-keyobject" class="type">&#x3C;KeyObject></a></li>
</ul>
<p>Example: Converting a <code>CryptoKey</code> instance to a <code>KeyObject</code>:</p>

<pre class="with-50-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">KeyObject</span> } = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> { subtle } = globalThis.<span class="hljs-property">crypto</span>;

<span class="hljs-keyword">const</span> key = <span class="hljs-keyword">await</span> subtle.<span class="hljs-title function_">generateKey</span>({
  <span class="hljs-attr">name</span>: <span class="hljs-string">'HMAC'</span>,
  <span class="hljs-attr">hash</span>: <span class="hljs-string">'SHA-256'</span>,
  <span class="hljs-attr">length</span>: <span class="hljs-number">256</span>,
}, <span class="hljs-literal">true</span>, [<span class="hljs-string">'sign'</span>, <span class="hljs-string">'verify'</span>]);

<span class="hljs-keyword">const</span> keyObject = <span class="hljs-title class_">KeyObject</span>.<span class="hljs-title function_">from</span>(key);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(keyObject.<span class="hljs-property">symmetricKeySize</span>);
<span class="hljs-comment">// Prints: 32 (symmetric key size in bytes)</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">KeyObject</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> { subtle } = globalThis.<span class="hljs-property">crypto</span>;

(<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">const</span> key = <span class="hljs-keyword">await</span> subtle.<span class="hljs-title function_">generateKey</span>({
    <span class="hljs-attr">name</span>: <span class="hljs-string">'HMAC'</span>,
    <span class="hljs-attr">hash</span>: <span class="hljs-string">'SHA-256'</span>,
    <span class="hljs-attr">length</span>: <span class="hljs-number">256</span>,
  }, <span class="hljs-literal">true</span>, [<span class="hljs-string">'sign'</span>, <span class="hljs-string">'verify'</span>]);

  <span class="hljs-keyword">const</span> keyObject = <span class="hljs-title class_">KeyObject</span>.<span class="hljs-title function_">from</span>(key);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(keyObject.<span class="hljs-property">symmetricKeySize</span>);
  <span class="hljs-comment">// Prints: 32 (symmetric key size in bytes)</span>
})();</code><button class="copy-button">copy</button></pre>
<h4><code>keyObject.asymmetricKeyDetails</code><span><a class="mark" href="#all_crypto_keyobjectasymmetrickeydetails" id="all_crypto_keyobjectasymmetrickeydetails">#</a></span><a aria-hidden="true" class="legacy" id="crypto_keyobject_asymmetrickeydetails"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.9.0</td>
<td><p>Expose <code>RSASSA-PSS-params</code> sequence parameters for RSA-PSS keys.</p></td></tr>
<tr><td>v15.7.0</td>
<td><p><span>Added in: v15.7.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>
<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/Reference/Global_Objects/BigInt" class="type">&#x3C;bigint></a> Public exponent (RSA).</li>
<li><code>hashAlgorithm</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Name of the message digest (RSA-PSS).</li>
<li><code>mgf1HashAlgorithm</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Name of the message digest used by
MGF1 (RSA-PSS).</li>
<li><code>saltLength</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Minimal salt length in bytes (RSA-PSS).</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 (EC).</li>
</ul>
</li>
</ul>
<p>This property exists only on asymmetric keys. Depending on the type of the key,
this object contains information about the key. None of the information obtained
through this property can be used to uniquely identify a key or to compromise
the security of the key.</p>
<p>For RSA-PSS keys, if the key material contains a <code>RSASSA-PSS-params</code> sequence,
the <code>hashAlgorithm</code>, <code>mgf1HashAlgorithm</code>, and <code>saltLength</code> properties will be
set.</p>
<p>Other key details might be exposed via this API using additional attributes.</p>
<h4><code>keyObject.asymmetricKeyType</code><span><a class="mark" href="#all_crypto_keyobjectasymmetrickeytype" id="all_crypto_keyobjectasymmetrickeytype">#</a></span><a aria-hidden="true" class="legacy" id="crypto_keyobject_asymmetrickeytype"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.9.0, 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>
<h4><code>keyObject.export([options])</code><span><a class="mark" href="#all_crypto_keyobjectexportoptions" id="all_crypto_keyobjectexportoptions">#</a></span><a aria-hidden="true" class="legacy" id="crypto_keyobject_export_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.9.0</td>
<td><p>Added support for <code>'jwk'</code> format.</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><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="#all_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></li>
</ul>
<p>For symmetric keys, the following encoding options can be used:</p>
<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> Must be <code>'buffer'</code> (default) or <code>'jwk'</code>.</li>
</ul>
<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>, <code>'der'</code>, or <code>'jwk'</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>, <code>'der'</code>, or <code>'jwk'</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> The passphrase to use for encryption, see
<code>cipher</code>.</li>
</ul>
<p>The result type depends on the selected encoding format, when PEM the
result is a string, when DER it will be a buffer containing the data
encoded as DER, when <a href="https://tools.ietf.org/html/rfc7517">JWK</a> it will be an object.</p>
<p>When <a href="https://tools.ietf.org/html/rfc7517">JWK</a> encoding format was selected, all other encoding options are
ignored.</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>
<h4><code>keyObject.equals(otherKeyObject)</code><span><a class="mark" href="#all_crypto_keyobjectequalsotherkeyobject" id="all_crypto_keyobjectequalsotherkeyobject">#</a></span><a aria-hidden="true" class="legacy" id="crypto_keyobject_equals_otherkeyobject"></a></h4>
<div class="api_metadata">
<span>Added in: v17.7.0, v16.15.0</span>
</div>
<ul>
<li><code>otherKeyObject</code>: <a href="#all_crypto_class-keyobject" class="type">&#x3C;KeyObject></a> A <code>KeyObject</code> with which to
compare <code>keyObject</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> or <code>false</code> depending on whether the keys have exactly the same
type, value, and parameters. This method is not
<a href="https://en.wikipedia.org/wiki/Timing_attack">constant time</a>.</p>
<h4><code>keyObject.symmetricKeySize</code><span><a class="mark" href="#all_crypto_keyobjectsymmetrickeysize" id="all_crypto_keyobjectsymmetrickeysize">#</a></span><a aria-hidden="true" class="legacy" id="crypto_keyobject_symmetrickeysize"></a></h4>
<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>
<h4><code>keyObject.type</code><span><a class="mark" href="#all_crypto_keyobjecttype" id="all_crypto_keyobjecttype">#</a></span><a aria-hidden="true" class="legacy" id="crypto_keyobject_type"></a></h4>
<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>
</section><section><h3>Class: <code>Sign</code><span><a class="mark" href="#all_crypto_class-sign" id="all_crypto_class-sign">#</a></span><a aria-hidden="true" class="legacy" id="crypto_class_sign"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.92</span>
</div>
<ul>
<li>Extends: <a href="#all_stream_class-streamwritable" 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="#all_crypto_signsignprivatekey-outputencoding"><code>sign.sign()</code></a> method is used to generate and return the signature, or</li>
<li>Using the <a href="#all_crypto_signupdatedata-inputencoding"><code>sign.update()</code></a> and <a href="#all_crypto_signsignprivatekey-outputencoding"><code>sign.sign()</code></a> methods to produce the
signature.</li>
</ul>
<p>The <a href="#all_crypto_cryptocreatesignalgorithm-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="#all_crypto_class-verify"><code>Verify</code></a> objects as streams:</p>

<pre class="with-22-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">const</span> {
  generateKeyPairSync,
  createSign,
  createVerify,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> { privateKey, publicKey } = <span class="hljs-title function_">generateKeyPairSync</span>(<span class="hljs-string">'ec'</span>, {
  <span class="hljs-attr">namedCurve</span>: <span class="hljs-string">'sect239k1'</span>,
});

<span class="hljs-keyword">const</span> sign = <span class="hljs-title function_">createSign</span>(<span class="hljs-string">'SHA256'</span>);
sign.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some data to sign'</span>);
sign.<span class="hljs-title function_">end</span>();
<span class="hljs-keyword">const</span> signature = sign.<span class="hljs-title function_">sign</span>(privateKey, <span class="hljs-string">'hex'</span>);

<span class="hljs-keyword">const</span> verify = <span class="hljs-title function_">createVerify</span>(<span class="hljs-string">'SHA256'</span>);
verify.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some data to sign'</span>);
verify.<span class="hljs-title function_">end</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(verify.<span class="hljs-title function_">verify</span>(publicKey, signature, <span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// Prints: true</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
  generateKeyPairSync,
  createSign,
  createVerify,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> { privateKey, publicKey } = <span class="hljs-title function_">generateKeyPairSync</span>(<span class="hljs-string">'ec'</span>, {
  <span class="hljs-attr">namedCurve</span>: <span class="hljs-string">'sect239k1'</span>,
});

<span class="hljs-keyword">const</span> sign = <span class="hljs-title function_">createSign</span>(<span class="hljs-string">'SHA256'</span>);
sign.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some data to sign'</span>);
sign.<span class="hljs-title function_">end</span>();
<span class="hljs-keyword">const</span> signature = sign.<span class="hljs-title function_">sign</span>(privateKey, <span class="hljs-string">'hex'</span>);

<span class="hljs-keyword">const</span> verify = <span class="hljs-title function_">createVerify</span>(<span class="hljs-string">'SHA256'</span>);
verify.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some data to sign'</span>);
verify.<span class="hljs-title function_">end</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(verify.<span class="hljs-title function_">verify</span>(publicKey, signature, <span class="hljs-string">'hex'</span>));
<span class="hljs-comment">// Prints: true</span></code><button class="copy-button">copy</button></pre>
<p>Example: Using the <a href="#all_crypto_signupdatedata-inputencoding"><code>sign.update()</code></a> and <a href="#all_crypto_verifyupdatedata-inputencoding"><code>verify.update()</code></a> methods:</p>

<pre class="with-22-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">const</span> {
  generateKeyPairSync,
  createSign,
  createVerify,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> { privateKey, publicKey } = <span class="hljs-title function_">generateKeyPairSync</span>(<span class="hljs-string">'rsa'</span>, {
  <span class="hljs-attr">modulusLength</span>: <span class="hljs-number">2048</span>,
});

<span class="hljs-keyword">const</span> sign = <span class="hljs-title function_">createSign</span>(<span class="hljs-string">'SHA256'</span>);
sign.<span class="hljs-title function_">update</span>(<span class="hljs-string">'some data to sign'</span>);
sign.<span class="hljs-title function_">end</span>();
<span class="hljs-keyword">const</span> signature = sign.<span class="hljs-title function_">sign</span>(privateKey);

<span class="hljs-keyword">const</span> verify = <span class="hljs-title function_">createVerify</span>(<span class="hljs-string">'SHA256'</span>);
verify.<span class="hljs-title function_">update</span>(<span class="hljs-string">'some data to sign'</span>);
verify.<span class="hljs-title function_">end</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(verify.<span class="hljs-title function_">verify</span>(publicKey, signature));
<span class="hljs-comment">// Prints: true</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
  generateKeyPairSync,
  createSign,
  createVerify,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> { privateKey, publicKey } = <span class="hljs-title function_">generateKeyPairSync</span>(<span class="hljs-string">'rsa'</span>, {
  <span class="hljs-attr">modulusLength</span>: <span class="hljs-number">2048</span>,
});

<span class="hljs-keyword">const</span> sign = <span class="hljs-title function_">createSign</span>(<span class="hljs-string">'SHA256'</span>);
sign.<span class="hljs-title function_">update</span>(<span class="hljs-string">'some data to sign'</span>);
sign.<span class="hljs-title function_">end</span>();
<span class="hljs-keyword">const</span> signature = sign.<span class="hljs-title function_">sign</span>(privateKey);

<span class="hljs-keyword">const</span> verify = <span class="hljs-title function_">createVerify</span>(<span class="hljs-string">'SHA256'</span>);
verify.<span class="hljs-title function_">update</span>(<span class="hljs-string">'some data to sign'</span>);
verify.<span class="hljs-title function_">end</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(verify.<span class="hljs-title function_">verify</span>(publicKey, signature));
<span class="hljs-comment">// Prints: true</span></code><button class="copy-button">copy</button></pre>
<h4><code>sign.sign(privateKey[, outputEncoding])</code><span><a class="mark" href="#all_crypto_signsignprivatekey-outputencoding" id="all_crypto_signsignprivatekey-outputencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_sign_sign_privatekey_outputencoding"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>The privateKey can also be an ArrayBuffer and CryptoKey.</p></td></tr>
<tr><td>v13.2.0, v12.16.0</td>
<td><p>This function now supports IEEE-P1363 DSA and ECDSA signatures.</p></td></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>
<!--lint disable maximum-line-length remark-lint-->
<ul>
<li><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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_crypto_class-keyobject" class="type">&#x3C;KeyObject></a> | <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></a>
<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="#all_buffer_buffers-and-character-encodings">encoding</a> of the return value.</li>
<li>Returns: <a href="#all_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>
<!--lint enable maximum-line-length remark-lint-->
<p>Calculates the signature on all the data passed through using either
<a href="#all_crypto_signupdatedata-inputencoding"><code>sign.update()</code></a> or <a href="#all_stream_writablewritechunk-encoding-callback"><code>sign.write()</code></a>.</p>
<p>If <code>privateKey</code> is not a <a href="#all_crypto_class-keyobject"><code>KeyObject</code></a>, this function behaves as if
<code>privateKey</code> had been passed to <a href="#all_crypto_cryptocreateprivatekeykey"><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>
<h4><code>sign.update(data[, inputEncoding])</code><span><a class="mark" href="#all_crypto_signupdatedata-inputencoding" id="all_crypto_signupdatedata-inputencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_sign_update_data_inputencoding"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.0.0</td>
<td><p>The 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="#all_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="#all_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>
</section><section><h3>Class: <code>Verify</code><span><a class="mark" href="#all_crypto_class-verify" id="all_crypto_class-verify">#</a></span><a aria-hidden="true" class="legacy" id="crypto_class_verify"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.92</span>
</div>
<ul>
<li>Extends: <a href="#all_stream_class-streamwritable" 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="#all_crypto_verifyupdatedata-inputencoding"><code>verify.update()</code></a> and <a href="#all_crypto_verifyverifyobject-signature-signatureencoding"><code>verify.verify()</code></a> methods to verify
the signature.</li>
</ul>
<p>The <a href="#all_crypto_cryptocreateverifyalgorithm-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="#all_crypto_class-sign"><code>Sign</code></a> for examples.</p>
<h4><code>verify.update(data[, inputEncoding])</code><span><a class="mark" href="#all_crypto_verifyupdatedata-inputencoding" id="all_crypto_verifyupdatedata-inputencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_verify_update_data_inputencoding"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v6.0.0</td>
<td><p>The 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="#all_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="#all_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>
<h4><code>verify.verify(object, signature[, signatureEncoding])</code><span><a class="mark" href="#all_crypto_verifyverifyobject-signature-signatureencoding" id="all_crypto_verifyverifyobject-signature-signatureencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_verify_verify_object_signature_signatureencoding"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>The object can also be an ArrayBuffer and CryptoKey.</p></td></tr>
<tr><td>v13.2.0, v12.16.0</td>
<td><p>This function now supports IEEE-P1363 DSA and ECDSA signatures.</p></td></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>
<!--lint disable maximum-line-length remark-lint-->
<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> | <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/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_crypto_class-keyobject" class="type">&#x3C;KeyObject></a> | <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></a>
<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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_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>
<!--lint enable maximum-line-length remark-lint-->
<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="#all_crypto_class-keyobject"><code>KeyObject</code></a>, this function behaves as if
<code>object</code> had been passed to <a href="#all_crypto_cryptocreatepublickeykey"><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 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>
</section><section><h3>Class: <code>X509Certificate</code><span><a class="mark" href="#all_crypto_class-x509certificate" id="all_crypto_class-x509certificate">#</a></span><a aria-hidden="true" class="legacy" id="crypto_class_x509certificate"></a></h3>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<p>Encapsulates an X509 certificate and provides read-only access to
its information.</p>

<pre class="with-56-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">const</span> { X509Certificate } = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> x509 = <span class="hljs-keyword">new</span> <span class="hljs-title function_">X509Certificate</span>(<span class="hljs-string">'{... pem encoded cert ...}'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(x509.<span class="hljs-property">subject</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { X509Certificate } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> x509 = <span class="hljs-keyword">new</span> <span class="hljs-title function_">X509Certificate</span>(<span class="hljs-string">'{... pem encoded cert ...}'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(x509.<span class="hljs-property">subject</span>);</code><button class="copy-button">copy</button></pre>
<h4><code>new X509Certificate(buffer)</code><span><a class="mark" href="#all_crypto_new-x509certificatebuffer" id="all_crypto_new-x509certificatebuffer">#</a></span><a aria-hidden="true" class="legacy" id="crypto_new_x509certificate_buffer"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<ul>
<li><code>buffer</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/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> A PEM or DER encoded
X509 Certificate.</li>
</ul>
<h4><code>x509.ca</code><span><a class="mark" href="#all_crypto_x509ca" id="all_crypto_x509ca">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_ca"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Will be <code>true</code> if this is a Certificate Authority (CA)
certificate.</li>
</ul>
<h4><code>x509.checkEmail(email[, options])</code><span><a class="mark" href="#all_crypto_x509checkemailemail-options" id="all_crypto_x509checkemailemail-options">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_checkemail_email_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>The subject option now defaults to <code>'default'</code>.</p></td></tr>
<tr><td>v17.5.0, v16.15.0</td>
<td><p>The subject option can now be set to <code>'default'</code>.</p></td></tr>
<tr><td>v17.5.0, v16.14.1</td>
<td><p>The <code>wildcards</code>, <code>partialWildcards</code>, <code>multiLabelWildcards</code>, and <code>singleLabelSubdomains</code> options have been removed since they had no effect.</p></td></tr>
<tr><td>v15.6.0</td>
<td><p><span>Added in: v15.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>email</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>
<ul>
<li><code>subject</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> <code>'default'</code>, <code>'always'</code>, or <code>'never'</code>.
<strong>Default:</strong> <code>'default'</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> Returns <code>email</code> if the certificate matches,
<code>undefined</code> if it does not.</li>
</ul>
<p>Checks whether the certificate matches the given email address.</p>
<p>If the <code>'subject'</code> option is undefined or set to <code>'default'</code>, the certificate
subject is only considered if the subject alternative name extension either does
not exist or does not contain any email addresses.</p>
<p>If the <code>'subject'</code> option is set to <code>'always'</code> and if the subject alternative
name extension either does not exist or does not contain a matching email
address, the certificate subject is considered.</p>
<p>If the <code>'subject'</code> option is set to <code>'never'</code>, the certificate subject is never
considered, even if the certificate contains no subject alternative names.</p>
<h4><code>x509.checkHost(name[, options])</code><span><a class="mark" href="#all_crypto_x509checkhostname-options" id="all_crypto_x509checkhostname-options">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_checkhost_name_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>The subject option now defaults to <code>'default'</code>.</p></td></tr>
<tr><td>v17.5.0, v16.15.0</td>
<td><p>The subject option can now be set to <code>'default'</code>.</p></td></tr>
<tr><td>v15.6.0</td>
<td><p><span>Added in: v15.6.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>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>subject</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> <code>'default'</code>, <code>'always'</code>, or <code>'never'</code>.
<strong>Default:</strong> <code>'default'</code>.</li>
<li><code>wildcards</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>partialWildcards</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>multiLabelWildcards</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>singleLabelSubdomains</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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> Returns a subject name that matches <code>name</code>,
or <code>undefined</code> if no subject name matches <code>name</code>.</li>
</ul>
<p>Checks whether the certificate matches the given host name.</p>
<p>If the certificate matches the given host name, the matching subject name is
returned. The returned name might be an exact match (e.g., <code>foo.example.com</code>)
or it might contain wildcards (e.g., <code>*.example.com</code>). Because host name
comparisons are case-insensitive, the returned subject name might also differ
from the given <code>name</code> in capitalization.</p>
<p>If the <code>'subject'</code> option is undefined or set to <code>'default'</code>, the certificate
subject is only considered if the subject alternative name extension either does
not exist or does not contain any DNS names. This behavior is consistent with
<a href="https://www.rfc-editor.org/rfc/rfc2818.txt">RFC 2818</a> ("HTTP Over TLS").</p>
<p>If the <code>'subject'</code> option is set to <code>'always'</code> and if the subject alternative
name extension either does not exist or does not contain a matching DNS name,
the certificate subject is considered.</p>
<p>If the <code>'subject'</code> option is set to <code>'never'</code>, the certificate subject is never
considered, even if the certificate contains no subject alternative names.</p>
<h4><code>x509.checkIP(ip)</code><span><a class="mark" href="#all_crypto_x509checkipip" id="all_crypto_x509checkipip">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_checkip_ip"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.5.0, v16.14.1</td>
<td><p>The <code>options</code> argument has been removed since it had no effect.</p></td></tr>
<tr><td>v15.6.0</td>
<td><p><span>Added in: v15.6.0</span></p></td></tr>
</tbody></table>
</details>
</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>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> Returns <code>ip</code> if the certificate matches,
<code>undefined</code> if it does not.</li>
</ul>
<p>Checks whether the certificate matches the given IP address (IPv4 or IPv6).</p>
<p>Only <a href="https://www.rfc-editor.org/rfc/rfc5280.txt">RFC 5280</a> <code>iPAddress</code> subject alternative names are considered, and they
must match the given <code>ip</code> address exactly. Other subject alternative names as
well as the subject field of the certificate are ignored.</p>
<h4><code>x509.checkIssued(otherCert)</code><span><a class="mark" href="#all_crypto_x509checkissuedothercert" id="all_crypto_x509checkissuedothercert">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_checkissued_othercert"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<ul>
<li><code>otherCert</code> <a href="#all_crypto_class-x509certificate" class="type">&#x3C;X509Certificate></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>Checks whether this certificate was issued by the given <code>otherCert</code>.</p>
<h4><code>x509.checkPrivateKey(privateKey)</code><span><a class="mark" href="#all_crypto_x509checkprivatekeyprivatekey" id="all_crypto_x509checkprivatekeyprivatekey">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_checkprivatekey_privatekey"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<ul>
<li><code>privateKey</code> <a href="#all_crypto_class-keyobject" class="type">&#x3C;KeyObject></a> A private key.</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>Checks whether the public key for this certificate is consistent with
the given private key.</p>
<h4><code>x509.fingerprint</code><span><a class="mark" href="#all_crypto_x509fingerprint" id="all_crypto_x509fingerprint">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_fingerprint"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The SHA-1 fingerprint of this certificate.</p>
<p>Because SHA-1 is cryptographically broken and because the security of SHA-1 is
significantly worse than that of algorithms that are commonly used to sign
certificates, consider using <a href="#all_crypto_x509fingerprint256"><code>x509.fingerprint256</code></a> instead.</p>
<h4><code>x509.fingerprint256</code><span><a class="mark" href="#all_crypto_x509fingerprint256" id="all_crypto_x509fingerprint256">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_fingerprint256"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The SHA-256 fingerprint of this certificate.</p>
<h4><code>x509.fingerprint512</code><span><a class="mark" href="#all_crypto_x509fingerprint512" id="all_crypto_x509fingerprint512">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_fingerprint512"></a></h4>
<div class="api_metadata">
<span>Added in: v17.2.0, v16.14.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The SHA-512 fingerprint of this certificate.</p>
<p>Because computing the SHA-256 fingerprint is usually faster and because it is
only half the size of the SHA-512 fingerprint, <a href="#all_crypto_x509fingerprint256"><code>x509.fingerprint256</code></a> may be
a better choice. While SHA-512 presumably provides a higher level of security in
general, the security of SHA-256 matches that of most algorithms that are
commonly used to sign certificates.</p>
<h4><code>x509.infoAccess</code><span><a class="mark" href="#all_crypto_x509infoaccess" id="all_crypto_x509infoaccess">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_infoaccess"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.3.1, v16.13.2</td>
<td><p>Parts of this string may be encoded as JSON string literals in response to CVE-2021-44532.</p></td></tr>
<tr><td>v15.6.0</td>
<td><p><span>Added in: v15.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>A textual representation of the certificate's authority information access
extension.</p>
<p>This is a line feed separated list of access descriptions. Each line begins with
the access method and the kind of the access location, followed by a colon and
the value associated with the access location.</p>
<p>After the prefix denoting the access method and the kind of the access location,
the remainder of each line might be enclosed in quotes to indicate that the
value is a JSON string literal. For backward compatibility, Node.js only uses
JSON string literals within this property when necessary to avoid ambiguity.
Third-party code should be prepared to handle both possible entry formats.</p>
<h4><code>x509.issuer</code><span><a class="mark" href="#all_crypto_x509issuer" id="all_crypto_x509issuer">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_issuer"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The issuer identification included in this certificate.</p>
<h4><code>x509.issuerCertificate</code><span><a class="mark" href="#all_crypto_x509issuercertificate" id="all_crypto_x509issuercertificate">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_issuercertificate"></a></h4>
<div class="api_metadata">
<span>Added in: v15.9.0</span>
</div>
<ul>
<li>Type: <a href="#all_crypto_class-x509certificate" class="type">&#x3C;X509Certificate></a></li>
</ul>
<p>The issuer certificate or <code>undefined</code> if the issuer certificate is not
available.</p>
<h4><code>x509.extKeyUsage</code><span><a class="mark" href="#all_crypto_x509extkeyusage" id="all_crypto_x509extkeyusage">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_extkeyusage"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a></li>
</ul>
<p>An array detailing the key extended usages for this certificate.</p>
<h4><code>x509.publicKey</code><span><a class="mark" href="#all_crypto_x509publickey" id="all_crypto_x509publickey">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_publickey"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<ul>
<li>Type: <a href="#all_crypto_class-keyobject" class="type">&#x3C;KeyObject></a></li>
</ul>
<p>The public key <a href="#all_crypto_class-keyobject" class="type">&#x3C;KeyObject></a> for this certificate.</p>
<h4><code>x509.raw</code><span><a class="mark" href="#all_crypto_x509raw" id="all_crypto_x509raw">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_raw"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<ul>
<li>Type: <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a></li>
</ul>
<p>A <code>Buffer</code> containing the DER encoding of this certificate.</p>
<h4><code>x509.serialNumber</code><span><a class="mark" href="#all_crypto_x509serialnumber" id="all_crypto_x509serialnumber">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_serialnumber"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The serial number of this certificate.</p>
<p>Serial numbers are assigned by certificate authorities and do not uniquely
identify certificates. Consider using <a href="#all_crypto_x509fingerprint256"><code>x509.fingerprint256</code></a> as a unique
identifier instead.</p>
<h4><code>x509.subject</code><span><a class="mark" href="#all_crypto_x509subject" id="all_crypto_x509subject">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_subject"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The complete subject of this certificate.</p>
<h4><code>x509.subjectAltName</code><span><a class="mark" href="#all_crypto_x509subjectaltname" id="all_crypto_x509subjectaltname">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_subjectaltname"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.3.1, v16.13.2</td>
<td><p>Parts of this string may be encoded as JSON string literals in response to CVE-2021-44532.</p></td></tr>
<tr><td>v15.6.0</td>
<td><p><span>Added in: v15.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The subject alternative name specified for this certificate.</p>
<p>This is a comma-separated list of subject alternative names. Each entry begins
with a string identifying the kind of the subject alternative name followed by
a colon and the value associated with the entry.</p>
<p>Earlier versions of Node.js incorrectly assumed that it is safe to split this
property at the two-character sequence <code>', '</code> (see <a href="https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44532">CVE-2021-44532</a>). However,
both malicious and legitimate certificates can contain subject alternative names
that include this sequence when represented as a string.</p>
<p>After the prefix denoting the type of the entry, the remainder of each entry
might be enclosed in quotes to indicate that the value is a JSON string literal.
For backward compatibility, Node.js only uses JSON string literals within this
property when necessary to avoid ambiguity. Third-party code should be prepared
to handle both possible entry formats.</p>
<h4><code>x509.toJSON()</code><span><a class="mark" href="#all_crypto_x509tojson" id="all_crypto_x509tojson">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_tojson"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>There is no standard JSON encoding for X509 certificates. The
<code>toJSON()</code> method returns a string containing the PEM encoded
certificate.</p>
<h4><code>x509.toLegacyObject()</code><span><a class="mark" href="#all_crypto_x509tolegacyobject" id="all_crypto_x509tolegacyobject">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_tolegacyobject"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<ul>
<li>Type: <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 this certificate using the legacy
<a href="#all_tls_certificate-object">certificate object</a> encoding.</p>
<h4><code>x509.toString()</code><span><a class="mark" href="#all_crypto_x509tostring" id="all_crypto_x509tostring">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_tostring"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<ul>
<li>Type: <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 PEM-encoded certificate.</p>
<h4><code>x509.validFrom</code><span><a class="mark" href="#all_crypto_x509validfrom" id="all_crypto_x509validfrom">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_validfrom"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The date/time from which this certificate is valid.</p>
<h4><code>x509.validTo</code><span><a class="mark" href="#all_crypto_x509validto" id="all_crypto_x509validto">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_validto"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The date/time until which this certificate is valid.</p>
<h4><code>x509.verify(publicKey)</code><span><a class="mark" href="#all_crypto_x509verifypublickey" id="all_crypto_x509verifypublickey">#</a></span><a aria-hidden="true" class="legacy" id="crypto_x509_verify_publickey"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0</span>
</div>
<ul>
<li><code>publicKey</code> <a href="#all_crypto_class-keyobject" class="type">&#x3C;KeyObject></a> A public key.</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 that this certificate was signed by the given public key.
Does not perform any other validation checks on the certificate.</p>
</section><section><h3><code>node:crypto</code> module methods and properties<span><a class="mark" href="#all_crypto_nodecrypto-module-methods-and-properties" id="all_crypto_nodecrypto-module-methods-and-properties">#</a></span><a aria-hidden="true" class="legacy" id="crypto_node_crypto_module_methods_and_properties"></a></h3>
<h4><code>crypto.constants</code><span><a class="mark" href="#all_crypto_cryptoconstants" id="all_crypto_cryptoconstants">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_constants"></a></h4>
<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>An object containing commonly used constants for crypto and security related
operations. The specific constants currently defined are described in
<a href="#all_crypto_crypto-constants">Crypto constants</a>.</p>
<h4><code>crypto.fips</code><span><a class="mark" href="#all_crypto_cryptofips" id="all_crypto_cryptofips">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_fips"></a></h4>
<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="#all_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>
<h4><code>crypto.checkPrime(candidate[, options], callback)</code><span><a class="mark" href="#all_crypto_cryptocheckprimecandidate-options-callback" id="all_crypto_cryptocheckprimecandidate-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_checkprime_candidate_options_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></tr>
<tr><td>v15.8.0</td>
<td><p><span>Added in: v15.8.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>candidate</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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></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/BigInt" class="type">&#x3C;bigint></a>
A possible prime encoded as a sequence of big endian octets of arbitrary
length.</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>
<ul>
<li><code>checks</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The number of Miller-Rabin probabilistic primality
iterations to perform. When the value is <code>0</code> (zero), a number of checks
is used that yields a false positive rate of at most 2<sup>-64</sup> for
random input. Care must be used when selecting a number of checks. Refer
to the OpenSSL documentation for the <a href="https://www.openssl.org/docs/man1.1.1/man3/BN_is_prime_ex.html"><code>BN_is_prime_ex</code></a> function <code>nchecks</code>
options for more details. <strong>Default:</strong> <code>0</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>
<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> Set to an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a> object if an error occurred during check.</li>
<li><code>result</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 candidate is a prime with an error
probability less than <code>0.25 ** options.checks</code>.</li>
</ul>
</li>
</ul>
<p>Checks the primality of the <code>candidate</code>.</p>
<h4><code>crypto.checkPrimeSync(candidate[, options])</code><span><a class="mark" href="#all_crypto_cryptocheckprimesynccandidate-options" id="all_crypto_cryptocheckprimesynccandidate-options">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_checkprimesync_candidate_options"></a></h4>
<div class="api_metadata">
<span>Added in: v15.8.0</span>
</div>
<ul>
<li><code>candidate</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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></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/BigInt" class="type">&#x3C;bigint></a>
A possible prime encoded as a sequence of big endian octets of arbitrary
length.</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>
<ul>
<li><code>checks</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The number of Miller-Rabin probabilistic primality
iterations to perform. When the value is <code>0</code> (zero), a number of checks
is used that yields a false positive rate of at most 2<sup>-64</sup> for
random input. Care must be used when selecting a number of checks. Refer
to the OpenSSL documentation for the <a href="https://www.openssl.org/docs/man1.1.1/man3/BN_is_prime_ex.html"><code>BN_is_prime_ex</code></a> function <code>nchecks</code>
options for more details. <strong>Default:</strong> <code>0</code></li>
</ul>
</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 candidate is a prime with an error
probability less than <code>0.25 ** options.checks</code>.</li>
</ul>
<p>Checks the primality of the <code>candidate</code>.</p>
<h4><code>crypto.createCipher(algorithm, password[, options])</code><span><a class="mark" href="#all_crypto_cryptocreatecipheralgorithm-password-options" id="all_crypto_cryptocreatecipheralgorithm-password-options">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_createcipher_algorithm_password_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.9.0, v16.17.0</td>
<td><p>The <code>authTagLength</code> option is now optional when using the <code>chacha20-poly1305</code> cipher and defaults to 16 bytes.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p>The password argument can be an ArrayBuffer and is limited to a maximum of 2 ** 31 - 1 bytes.</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>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="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_crypto_cryptocreatecipherivalgorithm-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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_stream_new-streamtransformoptions"><code>stream.transform</code> options</a></li>
<li>Returns: <a href="#all_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 (e.g. <code>'aes-128-ccm'</code>) is used. In that case, the
<code>authTagLength</code> option is required and specifies the length of the
authentication tag in bytes, see <a href="#all_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.
For <code>chacha20-poly1305</code>, the <code>authTagLength</code> option 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> 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><strong class="critical">This function is semantically insecure for all
supported ciphers and fatally flawed for ciphers in counter mode (such as CTR,
GCM, or CCM).</strong></p>
<p>The implementation of <code>crypto.createCipher()</code> derives keys using the OpenSSL
function <a href="https://www.openssl.org/docs/man3.0/man3/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/man3.0/man3/EVP_BytesToKey.html"><code>EVP_BytesToKey</code></a> it is recommended that developers derive a key and IV on
their own using <a href="#all_crypto_cryptoscryptpassword-salt-keylen-options-callback"><code>crypto.scrypt()</code></a> and to use <a href="#all_crypto_cryptocreatecipherivalgorithm-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>
<h4><code>crypto.createCipheriv(algorithm, key, iv[, options])</code><span><a class="mark" href="#all_crypto_cryptocreatecipherivalgorithm-key-iv-options" id="all_crypto_cryptocreatecipherivalgorithm-key-iv-options">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_createcipheriv_algorithm_key_iv_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.9.0, v16.17.0</td>
<td><p>The <code>authTagLength</code> option is now optional when using the <code>chacha20-poly1305</code> cipher and defaults to 16 bytes.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p>The password and iv arguments can be an ArrayBuffer and are each limited to a maximum of 2 ** 31 - 1 bytes.</p></td></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, v10.17.0</td>
<td><p>The cipher <code>chacha20-poly1305</code> (the IETF variant of ChaCha20-Poly1305) 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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_crypto_class-keyobject" class="type">&#x3C;KeyObject></a> | <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_stream_new-streamtransformoptions"><code>stream.transform</code> options</a></li>
<li>Returns: <a href="#all_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 (e.g. <code>'aes-128-ccm'</code>) is used. In that case, the
<code>authTagLength</code> option is required and specifies the length of the
authentication tag in bytes, see <a href="#all_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.
For <code>chacha20-poly1305</code>, the <code>authTagLength</code> option 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> 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="#all_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>When passing strings for <code>key</code> or <code>iv</code>, please consider
<a href="#all_crypto_using-strings-as-inputs-to-cryptographic-apis">caveats when using strings as inputs to cryptographic APIs</a>.</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>
<h4><code>crypto.createDecipher(algorithm, password[, options])</code><span><a class="mark" href="#all_crypto_cryptocreatedecipheralgorithm-password-options" id="all_crypto_cryptocreatedecipheralgorithm-password-options">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_createdecipher_algorithm_password_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.9.0, v16.17.0</td>
<td><p>The <code>authTagLength</code> option is now optional when using the <code>chacha20-poly1305</code> cipher and defaults to 16 bytes.</p></td></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="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_crypto_cryptocreatedecipherivalgorithm-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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_stream_new-streamtransformoptions"><code>stream.transform</code> options</a></li>
<li>Returns: <a href="#all_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 (e.g. <code>'aes-128-ccm'</code>) is used. In that case, the
<code>authTagLength</code> option is required and specifies the length of the
authentication tag in bytes, see <a href="#all_crypto_ccm-mode">CCM mode</a>.
For <code>chacha20-poly1305</code>, the <code>authTagLength</code> option defaults to 16 bytes.</p>
<p><strong class="critical">This function is semantically insecure for all
supported ciphers and fatally flawed for ciphers in counter mode (such as CTR,
GCM, or CCM).</strong></p>
<p>The implementation of <code>crypto.createDecipher()</code> derives keys using the OpenSSL
function <a href="https://www.openssl.org/docs/man3.0/man3/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/man3.0/man3/EVP_BytesToKey.html"><code>EVP_BytesToKey</code></a> it is recommended that developers derive a key and IV on
their own using <a href="#all_crypto_cryptoscryptpassword-salt-keylen-options-callback"><code>crypto.scrypt()</code></a> and to use <a href="#all_crypto_cryptocreatedecipherivalgorithm-key-iv-options"><code>crypto.createDecipheriv()</code></a>
to create the <code>Decipher</code> object.</p>
<h4><code>crypto.createDecipheriv(algorithm, key, iv[, options])</code><span><a class="mark" href="#all_crypto_cryptocreatedecipherivalgorithm-key-iv-options" id="all_crypto_cryptocreatedecipherivalgorithm-key-iv-options">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_createdecipheriv_algorithm_key_iv_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.9.0, v16.17.0</td>
<td><p>The <code>authTagLength</code> option is now optional when using the <code>chacha20-poly1305</code> cipher and defaults to 16 bytes.</p></td></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, v10.17.0</td>
<td><p>The cipher <code>chacha20-poly1305</code> (the IETF variant of ChaCha20-Poly1305) 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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_crypto_class-keyobject" class="type">&#x3C;KeyObject></a> | <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_stream_new-streamtransformoptions"><code>stream.transform</code> options</a></li>
<li>Returns: <a href="#all_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 (e.g. <code>'aes-128-ccm'</code>) is used. In that case, the
<code>authTagLength</code> option is required and specifies the length of the
authentication tag in bytes, see <a href="#all_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.
For <code>chacha20-poly1305</code>, the <code>authTagLength</code> option 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> 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="#all_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>When passing strings for <code>key</code> or <code>iv</code>, please consider
<a href="#all_crypto_using-strings-as-inputs-to-cryptographic-apis">caveats when using strings as inputs to cryptographic APIs</a>.</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>
<h4><code>crypto.createDiffieHellman(prime[, primeEncoding][, generator][, generatorEncoding])</code><span><a class="mark" href="#all_crypto_cryptocreatediffiehellmanprime-primeencoding-generator-generatorencoding" id="all_crypto_cryptocreatediffiehellmanprime-primeencoding-generator-generatorencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_creatediffiehellman_prime_primeencoding_generator_generatorencoding"></a></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>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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_buffer_buffers-and-character-encodings">encoding</a> of the <code>generator</code> string.</li>
<li>Returns: <a href="#all_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>
<h4><code>crypto.createDiffieHellman(primeLength[, generator])</code><span><a class="mark" href="#all_crypto_cryptocreatediffiehellmanprimelength-generator" id="all_crypto_cryptocreatediffiehellmanprimelength-generator">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_creatediffiehellman_primelength_generator"></a></h4>
<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="#all_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>
<h4><code>crypto.createDiffieHellmanGroup(name)</code><span><a class="mark" href="#all_crypto_cryptocreatediffiehellmangroupname" id="all_crypto_cryptocreatediffiehellmangroupname">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_creatediffiehellmangroup_name"></a></h4>
<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="#all_crypto_class-diffiehellmangroup" class="type">&#x3C;DiffieHellmanGroup></a></li>
</ul>
<p>An alias for <a href="#all_crypto_cryptogetdiffiehellmangroupname"><code>crypto.getDiffieHellman()</code></a></p>
<h4><code>crypto.createECDH(curveName)</code><span><a class="mark" href="#all_crypto_cryptocreateecdhcurvename" id="all_crypto_cryptocreateecdhcurvename">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_createecdh_curvename"></a></h4>
<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="#all_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="#all_crypto_cryptogetcurves"><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>
<h4><code>crypto.createHash(algorithm[, options])</code><span><a class="mark" href="#all_crypto_cryptocreatehashalgorithm-options" id="all_crypto_cryptocreatehashalgorithm-options">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_createhash_algorithm_options"></a></h4>
<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="#all_stream_new-streamtransformoptions"><code>stream.transform</code> options</a></li>
<li>Returns: <a href="#all_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> will
display the available digest algorithms.</p>
<p>Example: generating the sha256 sum of a file</p>

<pre class="with-19-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> {
  createReadStream,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">import</span> { argv } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">const</span> {
  createHash,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> filename = argv[<span class="hljs-number">2</span>];

<span class="hljs-keyword">const</span> hash = <span class="hljs-title function_">createHash</span>(<span class="hljs-string">'sha256'</span>);

<span class="hljs-keyword">const</span> input = <span class="hljs-title function_">createReadStream</span>(filename);
input.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-comment">// Only one element is going to be produced by the</span>
  <span class="hljs-comment">// hash stream.</span>
  <span class="hljs-keyword">const</span> data = input.<span class="hljs-title function_">read</span>();
  <span class="hljs-keyword">if</span> (data)
    hash.<span class="hljs-title function_">update</span>(data);
  <span class="hljs-keyword">else</span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${hash.digest(<span class="hljs-string">'hex'</span>)}</span> <span class="hljs-subst">${filename}</span>`</span>);
  }
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
  createReadStream,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> {
  createHash,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> { argv } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-keyword">const</span> filename = argv[<span class="hljs-number">2</span>];

<span class="hljs-keyword">const</span> hash = <span class="hljs-title function_">createHash</span>(<span class="hljs-string">'sha256'</span>);

<span class="hljs-keyword">const</span> input = <span class="hljs-title function_">createReadStream</span>(filename);
input.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-comment">// Only one element is going to be produced by the</span>
  <span class="hljs-comment">// hash stream.</span>
  <span class="hljs-keyword">const</span> data = input.<span class="hljs-title function_">read</span>();
  <span class="hljs-keyword">if</span> (data)
    hash.<span class="hljs-title function_">update</span>(data);
  <span class="hljs-keyword">else</span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${hash.digest(<span class="hljs-string">'hex'</span>)}</span> <span class="hljs-subst">${filename}</span>`</span>);
  }
});</code><button class="copy-button">copy</button></pre>
<h4><code>crypto.createHmac(algorithm, key[, options])</code><span><a class="mark" href="#all_crypto_cryptocreatehmacalgorithm-key-options" id="all_crypto_cryptocreatehmacalgorithm-key-options">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_createhmac_algorithm_key_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>The key can also be an ArrayBuffer or CryptoKey. The encoding option was added. The key cannot contain more than 2 ** 32 - 1 bytes.</p></td></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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_crypto_class-keyobject" class="type">&#x3C;KeyObject></a> | <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></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="#all_stream_new-streamtransformoptions"><code>stream.transform</code> options</a>
<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 string encoding to use when <code>key</code> is a string.</li>
</ul>
</li>
<li>Returns: <a href="#all_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> 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="#all_crypto_class-keyobject"><code>KeyObject</code></a>, its type must be <code>secret</code>. If it is a string, please consider
<a href="#all_crypto_using-strings-as-inputs-to-cryptographic-apis">caveats when using strings as inputs to cryptographic APIs</a>. If it was
obtained from a cryptographically secure source of entropy, such as
<a href="#all_crypto_cryptorandombytessize-callback"><code>crypto.randomBytes()</code></a> or <a href="#all_crypto_cryptogeneratekeytype-options-callback"><code>crypto.generateKey()</code></a>, its length should not
exceed the block size of <code>algorithm</code> (e.g., 512 bits for SHA-256).</p>
<p>Example: generating the sha256 HMAC of a file</p>

<pre class="with-19-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> {
  createReadStream,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">import</span> { argv } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">const</span> {
  createHmac,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> filename = argv[<span class="hljs-number">2</span>];

<span class="hljs-keyword">const</span> hmac = <span class="hljs-title function_">createHmac</span>(<span class="hljs-string">'sha256'</span>, <span class="hljs-string">'a secret'</span>);

<span class="hljs-keyword">const</span> input = <span class="hljs-title function_">createReadStream</span>(filename);
input.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-comment">// Only one element is going to be produced by the</span>
  <span class="hljs-comment">// hash stream.</span>
  <span class="hljs-keyword">const</span> data = input.<span class="hljs-title function_">read</span>();
  <span class="hljs-keyword">if</span> (data)
    hmac.<span class="hljs-title function_">update</span>(data);
  <span class="hljs-keyword">else</span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${hmac.digest(<span class="hljs-string">'hex'</span>)}</span> <span class="hljs-subst">${filename}</span>`</span>);
  }
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
  createReadStream,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> {
  createHmac,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> { argv } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-keyword">const</span> filename = argv[<span class="hljs-number">2</span>];

<span class="hljs-keyword">const</span> hmac = <span class="hljs-title function_">createHmac</span>(<span class="hljs-string">'sha256'</span>, <span class="hljs-string">'a secret'</span>);

<span class="hljs-keyword">const</span> input = <span class="hljs-title function_">createReadStream</span>(filename);
input.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-comment">// Only one element is going to be produced by the</span>
  <span class="hljs-comment">// hash stream.</span>
  <span class="hljs-keyword">const</span> data = input.<span class="hljs-title function_">read</span>();
  <span class="hljs-keyword">if</span> (data)
    hmac.<span class="hljs-title function_">update</span>(data);
  <span class="hljs-keyword">else</span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${hmac.digest(<span class="hljs-string">'hex'</span>)}</span> <span class="hljs-subst">${filename}</span>`</span>);
  }
});</code><button class="copy-button">copy</button></pre>
<h4><code>crypto.createPrivateKey(key)</code><span><a class="mark" href="#all_crypto_cryptocreateprivatekeykey" id="all_crypto_cryptocreateprivatekeykey">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_createprivatekey_key"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.12.0</td>
<td><p>The key can also be a JWK object.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p>The key can also be an ArrayBuffer. The encoding option was added. The key cannot contain more than 2 ** 32 - 1 bytes.</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>
<!--lint disable maximum-line-length remark-lint-->
<ul>
<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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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>
<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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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/Object" class="type">&#x3C;Object></a> The key
material, either in PEM, DER, or JWK 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>, <code>'der'</code>, or '<code>'jwk'</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 otherwise.</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> The passphrase to use for decryption.</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 string encoding to use when <code>key</code> is a string.</li>
</ul>
</li>
<li>Returns: <a href="#all_crypto_class-keyobject" class="type">&#x3C;KeyObject></a></li>
</ul>
<!--lint enable maximum-line-length remark-lint-->
<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>
<h4><code>crypto.createPublicKey(key)</code><span><a class="mark" href="#all_crypto_cryptocreatepublickeykey" id="all_crypto_cryptocreatepublickeykey">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_createpublickey_key"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.12.0</td>
<td><p>The key can also be a JWK object.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p>The key can also be an ArrayBuffer. The encoding option was added. The key cannot contain more than 2 ** 32 - 1 bytes.</p></td></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>
<!--lint disable maximum-line-length remark-lint-->
<ul>
<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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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>
<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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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/Object" class="type">&#x3C;Object></a> The key
material, either in PEM, DER, or JWK 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>, <code>'der'</code>, or <code>'jwk'</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> and ignored otherwise.</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 string encoding to use when <code>key</code> is a string.</li>
</ul>
</li>
<li>Returns: <a href="#all_crypto_class-keyobject" class="type">&#x3C;KeyObject></a></li>
</ul>
<!--lint enable maximum-line-length remark-lint-->
<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="#all_crypto_cryptocreateprivatekeykey"><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>
<h4><code>crypto.createSecretKey(key[, encoding])</code><span><a class="mark" href="#all_crypto_cryptocreatesecretkeykey-encoding" id="all_crypto_cryptocreatesecretkeykey-encoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_createsecretkey_key_encoding"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.8.0, v16.18.0</td>
<td><p>The key can now be zero-length.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p>The key can also be an ArrayBuffer or string. The encoding argument was added. The key cannot contain more than 2 ** 32 - 1 bytes.</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><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/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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 string encoding when <code>key</code> is a string.</li>
<li>Returns: <a href="#all_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>
<h4><code>crypto.createSign(algorithm[, options])</code><span><a class="mark" href="#all_crypto_cryptocreatesignalgorithm-options" id="all_crypto_cryptocreatesignalgorithm-options">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_createsign_algorithm_options"></a></h4>
<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="#all_stream_new-streamwritableoptions"><code>stream.Writable</code> options</a></li>
<li>Returns: <a href="#all_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="#all_crypto_cryptogethashes"><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>
<h4><code>crypto.createVerify(algorithm[, options])</code><span><a class="mark" href="#all_crypto_cryptocreateverifyalgorithm-options" id="all_crypto_cryptocreateverifyalgorithm-options">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_createverify_algorithm_options"></a></h4>
<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="#all_stream_new-streamwritableoptions"><code>stream.Writable</code> options</a></li>
<li>Returns: <a href="#all_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="#all_crypto_cryptogethashes"><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>
<h4><code>crypto.diffieHellman(options)</code><span><a class="mark" href="#all_crypto_cryptodiffiehellmanoptions" id="all_crypto_cryptodiffiehellmanoptions">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_diffiehellman_options"></a></h4>
<div class="api_metadata">
<span>Added in: v13.9.0, v12.17.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>
<ul>
<li><code>privateKey</code>: <a href="#all_crypto_class-keyobject" class="type">&#x3C;KeyObject></a></li>
<li><code>publicKey</code>: <a href="#all_crypto_class-keyobject" class="type">&#x3C;KeyObject></a></li>
</ul>
</li>
<li>Returns: <a href="#all_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>
<h4><code>crypto.hash(algorithm, data[, outputEncoding])</code><span><a class="mark" href="#all_crypto_cryptohashalgorithm-data-outputencoding" id="all_crypto_cryptohashalgorithm-data-outputencoding">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_hash_algorithm_data_outputencoding"></a></h4>
<div class="api_metadata">
<span>Added in: v20.12.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.2 - Release candidate</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> | <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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#all_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> When <code>data</code> is a
string, it will be encoded as UTF-8 before being hashed. If a different
input encoding is desired for a string input, user could encode the string
into a <code>TypedArray</code> using either <code>TextEncoder</code> or <code>Buffer.from()</code> and passing
the encoded <code>TypedArray</code> into this API instead.</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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a>  <a href="#all_buffer_buffers-and-character-encodings">Encoding</a> used to encode the
returned digest. <strong>Default:</strong> <code>'hex'</code>.</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a></li>
</ul>
<p>A utility for creating one-shot hash digests of data. It can be faster than
the object-based <code>crypto.createHash()</code> when hashing a smaller amount of data
(&#x3C;= 5MB) that's readily available. If the data can be big or if it is streamed,
it's still recommended to use <code>crypto.createHash()</code> instead.</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> will
display the available digest algorithms.</p>
<p>Example:</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> crypto = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-comment">// Hashing a string and return the result as a hex-encoded string.</span>
<span class="hljs-keyword">const</span> string = <span class="hljs-string">'Node.js'</span>;
<span class="hljs-comment">// 10b3493287f831e81a438811a1ffba01f8cec4b7</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(crypto.<span class="hljs-title function_">hash</span>(<span class="hljs-string">'sha1'</span>, string));

<span class="hljs-comment">// Encode a base64-encoded string into a Buffer, hash it and return</span>
<span class="hljs-comment">// the result as a buffer.</span>
<span class="hljs-keyword">const</span> base64 = <span class="hljs-string">'Tm9kZS5qcw=='</span>;
<span class="hljs-comment">// &#x3C;Buffer 10 b3 49 32 87 f8 31 e8 1a 43 88 11 a1 ff ba 01 f8 ce c4 b7></span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(crypto.<span class="hljs-title function_">hash</span>(<span class="hljs-string">'sha1'</span>, <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(base64, <span class="hljs-string">'base64'</span>), <span class="hljs-string">'buffer'</span>));</code><code class="language-js mjs"><span class="hljs-keyword">import</span> crypto <span class="hljs-keyword">from</span> <span class="hljs-string">'node:crypto'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-comment">// Hashing a string and return the result as a hex-encoded string.</span>
<span class="hljs-keyword">const</span> string = <span class="hljs-string">'Node.js'</span>;
<span class="hljs-comment">// 10b3493287f831e81a438811a1ffba01f8cec4b7</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(crypto.<span class="hljs-title function_">hash</span>(<span class="hljs-string">'sha1'</span>, string));

<span class="hljs-comment">// Encode a base64-encoded string into a Buffer, hash it and return</span>
<span class="hljs-comment">// the result as a buffer.</span>
<span class="hljs-keyword">const</span> base64 = <span class="hljs-string">'Tm9kZS5qcw=='</span>;
<span class="hljs-comment">// &#x3C;Buffer 10 b3 49 32 87 f8 31 e8 1a 43 88 11 a1 ff ba 01 f8 ce c4 b7></span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(crypto.<span class="hljs-title function_">hash</span>(<span class="hljs-string">'sha1'</span>, <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(base64, <span class="hljs-string">'base64'</span>), <span class="hljs-string">'buffer'</span>));</code><button class="copy-button">copy</button></pre>
<h4><code>crypto.generateKey(type, options, callback)</code><span><a class="mark" href="#all_crypto_cryptogeneratekeytype-options-callback" id="all_crypto_cryptogeneratekeytype-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_generatekey_type_options_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p><span>Added in: v15.0.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> The intended use of the generated secret key. Currently
accepted values are <code>'hmac'</code> and <code>'aes'</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>
<ul>
<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 bit length of the key to generate. This must be a
value greater than 0.
<ul>
<li>If <code>type</code> is <code>'hmac'</code>, the minimum is 8, and the maximum length is
2<sup>31</sup>-1. If the value is not a multiple of 8, the generated
key will be truncated to <code>Math.floor(length / 8)</code>.</li>
<li>If <code>type</code> is <code>'aes'</code>, the length must be one of <code>128</code>, <code>192</code>, or <code>256</code>.</li>
</ul>
</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>
<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>key</code>: <a href="#all_crypto_class-keyobject" class="type">&#x3C;KeyObject></a></li>
</ul>
</li>
</ul>
<p>Asynchronously generates a new random secret key of the given <code>length</code>. The
<code>type</code> will determine which validations will be performed on the <code>length</code>.</p>

<pre class="with-14-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">const</span> {
  generateKey,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-title function_">generateKey</span>(<span class="hljs-string">'hmac'</span>, { <span class="hljs-attr">length</span>: <span class="hljs-number">512</span> }, <span class="hljs-function">(<span class="hljs-params">err, key</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(key.<span class="hljs-title function_">export</span>().<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));  <span class="hljs-comment">// 46e..........620</span>
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
  generateKey,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-title function_">generateKey</span>(<span class="hljs-string">'hmac'</span>, { <span class="hljs-attr">length</span>: <span class="hljs-number">512</span> }, <span class="hljs-function">(<span class="hljs-params">err, key</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(key.<span class="hljs-title function_">export</span>().<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));  <span class="hljs-comment">// 46e..........620</span>
});</code><button class="copy-button">copy</button></pre>
<p>The size of a generated HMAC key should not exceed the block size of the
underlying hash function. See <a href="#all_crypto_cryptocreatehmacalgorithm-key-options"><code>crypto.createHmac()</code></a> for more information.</p>
<h4><code>crypto.generateKeyPair(type, options, callback)</code><span><a class="mark" href="#all_crypto_cryptogeneratekeypairtype-options-callback" id="all_crypto_cryptogeneratekeypairtype-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_generatekeypair_type_options_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></tr>
<tr><td>v16.10.0</td>
<td><p>Add ability to define <code>RSASSA-PSS-params</code> sequence parameters for RSA-PSS keys pairs.</p></td></tr>
<tr><td>v13.9.0, v12.17.0</td>
<td><p>Add support for Diffie-Hellman.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>Add support for RSA-PSS key pairs.</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>'rsa-pss'</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><code>options</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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>hashAlgorithm</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Name of the message digest (RSA-PSS).</li>
<li><code>mgf1HashAlgorithm</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Name of the message digest used by
MGF1 (RSA-PSS).</li>
<li><code>saltLength</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Minimal salt length in bytes (RSA-PSS).</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="#all_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="#all_crypto_cryptogetdiffiehellmangroupname"><code>crypto.getDiffieHellman()</code></a>.</li>
<li><code>paramEncoding</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Must be <code>'named'</code> or <code>'explicit'</code> (EC).
<strong>Default:</strong> <code>'named'</code>.</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="#all_crypto_keyobjectexportoptions"><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="#all_crypto_keyobjectexportoptions"><code>keyObject.export()</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>
<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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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, RSA-PSS, 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="#all_crypto_keyobjectexportoptions"><code>keyObject.export()</code></a> had been called on its result. Otherwise,
the respective part of the key is returned as a <a href="#all_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 class="with-18-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">const</span> {
  generateKeyPair,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-title function_">generateKeyPair</span>(<span class="hljs-string">'rsa'</span>, {
  <span class="hljs-attr">modulusLength</span>: <span class="hljs-number">4096</span>,
  <span class="hljs-attr">publicKeyEncoding</span>: {
    <span class="hljs-attr">type</span>: <span class="hljs-string">'spki'</span>,
    <span class="hljs-attr">format</span>: <span class="hljs-string">'pem'</span>,
  },
  <span class="hljs-attr">privateKeyEncoding</span>: {
    <span class="hljs-attr">type</span>: <span class="hljs-string">'pkcs8'</span>,
    <span class="hljs-attr">format</span>: <span class="hljs-string">'pem'</span>,
    <span class="hljs-attr">cipher</span>: <span class="hljs-string">'aes-256-cbc'</span>,
    <span class="hljs-attr">passphrase</span>: <span class="hljs-string">'top secret'</span>,
  },
}, <span class="hljs-function">(<span class="hljs-params">err, publicKey, privateKey</span>) =></span> {
  <span class="hljs-comment">// Handle errors and use the generated key pair.</span>
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
  generateKeyPair,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-title function_">generateKeyPair</span>(<span class="hljs-string">'rsa'</span>, {
  <span class="hljs-attr">modulusLength</span>: <span class="hljs-number">4096</span>,
  <span class="hljs-attr">publicKeyEncoding</span>: {
    <span class="hljs-attr">type</span>: <span class="hljs-string">'spki'</span>,
    <span class="hljs-attr">format</span>: <span class="hljs-string">'pem'</span>,
  },
  <span class="hljs-attr">privateKeyEncoding</span>: {
    <span class="hljs-attr">type</span>: <span class="hljs-string">'pkcs8'</span>,
    <span class="hljs-attr">format</span>: <span class="hljs-string">'pem'</span>,
    <span class="hljs-attr">cipher</span>: <span class="hljs-string">'aes-256-cbc'</span>,
    <span class="hljs-attr">passphrase</span>: <span class="hljs-string">'top secret'</span>,
  },
}, <span class="hljs-function">(<span class="hljs-params">err, publicKey, privateKey</span>) =></span> {
  <span class="hljs-comment">// Handle errors and use the generated key pair.</span>
});</code><button class="copy-button">copy</button></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="#all_util_utilpromisifyoriginal"><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>
<h4><code>crypto.generateKeyPairSync(type, options)</code><span><a class="mark" href="#all_crypto_cryptogeneratekeypairsynctype-options" id="all_crypto_cryptogeneratekeypairsynctype-options">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_generatekeypairsync_type_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.10.0</td>
<td><p>Add ability to define <code>RSASSA-PSS-params</code> sequence parameters for RSA-PSS keys pairs.</p></td></tr>
<tr><td>v13.9.0, v12.17.0</td>
<td><p>Add support for Diffie-Hellman.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>Add support for RSA-PSS key pairs.</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>'rsa-pss'</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><code>options</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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>hashAlgorithm</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Name of the message digest (RSA-PSS).</li>
<li><code>mgf1HashAlgorithm</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Name of the message digest used by
MGF1 (RSA-PSS).</li>
<li><code>saltLength</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Minimal salt length in bytes (RSA-PSS).</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="#all_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="#all_crypto_cryptogetdiffiehellmangroupname"><code>crypto.getDiffieHellman()</code></a>.</li>
<li><code>paramEncoding</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Must be <code>'named'</code> or <code>'explicit'</code> (EC).
<strong>Default:</strong> <code>'named'</code>.</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="#all_crypto_keyobjectexportoptions"><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="#all_crypto_keyobjectexportoptions"><code>keyObject.export()</code></a>.</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>
<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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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, RSA-PSS, 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="#all_crypto_keyobjectexportoptions"><code>keyObject.export()</code></a> had been called on its result. Otherwise,
the respective part of the key is returned as a <a href="#all_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 class="with-22-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">const</span> {
  generateKeyPairSync,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> {
  publicKey,
  privateKey,
} = <span class="hljs-title function_">generateKeyPairSync</span>(<span class="hljs-string">'rsa'</span>, {
  <span class="hljs-attr">modulusLength</span>: <span class="hljs-number">4096</span>,
  <span class="hljs-attr">publicKeyEncoding</span>: {
    <span class="hljs-attr">type</span>: <span class="hljs-string">'spki'</span>,
    <span class="hljs-attr">format</span>: <span class="hljs-string">'pem'</span>,
  },
  <span class="hljs-attr">privateKeyEncoding</span>: {
    <span class="hljs-attr">type</span>: <span class="hljs-string">'pkcs8'</span>,
    <span class="hljs-attr">format</span>: <span class="hljs-string">'pem'</span>,
    <span class="hljs-attr">cipher</span>: <span class="hljs-string">'aes-256-cbc'</span>,
    <span class="hljs-attr">passphrase</span>: <span class="hljs-string">'top secret'</span>,
  },
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
  generateKeyPairSync,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> {
  publicKey,
  privateKey,
} = <span class="hljs-title function_">generateKeyPairSync</span>(<span class="hljs-string">'rsa'</span>, {
  <span class="hljs-attr">modulusLength</span>: <span class="hljs-number">4096</span>,
  <span class="hljs-attr">publicKeyEncoding</span>: {
    <span class="hljs-attr">type</span>: <span class="hljs-string">'spki'</span>,
    <span class="hljs-attr">format</span>: <span class="hljs-string">'pem'</span>,
  },
  <span class="hljs-attr">privateKeyEncoding</span>: {
    <span class="hljs-attr">type</span>: <span class="hljs-string">'pkcs8'</span>,
    <span class="hljs-attr">format</span>: <span class="hljs-string">'pem'</span>,
    <span class="hljs-attr">cipher</span>: <span class="hljs-string">'aes-256-cbc'</span>,
    <span class="hljs-attr">passphrase</span>: <span class="hljs-string">'top secret'</span>,
  },
});</code><button class="copy-button">copy</button></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>
<h4><code>crypto.generateKeySync(type, options)</code><span><a class="mark" href="#all_crypto_cryptogeneratekeysynctype-options" id="all_crypto_cryptogeneratekeysynctype-options">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_generatekeysync_type_options"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.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 intended use of the generated secret key. Currently
accepted values are <code>'hmac'</code> and <code>'aes'</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>
<ul>
<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 bit length of the key to generate.
<ul>
<li>If <code>type</code> is <code>'hmac'</code>, the minimum is 8, and the maximum length is
2<sup>31</sup>-1. If the value is not a multiple of 8, the generated
key will be truncated to <code>Math.floor(length / 8)</code>.</li>
<li>If <code>type</code> is <code>'aes'</code>, the length must be one of <code>128</code>, <code>192</code>, or <code>256</code>.</li>
</ul>
</li>
</ul>
</li>
<li>Returns: <a href="#all_crypto_class-keyobject" class="type">&#x3C;KeyObject></a></li>
</ul>
<p>Synchronously generates a new random secret key of the given <code>length</code>. The
<code>type</code> will determine which validations will be performed on the <code>length</code>.</p>

<pre class="with-18-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">const</span> {
  generateKeySync,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> key = <span class="hljs-title function_">generateKeySync</span>(<span class="hljs-string">'hmac'</span>, { <span class="hljs-attr">length</span>: <span class="hljs-number">512</span> });
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(key.<span class="hljs-title function_">export</span>().<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));  <span class="hljs-comment">// e89..........41e</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
  generateKeySync,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> key = <span class="hljs-title function_">generateKeySync</span>(<span class="hljs-string">'hmac'</span>, { <span class="hljs-attr">length</span>: <span class="hljs-number">512</span> });
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(key.<span class="hljs-title function_">export</span>().<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));  <span class="hljs-comment">// e89..........41e</span></code><button class="copy-button">copy</button></pre>
<p>The size of a generated HMAC key should not exceed the block size of the
underlying hash function. See <a href="#all_crypto_cryptocreatehmacalgorithm-key-options"><code>crypto.createHmac()</code></a> for more information.</p>
<h4><code>crypto.generatePrime(size[, options[, callback]])</code><span><a class="mark" href="#all_crypto_cryptogenerateprimesize-options-callback" id="all_crypto_cryptogenerateprimesize-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_generateprime_size_options_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></tr>
<tr><td>v15.8.0</td>
<td><p><span>Added in: v15.8.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;number></a> The size (in bits) of the prime to generate.</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>
<ul>
<li><code>add</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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></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/BigInt" class="type">&#x3C;bigint></a></li>
<li><code>rem</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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></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/BigInt" class="type">&#x3C;bigint></a></li>
<li><code>safe</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>bigint</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 generated prime is returned
as a <code>bigint</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>
<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>prime</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/BigInt" class="type">&#x3C;bigint></a></li>
</ul>
</li>
</ul>
<p>Generates a pseudorandom prime of <code>size</code> bits.</p>
<p>If <code>options.safe</code> is <code>true</code>, the prime will be a safe prime -- that is,
<code>(prime - 1) / 2</code> will also be a prime.</p>
<p>The <code>options.add</code> and <code>options.rem</code> parameters can be used to enforce additional
requirements, e.g., for Diffie-Hellman:</p>
<ul>
<li>If <code>options.add</code> and <code>options.rem</code> are both set, the prime will satisfy the
condition that <code>prime % add = rem</code>.</li>
<li>If only <code>options.add</code> is set and <code>options.safe</code> is not <code>true</code>, the prime will
satisfy the condition that <code>prime % add = 1</code>.</li>
<li>If only <code>options.add</code> is set and <code>options.safe</code> is set to <code>true</code>, the prime
will instead satisfy the condition that <code>prime % add = 3</code>. This is necessary
because <code>prime % add = 1</code> for <code>options.add > 2</code> would contradict the condition
enforced by <code>options.safe</code>.</li>
<li><code>options.rem</code> is ignored if <code>options.add</code> is not given.</li>
</ul>
<p>Both <code>options.add</code> and <code>options.rem</code> must be encoded as big-endian sequences
if given as an <code>ArrayBuffer</code>, <code>SharedArrayBuffer</code>, <code>TypedArray</code>, <code>Buffer</code>, or
<code>DataView</code>.</p>
<p>By default, the prime is encoded as a big-endian sequence of octets
in an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a>. If the <code>bigint</code> option is <code>true</code>, then a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type">&#x3C;bigint></a>
is provided.</p>
<h4><code>crypto.generatePrimeSync(size[, options])</code><span><a class="mark" href="#all_crypto_cryptogenerateprimesyncsize-options" id="all_crypto_cryptogenerateprimesyncsize-options">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_generateprimesync_size_options"></a></h4>
<div class="api_metadata">
<span>Added in: v15.8.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;number></a> The size (in bits) of the prime to generate.</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>
<ul>
<li><code>add</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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></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/BigInt" class="type">&#x3C;bigint></a></li>
<li><code>rem</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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> | <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></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/BigInt" class="type">&#x3C;bigint></a></li>
<li><code>safe</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>bigint</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 generated prime is returned
as a <code>bigint</code>.</li>
</ul>
</li>
<li>Returns: <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/BigInt" class="type">&#x3C;bigint></a></li>
</ul>
<p>Generates a pseudorandom prime of <code>size</code> bits.</p>
<p>If <code>options.safe</code> is <code>true</code>, the prime will be a safe prime -- that is,
<code>(prime - 1) / 2</code> will also be a prime.</p>
<p>The <code>options.add</code> and <code>options.rem</code> parameters can be used to enforce additional
requirements, e.g., for Diffie-Hellman:</p>
<ul>
<li>If <code>options.add</code> and <code>options.rem</code> are both set, the prime will satisfy the
condition that <code>prime % add = rem</code>.</li>
<li>If only <code>options.add</code> is set and <code>options.safe</code> is not <code>true</code>, the prime will
satisfy the condition that <code>prime % add = 1</code>.</li>
<li>If only <code>options.add</code> is set and <code>options.safe</code> is set to <code>true</code>, the prime
will instead satisfy the condition that <code>prime % add = 3</code>. This is necessary
because <code>prime % add = 1</code> for <code>options.add > 2</code> would contradict the condition
enforced by <code>options.safe</code>.</li>
<li><code>options.rem</code> is ignored if <code>options.add</code> is not given.</li>
</ul>
<p>Both <code>options.add</code> and <code>options.rem</code> must be encoded as big-endian sequences
if given as an <code>ArrayBuffer</code>, <code>SharedArrayBuffer</code>, <code>TypedArray</code>, <code>Buffer</code>, or
<code>DataView</code>.</p>
<p>By default, the prime is encoded as a big-endian sequence of octets
in an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a>. If the <code>bigint</code> option is <code>true</code>, then a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type">&#x3C;bigint></a>
is provided.</p>
<h4><code>crypto.getCipherInfo(nameOrNid[, options])</code><span><a class="mark" href="#all_crypto_cryptogetcipherinfonameornid-options" id="all_crypto_cryptogetcipherinfonameornid-options">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_getcipherinfo_nameornid_options"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li><code>nameOrNid</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 name or nid of the cipher to query.</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>
<ul>
<li><code>keyLength</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> A test key length.</li>
<li><code>ivLength</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> A test IV length.</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>
<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 cipher</li>
<li><code>nid</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The nid of the cipher</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> The block size of the cipher in bytes. This property
is omitted when <code>mode</code> is <code>'stream'</code>.</li>
<li><code>ivLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The expected or default initialization vector length in
bytes. This property is omitted if the cipher does not use an initialization
vector.</li>
<li><code>keyLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The expected or default key length in bytes.</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> The cipher mode. One of <code>'cbc'</code>, <code>'ccm'</code>, <code>'cfb'</code>, <code>'ctr'</code>,
<code>'ecb'</code>, <code>'gcm'</code>, <code>'ocb'</code>, <code>'ofb'</code>, <code>'stream'</code>, <code>'wrap'</code>, <code>'xts'</code>.</li>
</ul>
</li>
</ul>
<p>Returns information about a given cipher.</p>
<p>Some ciphers accept variable length keys and initialization vectors. By default,
the <code>crypto.getCipherInfo()</code> method will return the default values for these
ciphers. To test if a given key length or iv length is acceptable for given
cipher, use the <code>keyLength</code> and <code>ivLength</code> options. If the given values are
unacceptable, <code>undefined</code> will be returned.</p>
<h4><code>crypto.getCiphers()</code><span><a class="mark" href="#all_crypto_cryptogetciphers" id="all_crypto_cryptogetciphers">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_getciphers"></a></h4>
<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 class="with-13-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">const</span> {
  getCiphers,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getCiphers</span>()); <span class="hljs-comment">// ['aes-128-cbc', 'aes-128-ccm', ...]</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
  getCiphers,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getCiphers</span>()); <span class="hljs-comment">// ['aes-128-cbc', 'aes-128-ccm', ...]</span></code><button class="copy-button">copy</button></pre>
<h4><code>crypto.getCurves()</code><span><a class="mark" href="#all_crypto_cryptogetcurves" id="all_crypto_cryptogetcurves">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_getcurves"></a></h4>
<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 class="with-12-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">const</span> {
  getCurves,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getCurves</span>()); <span class="hljs-comment">// ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
  getCurves,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getCurves</span>()); <span class="hljs-comment">// ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]</span></code><button class="copy-button">copy</button></pre>
<h4><code>crypto.getDiffieHellman(groupName)</code><span><a class="mark" href="#all_crypto_cryptogetdiffiehellmangroupname" id="all_crypto_cryptogetdiffiehellmangroupname">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_getdiffiehellman_groupname"></a></h4>
<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="#all_crypto_class-diffiehellmangroup" class="type">&#x3C;DiffieHellmanGroup></a></li>
</ul>
<p>Creates a predefined <code>DiffieHellmanGroup</code> key exchange object. The
supported groups are listed in the documentation for <a href="#all_crypto_class-diffiehellmangroup"><code>DiffieHellmanGroup</code></a>.</p>
<p>The returned object mimics the interface of objects created by
<a href="#all_crypto_cryptocreatediffiehellmanprime-primeencoding-generator-generatorencoding"><code>crypto.createDiffieHellman()</code></a>, but will not allow changing
the keys (with <a href="#all_crypto_diffiehellmansetpublickeypublickey-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 class="with-19-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">const</span> {
  getDiffieHellman,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> alice = <span class="hljs-title function_">getDiffieHellman</span>(<span class="hljs-string">'modp14'</span>);
<span class="hljs-keyword">const</span> bob = <span class="hljs-title function_">getDiffieHellman</span>(<span class="hljs-string">'modp14'</span>);

alice.<span class="hljs-title function_">generateKeys</span>();
bob.<span class="hljs-title function_">generateKeys</span>();

<span class="hljs-keyword">const</span> aliceSecret = alice.<span class="hljs-title function_">computeSecret</span>(bob.<span class="hljs-title function_">getPublicKey</span>(), <span class="hljs-literal">null</span>, <span class="hljs-string">'hex'</span>);
<span class="hljs-keyword">const</span> bobSecret = bob.<span class="hljs-title function_">computeSecret</span>(alice.<span class="hljs-title function_">getPublicKey</span>(), <span class="hljs-literal">null</span>, <span class="hljs-string">'hex'</span>);

<span class="hljs-comment">/* aliceSecret and bobSecret should be the same */</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(aliceSecret === bobSecret);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
  getDiffieHellman,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> alice = <span class="hljs-title function_">getDiffieHellman</span>(<span class="hljs-string">'modp14'</span>);
<span class="hljs-keyword">const</span> bob = <span class="hljs-title function_">getDiffieHellman</span>(<span class="hljs-string">'modp14'</span>);

alice.<span class="hljs-title function_">generateKeys</span>();
bob.<span class="hljs-title function_">generateKeys</span>();

<span class="hljs-keyword">const</span> aliceSecret = alice.<span class="hljs-title function_">computeSecret</span>(bob.<span class="hljs-title function_">getPublicKey</span>(), <span class="hljs-literal">null</span>, <span class="hljs-string">'hex'</span>);
<span class="hljs-keyword">const</span> bobSecret = bob.<span class="hljs-title function_">computeSecret</span>(alice.<span class="hljs-title function_">getPublicKey</span>(), <span class="hljs-literal">null</span>, <span class="hljs-string">'hex'</span>);

<span class="hljs-comment">/* aliceSecret and bobSecret should be the same */</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(aliceSecret === bobSecret);</code><button class="copy-button">copy</button></pre>
<h4><code>crypto.getFips()</code><span><a class="mark" href="#all_crypto_cryptogetfips" id="all_crypto_cryptogetfips">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_getfips"></a></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/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>
<h4><code>crypto.getHashes()</code><span><a class="mark" href="#all_crypto_cryptogethashes" id="all_crypto_cryptogethashes">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_gethashes"></a></h4>
<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 class="with-12-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">const</span> {
  getHashes,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getHashes</span>()); <span class="hljs-comment">// ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
  getHashes,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getHashes</span>()); <span class="hljs-comment">// ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]</span></code><button class="copy-button">copy</button></pre>
<h4><code>crypto.getRandomValues(typedArray)</code><span><a class="mark" href="#all_crypto_cryptogetrandomvaluestypedarray" id="all_crypto_cryptogetrandomvaluestypedarray">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_getrandomvalues_typedarray"></a></h4>
<div class="api_metadata">
<span>Added in: v17.4.0</span>
</div>
<ul>
<li><code>typedArray</code> <a href="#all_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></li>
<li>Returns: <a href="#all_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> Returns <code>typedArray</code>.</li>
</ul>
<p>A convenient alias for <a href="#all_webcrypto_cryptogetrandomvaluestypedarray"><code>crypto.webcrypto.getRandomValues()</code></a>. This
implementation is not compliant with the Web Crypto spec, to write
web-compatible code use <a href="#all_webcrypto_cryptogetrandomvaluestypedarray"><code>crypto.webcrypto.getRandomValues()</code></a> instead.</p>
<h4><code>crypto.hkdf(digest, ikm, salt, info, keylen, callback)</code><span><a class="mark" href="#all_crypto_cryptohkdfdigest-ikm-salt-info-keylen-callback" id="all_crypto_cryptohkdfdigest-ikm-salt-info-keylen-callback">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_hkdf_digest_ikm_salt_info_keylen_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></tr>
<tr><td>v18.8.0, v16.18.0</td>
<td><p>The input keying material can now be zero-length.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p><span>Added in: v15.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>digest</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The digest algorithm to use.</li>
<li><code>ikm</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/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_crypto_class-keyobject" class="type">&#x3C;KeyObject></a> The input
keying material. Must be provided but can be zero-length.</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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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 salt value. Must
be provided but can be zero-length.</li>
<li><code>info</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/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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> Additional info value.
Must be provided but can be zero-length, and cannot be more than 1024 bytes.</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> The length of the key to generate. Must be greater than 0.
The maximum allowable value is <code>255</code> times the number of bytes produced by
the selected digest function (e.g. <code>sha512</code> generates 64-byte hashes, making
the maximum HKDF output 16320 bytes).</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>
<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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a></li>
</ul>
</li>
</ul>
<p>HKDF is a simple key derivation function defined in RFC 5869. The given <code>ikm</code>,
<code>salt</code> and <code>info</code> are used with the <code>digest</code> to derive a key of <code>keylen</code> bytes.</p>
<p>The supplied <code>callback</code> function is called with two arguments: <code>err</code> and
<code>derivedKey</code>. If an errors occurs while deriving the key, <code>err</code> will be set;
otherwise <code>err</code> will be <code>null</code>. The successfully generated <code>derivedKey</code> will
be passed to the callback as an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a>. An error will be thrown if any
of the input arguments specify invalid values or types.</p>

<pre class="with-37-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> {
  hkdf,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-title function_">hkdf</span>(<span class="hljs-string">'sha512'</span>, <span class="hljs-string">'key'</span>, <span class="hljs-string">'salt'</span>, <span class="hljs-string">'info'</span>, <span class="hljs-number">64</span>, <span class="hljs-function">(<span class="hljs-params">err, derivedKey</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(derivedKey).<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));  <span class="hljs-comment">// '24156e2...5391653'</span>
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
  hkdf,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-title function_">hkdf</span>(<span class="hljs-string">'sha512'</span>, <span class="hljs-string">'key'</span>, <span class="hljs-string">'salt'</span>, <span class="hljs-string">'info'</span>, <span class="hljs-number">64</span>, <span class="hljs-function">(<span class="hljs-params">err, derivedKey</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(derivedKey).<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));  <span class="hljs-comment">// '24156e2...5391653'</span>
});</code><button class="copy-button">copy</button></pre>
<h4><code>crypto.hkdfSync(digest, ikm, salt, info, keylen)</code><span><a class="mark" href="#all_crypto_cryptohkdfsyncdigest-ikm-salt-info-keylen" id="all_crypto_cryptohkdfsyncdigest-ikm-salt-info-keylen">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_hkdfsync_digest_ikm_salt_info_keylen"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.8.0, v16.18.0</td>
<td><p>The input keying material can now be zero-length.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p><span>Added in: v15.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>digest</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The digest algorithm to use.</li>
<li><code>ikm</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/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_crypto_class-keyobject" class="type">&#x3C;KeyObject></a> The input
keying material. Must be provided but can be zero-length.</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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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 salt value. Must
be provided but can be zero-length.</li>
<li><code>info</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/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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> Additional info value.
Must be provided but can be zero-length, and cannot be more than 1024 bytes.</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> The length of the key to generate. Must be greater than 0.
The maximum allowable value is <code>255</code> times the number of bytes produced by
the selected digest function (e.g. <code>sha512</code> generates 64-byte hashes, making
the maximum HKDF output 16320 bytes).</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a></li>
</ul>
<p>Provides a synchronous HKDF key derivation function as defined in RFC 5869. The
given <code>ikm</code>, <code>salt</code> and <code>info</code> are used with the <code>digest</code> to derive a key of
<code>keylen</code> bytes.</p>
<p>The successfully generated <code>derivedKey</code> will be returned as an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a>.</p>
<p>An error will be thrown if any of the input arguments specify invalid values or
types, or if the derived key cannot be generated.</p>

<pre class="with-37-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> {
  hkdfSync,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> derivedKey = <span class="hljs-title function_">hkdfSync</span>(<span class="hljs-string">'sha512'</span>, <span class="hljs-string">'key'</span>, <span class="hljs-string">'salt'</span>, <span class="hljs-string">'info'</span>, <span class="hljs-number">64</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(derivedKey).<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));  <span class="hljs-comment">// '24156e2...5391653'</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
  hkdfSync,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> derivedKey = <span class="hljs-title function_">hkdfSync</span>(<span class="hljs-string">'sha512'</span>, <span class="hljs-string">'key'</span>, <span class="hljs-string">'salt'</span>, <span class="hljs-string">'info'</span>, <span class="hljs-number">64</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(derivedKey).<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));  <span class="hljs-comment">// '24156e2...5391653'</span></code><button class="copy-button">copy</button></pre>
<h4><code>crypto.pbkdf2(password, salt, iterations, keylen, digest, callback)</code><span><a class="mark" href="#all_crypto_cryptopbkdf2password-salt-iterations-keylen-digest-callback" id="all_crypto_cryptopbkdf2password-salt-iterations-keylen-digest-callback">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p>The password and salt arguments can also be ArrayBuffer instances.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>The <code>iterations</code> parameter is now restricted to positive values. Earlier releases treated other values as one.</p></td></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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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="#all_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>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>
<p>When passing strings for <code>password</code> or <code>salt</code>, please consider
<a href="#all_crypto_using-strings-as-inputs-to-cryptographic-apis">caveats when using strings as inputs to cryptographic APIs</a>.</p>

<pre class="with-9-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">const</span> {
  pbkdf2,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-title function_">pbkdf2</span>(<span class="hljs-string">'secret'</span>, <span class="hljs-string">'salt'</span>, <span class="hljs-number">100000</span>, <span class="hljs-number">64</span>, <span class="hljs-string">'sha512'</span>, <span class="hljs-function">(<span class="hljs-params">err, derivedKey</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(derivedKey.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));  <span class="hljs-comment">// '3745e48...08d59ae'</span>
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
  pbkdf2,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-title function_">pbkdf2</span>(<span class="hljs-string">'secret'</span>, <span class="hljs-string">'salt'</span>, <span class="hljs-number">100000</span>, <span class="hljs-number">64</span>, <span class="hljs-string">'sha512'</span>, <span class="hljs-function">(<span class="hljs-params">err, derivedKey</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(derivedKey.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));  <span class="hljs-comment">// '3745e48...08d59ae'</span>
});</code><button class="copy-button">copy</button></pre>
<p>An array of supported digest functions can be retrieved using
<a href="#all_crypto_cryptogethashes"><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="#all_cli_uv_threadpool_sizesize"><code>UV_THREADPOOL_SIZE</code></a> documentation for more information.</p>
<h4><code>crypto.pbkdf2Sync(password, salt, iterations, keylen, digest)</code><span><a class="mark" href="#all_crypto_cryptopbkdf2syncpassword-salt-iterations-keylen-digest" id="all_crypto_cryptopbkdf2syncpassword-salt-iterations-keylen-digest">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_pbkdf2sync_password_salt_iterations_keylen_digest"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.0.0</td>
<td><p>The <code>iterations</code> parameter is now restricted to positive values. Earlier releases treated other values as one.</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.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="#all_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="#all_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="#all_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>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>
<p>When passing strings for <code>password</code> or <code>salt</code>, please consider
<a href="#all_crypto_using-strings-as-inputs-to-cryptographic-apis">caveats when using strings as inputs to cryptographic APIs</a>.</p>

<pre class="with-13-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">const</span> {
  pbkdf2Sync,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> key = <span class="hljs-title function_">pbkdf2Sync</span>(<span class="hljs-string">'secret'</span>, <span class="hljs-string">'salt'</span>, <span class="hljs-number">100000</span>, <span class="hljs-number">64</span>, <span class="hljs-string">'sha512'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(key.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));  <span class="hljs-comment">// '3745e48...08d59ae'</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
  pbkdf2Sync,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> key = <span class="hljs-title function_">pbkdf2Sync</span>(<span class="hljs-string">'secret'</span>, <span class="hljs-string">'salt'</span>, <span class="hljs-number">100000</span>, <span class="hljs-number">64</span>, <span class="hljs-string">'sha512'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(key.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));  <span class="hljs-comment">// '3745e48...08d59ae'</span></code><button class="copy-button">copy</button></pre>
<p>An array of supported digest functions can be retrieved using
<a href="#all_crypto_cryptogethashes"><code>crypto.getHashes()</code></a>.</p>
<h4><code>crypto.privateDecrypt(privateKey, buffer)</code><span><a class="mark" href="#all_crypto_cryptoprivatedecryptprivatekey-buffer" id="all_crypto_cryptoprivatedecryptprivatekey-buffer">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_privatedecrypt_privatekey_buffer"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v21.6.2, v20.11.1, v18.19.1</td>
<td><p>The <code>RSA_PKCS1_PADDING</code> padding was disabled unless the OpenSSL build supports implicit rejection.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p>Added string, ArrayBuffer, and CryptoKey as allowable key types. The oaepLabel can be an ArrayBuffer. The buffer can be a string or ArrayBuffer. All types that accept buffers are limited to a maximum of 2 ** 31 - 1 bytes.</p></td></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>
<!--lint disable maximum-line-length remark-lint-->
<ul>
<li><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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_crypto_class-keyobject" class="type">&#x3C;KeyObject></a> | <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></a>
<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="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/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_crypto_cryptoconstants" 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="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/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> A new <code>Buffer</code> with the decrypted content.</li>
</ul>
<!--lint enable maximum-line-length remark-lint-->
<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="#all_crypto_cryptopublicencryptkey-buffer"><code>crypto.publicEncrypt()</code></a>.</p>
<p>If <code>privateKey</code> is not a <a href="#all_crypto_class-keyobject"><code>KeyObject</code></a>, this function behaves as if
<code>privateKey</code> had been passed to <a href="#all_crypto_cryptocreateprivatekeykey"><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>
<p>Using <code>crypto.constants.RSA_PKCS1_PADDING</code> in <a href="#all_crypto_cryptoprivatedecryptprivatekey-buffer"><code>crypto.privateDecrypt()</code></a>
requires OpenSSL to support implicit rejection (<code>rsa_pkcs1_implicit_rejection</code>).
If the version of OpenSSL used by Node.js does not support this feature,
attempting to use <code>RSA_PKCS1_PADDING</code> will fail.</p>
<h4><code>crypto.privateEncrypt(privateKey, buffer)</code><span><a class="mark" href="#all_crypto_cryptoprivateencryptprivatekey-buffer" id="all_crypto_cryptoprivateencryptprivatekey-buffer">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_privateencrypt_privatekey_buffer"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>Added string, ArrayBuffer, and CryptoKey as allowable key types. The passphrase can be an ArrayBuffer. The buffer can be a string or ArrayBuffer. All types that accept buffers are limited to a maximum of 2 ** 31 - 1 bytes.</p></td></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>
<!--lint disable maximum-line-length remark-lint-->
<ul>
<li><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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_crypto_class-keyobject" class="type">&#x3C;KeyObject></a> | <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></a>
<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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_crypto_class-keyobject" class="type">&#x3C;KeyObject></a> | <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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 optional
passphrase for the private key.</li>
<li><code>padding</code> <a href="#all_crypto_cryptoconstants" 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>
<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 string encoding to use when <code>buffer</code>, <code>key</code>,
or <code>passphrase</code> are strings.</li>
</ul>
</li>
<li><code>buffer</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/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> A new <code>Buffer</code> with the encrypted content.</li>
</ul>
<!--lint enable maximum-line-length remark-lint-->
<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="#all_crypto_cryptopublicdecryptkey-buffer"><code>crypto.publicDecrypt()</code></a>.</p>
<p>If <code>privateKey</code> is not a <a href="#all_crypto_class-keyobject"><code>KeyObject</code></a>, this function behaves as if
<code>privateKey</code> had been passed to <a href="#all_crypto_cryptocreateprivatekeykey"><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>
<h4><code>crypto.publicDecrypt(key, buffer)</code><span><a class="mark" href="#all_crypto_cryptopublicdecryptkey-buffer" id="all_crypto_cryptopublicdecryptkey-buffer">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_publicdecrypt_key_buffer"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>Added string, ArrayBuffer, and CryptoKey as allowable key types. The passphrase can be an ArrayBuffer. The buffer can be a string or ArrayBuffer. All types that accept buffers are limited to a maximum of 2 ** 31 - 1 bytes.</p></td></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>
<!--lint disable maximum-line-length remark-lint-->
<ul>
<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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_crypto_class-keyobject" class="type">&#x3C;KeyObject></a> | <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></a>
<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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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 optional
passphrase for the private key.</li>
<li><code>padding</code> <a href="#all_crypto_cryptoconstants" 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>
<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 string encoding to use when <code>buffer</code>, <code>key</code>,
or <code>passphrase</code> are strings.</li>
</ul>
</li>
<li><code>buffer</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/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> A new <code>Buffer</code> with the decrypted content.</li>
</ul>
<!--lint enable maximum-line-length remark-lint-->
<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="#all_crypto_cryptoprivateencryptprivatekey-buffer"><code>crypto.privateEncrypt()</code></a>.</p>
<p>If <code>key</code> is not a <a href="#all_crypto_class-keyobject"><code>KeyObject</code></a>, this function behaves as if
<code>key</code> had been passed to <a href="#all_crypto_cryptocreatepublickeykey"><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>
<h4><code>crypto.publicEncrypt(key, buffer)</code><span><a class="mark" href="#all_crypto_cryptopublicencryptkey-buffer" id="all_crypto_cryptopublicencryptkey-buffer">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_publicencrypt_key_buffer"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>Added string, ArrayBuffer, and CryptoKey as allowable key types. The oaepLabel and passphrase can be ArrayBuffers. The buffer can be a string or ArrayBuffer. All types that accept buffers are limited to a maximum of 2 ** 31 - 1 bytes.</p></td></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>
<!--lint disable maximum-line-length remark-lint-->
<ul>
<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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_crypto_class-keyobject" class="type">&#x3C;KeyObject></a> | <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></a>
<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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_crypto_class-keyobject" class="type">&#x3C;KeyObject></a> | <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></a>
A PEM encoded public or private key, <a href="#all_crypto_class-keyobject" class="type">&#x3C;KeyObject></a>, or <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></a>.</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="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/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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 optional
passphrase for the private key.</li>
<li><code>padding</code> <a href="#all_crypto_cryptoconstants" 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>
<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 string encoding to use when <code>buffer</code>, <code>key</code>,
<code>oaepLabel</code>, or <code>passphrase</code> are strings.</li>
</ul>
</li>
<li><code>buffer</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/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> A new <code>Buffer</code> with the encrypted content.</li>
</ul>
<!--lint enable maximum-line-length remark-lint-->
<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="#all_crypto_cryptoprivatedecryptprivatekey-buffer"><code>crypto.privateDecrypt()</code></a>.</p>
<p>If <code>key</code> is not a <a href="#all_crypto_class-keyobject"><code>KeyObject</code></a>, this function behaves as if
<code>key</code> had been passed to <a href="#all_crypto_cryptocreatepublickeykey"><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>
<h4><code>crypto.randomBytes(size[, callback])</code><span><a class="mark" href="#all_crypto_cryptorandombytessize-callback" id="all_crypto_cryptorandombytessize-callback">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_randombytes_size_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></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> The number of bytes to generate.  The <code>size</code> must
not be larger than <code>2**31 - 1</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>
<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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a></li>
</ul>
</li>
<li>Returns: <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> if the <code>callback</code> function is not provided.</li>
</ul>
<p>Generates cryptographically strong pseudorandom 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 class="with-15-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// Asynchronous</span>
<span class="hljs-keyword">const</span> {
  randomBytes,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-title function_">randomBytes</span>(<span class="hljs-number">256</span>, <span class="hljs-function">(<span class="hljs-params">err, buf</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${buf.length}</span> bytes of random data: <span class="hljs-subst">${buf.toString(<span class="hljs-string">'hex'</span>)}</span>`</span>);
});</code><code class="language-js cjs"><span class="hljs-comment">// Asynchronous</span>
<span class="hljs-keyword">const</span> {
  randomBytes,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-title function_">randomBytes</span>(<span class="hljs-number">256</span>, <span class="hljs-function">(<span class="hljs-params">err, buf</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${buf.length}</span> bytes of random data: <span class="hljs-subst">${buf.toString(<span class="hljs-string">'hex'</span>)}</span>`</span>);
});</code><button class="copy-button">copy</button></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 class="with-14-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// Synchronous</span>
<span class="hljs-keyword">const</span> {
  randomBytes,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title function_">randomBytes</span>(<span class="hljs-number">256</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(
  <span class="hljs-string">`<span class="hljs-subst">${buf.length}</span> bytes of random data: <span class="hljs-subst">${buf.toString(<span class="hljs-string">'hex'</span>)}</span>`</span>);</code><code class="language-js cjs"><span class="hljs-comment">// Synchronous</span>
<span class="hljs-keyword">const</span> {
  randomBytes,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title function_">randomBytes</span>(<span class="hljs-number">256</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(
  <span class="hljs-string">`<span class="hljs-subst">${buf.length}</span> bytes of random data: <span class="hljs-subst">${buf.toString(<span class="hljs-string">'hex'</span>)}</span>`</span>);</code><button class="copy-button">copy</button></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="#all_cli_uv_threadpool_sizesize"><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>
<h4><code>crypto.randomFillSync(buffer[, offset][, size])</code><span><a class="mark" href="#all_crypto_cryptorandomfillsyncbuffer-offset-size" id="all_crypto_cryptorandomfillsyncbuffer-offset-size">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_randomfillsync_buffer_offset_size"></a></h4>
<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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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. The
size of the provided <code>buffer</code> must not be larger than <code>2**31 - 1</code>.</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>. The <code>size</code> must
not be larger than <code>2**31 - 1</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_crypto_cryptorandomfillbuffer-offset-size-callback"><code>crypto.randomFill()</code></a>.</p>

<pre class="with-55-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> { randomFillSync } = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">10</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">randomFillSync</span>(buf).<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));

<span class="hljs-title function_">randomFillSync</span>(buf, <span class="hljs-number">5</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));

<span class="hljs-comment">// The above is equivalent to the following:</span>
<span class="hljs-title function_">randomFillSync</span>(buf, <span class="hljs-number">5</span>, <span class="hljs-number">5</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { randomFillSync } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">10</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">randomFillSync</span>(buf).<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));

<span class="hljs-title function_">randomFillSync</span>(buf, <span class="hljs-number">5</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));

<span class="hljs-comment">// The above is equivalent to the following:</span>
<span class="hljs-title function_">randomFillSync</span>(buf, <span class="hljs-number">5</span>, <span class="hljs-number">5</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));</code><button class="copy-button">copy</button></pre>
<p>Any <code>ArrayBuffer</code>, <code>TypedArray</code> or <code>DataView</code> instance may be passed as
<code>buffer</code>.</p>

<pre class="with-55-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> { randomFillSync } = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> a = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint32Array</span>(<span class="hljs-number">10</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-title function_">randomFillSync</span>(a).<span class="hljs-property">buffer</span>,
                        a.<span class="hljs-property">byteOffset</span>, a.<span class="hljs-property">byteLength</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));

<span class="hljs-keyword">const</span> b = <span class="hljs-keyword">new</span> <span class="hljs-title class_">DataView</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>(<span class="hljs-number">10</span>));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-title function_">randomFillSync</span>(b).<span class="hljs-property">buffer</span>,
                        b.<span class="hljs-property">byteOffset</span>, b.<span class="hljs-property">byteLength</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));

<span class="hljs-keyword">const</span> c = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>(<span class="hljs-number">10</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-title function_">randomFillSync</span>(c)).<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { randomFillSync } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> a = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint32Array</span>(<span class="hljs-number">10</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-title function_">randomFillSync</span>(a).<span class="hljs-property">buffer</span>,
                        a.<span class="hljs-property">byteOffset</span>, a.<span class="hljs-property">byteLength</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));

<span class="hljs-keyword">const</span> b = <span class="hljs-keyword">new</span> <span class="hljs-title class_">DataView</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>(<span class="hljs-number">10</span>));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-title function_">randomFillSync</span>(b).<span class="hljs-property">buffer</span>,
                        b.<span class="hljs-property">byteOffset</span>, b.<span class="hljs-property">byteLength</span>).<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));

<span class="hljs-keyword">const</span> c = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>(<span class="hljs-number">10</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-title function_">randomFillSync</span>(c)).<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));</code><button class="copy-button">copy</button></pre>
<h4><code>crypto.randomFill(buffer[, offset][, size], callback)</code><span><a class="mark" href="#all_crypto_cryptorandomfillbuffer-offset-size-callback" id="all_crypto_cryptorandomfillbuffer-offset-size-callback">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_randomfill_buffer_offset_size_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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. The
size of the provided <code>buffer</code> must not be larger than <code>2**31 - 1</code>.</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>. The <code>size</code> must
not be larger than <code>2**31 - 1</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="#all_crypto_cryptorandombytessize-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 class="with-51-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> { randomFill } = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">10</span>);
<span class="hljs-title function_">randomFill</span>(buf, <span class="hljs-function">(<span class="hljs-params">err, buf</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
});

<span class="hljs-title function_">randomFill</span>(buf, <span class="hljs-number">5</span>, <span class="hljs-function">(<span class="hljs-params">err, buf</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
});

<span class="hljs-comment">// The above is equivalent to the following:</span>
<span class="hljs-title function_">randomFill</span>(buf, <span class="hljs-number">5</span>, <span class="hljs-number">5</span>, <span class="hljs-function">(<span class="hljs-params">err, buf</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { randomFill } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">10</span>);
<span class="hljs-title function_">randomFill</span>(buf, <span class="hljs-function">(<span class="hljs-params">err, buf</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
});

<span class="hljs-title function_">randomFill</span>(buf, <span class="hljs-number">5</span>, <span class="hljs-function">(<span class="hljs-params">err, buf</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
});

<span class="hljs-comment">// The above is equivalent to the following:</span>
<span class="hljs-title function_">randomFill</span>(buf, <span class="hljs-number">5</span>, <span class="hljs-number">5</span>, <span class="hljs-function">(<span class="hljs-params">err, buf</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
});</code><button class="copy-button">copy</button></pre>
<p>Any <code>ArrayBuffer</code>, <code>TypedArray</code>, or <code>DataView</code> instance may be passed as
<code>buffer</code>.</p>
<p>While this includes instances of <code>Float32Array</code> and <code>Float64Array</code>, this
function should not be used to generate random floating-point numbers. The
result may contain <code>+Infinity</code>, <code>-Infinity</code>, and <code>NaN</code>, and even if the array
contains finite numbers only, they are not drawn from a uniform random
distribution and have no meaningful lower or upper bounds.</p>

<pre class="with-51-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> { randomFill } = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> a = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint32Array</span>(<span class="hljs-number">10</span>);
<span class="hljs-title function_">randomFill</span>(a, <span class="hljs-function">(<span class="hljs-params">err, buf</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(buf.<span class="hljs-property">buffer</span>, buf.<span class="hljs-property">byteOffset</span>, buf.<span class="hljs-property">byteLength</span>)
    .<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
});

<span class="hljs-keyword">const</span> b = <span class="hljs-keyword">new</span> <span class="hljs-title class_">DataView</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>(<span class="hljs-number">10</span>));
<span class="hljs-title function_">randomFill</span>(b, <span class="hljs-function">(<span class="hljs-params">err, buf</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(buf.<span class="hljs-property">buffer</span>, buf.<span class="hljs-property">byteOffset</span>, buf.<span class="hljs-property">byteLength</span>)
    .<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
});

<span class="hljs-keyword">const</span> c = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>(<span class="hljs-number">10</span>);
<span class="hljs-title function_">randomFill</span>(c, <span class="hljs-function">(<span class="hljs-params">err, buf</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(buf).<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { randomFill } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> a = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint32Array</span>(<span class="hljs-number">10</span>);
<span class="hljs-title function_">randomFill</span>(a, <span class="hljs-function">(<span class="hljs-params">err, buf</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(buf.<span class="hljs-property">buffer</span>, buf.<span class="hljs-property">byteOffset</span>, buf.<span class="hljs-property">byteLength</span>)
    .<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
});

<span class="hljs-keyword">const</span> b = <span class="hljs-keyword">new</span> <span class="hljs-title class_">DataView</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>(<span class="hljs-number">10</span>));
<span class="hljs-title function_">randomFill</span>(b, <span class="hljs-function">(<span class="hljs-params">err, buf</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(buf.<span class="hljs-property">buffer</span>, buf.<span class="hljs-property">byteOffset</span>, buf.<span class="hljs-property">byteLength</span>)
    .<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
});

<span class="hljs-keyword">const</span> c = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>(<span class="hljs-number">10</span>);
<span class="hljs-title function_">randomFill</span>(c, <span class="hljs-function">(<span class="hljs-params">err, buf</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(buf).<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));
});</code><button class="copy-button">copy</button></pre>
<p>This API uses libuv's threadpool, which can have surprising and
negative performance implications for some applications; see the
<a href="#all_cli_uv_threadpool_sizesize"><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>
<h4><code>crypto.randomInt([min, ]max[, callback])</code><span><a class="mark" href="#all_crypto_cryptorandomintmin-max-callback" id="all_crypto_cryptorandomintmin-max-callback">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_randomint_min_max_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></tr>
<tr><td>v14.10.0, v12.19.0</td>
<td><p><span>Added in: v14.10.0, v12.19.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>min</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Start of random range (inclusive). <strong>Default:</strong> <code>0</code>.</li>
<li><code>max</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> End of random range (exclusive).</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, n) {}</code>.</li>
</ul>
<p>Return a random integer <code>n</code> such that <code>min &#x3C;= n &#x3C; max</code>.  This
implementation avoids <a href="https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Modulo_bias">modulo bias</a>.</p>
<p>The range (<code>max - min</code>) must be less than 2<sup>48</sup>. <code>min</code> and <code>max</code> must
be <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger">safe integers</a>.</p>
<p>If the <code>callback</code> function is not provided, the random integer is
generated synchronously.</p>

<pre class="with-15-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// Asynchronous</span>
<span class="hljs-keyword">const</span> {
  randomInt,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-title function_">randomInt</span>(<span class="hljs-number">3</span>, <span class="hljs-function">(<span class="hljs-params">err, n</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Random number chosen from (0, 1, 2): <span class="hljs-subst">${n}</span>`</span>);
});</code><code class="language-js cjs"><span class="hljs-comment">// Asynchronous</span>
<span class="hljs-keyword">const</span> {
  randomInt,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-title function_">randomInt</span>(<span class="hljs-number">3</span>, <span class="hljs-function">(<span class="hljs-params">err, n</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Random number chosen from (0, 1, 2): <span class="hljs-subst">${n}</span>`</span>);
});</code><button class="copy-button">copy</button></pre>

<pre class="with-14-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// Synchronous</span>
<span class="hljs-keyword">const</span> {
  randomInt,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> n = <span class="hljs-title function_">randomInt</span>(<span class="hljs-number">3</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Random number chosen from (0, 1, 2): <span class="hljs-subst">${n}</span>`</span>);</code><code class="language-js cjs"><span class="hljs-comment">// Synchronous</span>
<span class="hljs-keyword">const</span> {
  randomInt,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> n = <span class="hljs-title function_">randomInt</span>(<span class="hljs-number">3</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Random number chosen from (0, 1, 2): <span class="hljs-subst">${n}</span>`</span>);</code><button class="copy-button">copy</button></pre>

<pre class="with-22-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// With `min` argument</span>
<span class="hljs-keyword">const</span> {
  randomInt,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> n = <span class="hljs-title function_">randomInt</span>(<span class="hljs-number">1</span>, <span class="hljs-number">7</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`The dice rolled: <span class="hljs-subst">${n}</span>`</span>);</code><code class="language-js cjs"><span class="hljs-comment">// With `min` argument</span>
<span class="hljs-keyword">const</span> {
  randomInt,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> n = <span class="hljs-title function_">randomInt</span>(<span class="hljs-number">1</span>, <span class="hljs-number">7</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`The dice rolled: <span class="hljs-subst">${n}</span>`</span>);</code><button class="copy-button">copy</button></pre>
<h4><code>crypto.randomUUID([options])</code><span><a class="mark" href="#all_crypto_cryptorandomuuidoptions" id="all_crypto_cryptorandomuuidoptions">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_randomuuid_options"></a></h4>
<div class="api_metadata">
<span>Added in: v15.6.0, v14.17.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>
<ul>
<li><code>disableEntropyCache</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> By default, to improve performance,
Node.js generates and caches enough
random data to generate up to 128 random UUIDs. To generate a UUID
without using the cache, set <code>disableEntropyCache</code> to <code>true</code>.
<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>Generates a random <a href="https://www.rfc-editor.org/rfc/rfc4122.txt">RFC 4122</a> version 4 UUID. The UUID is generated using a
cryptographic pseudorandom number generator.</p>
<h4><code>crypto.scrypt(password, salt, keylen[, options], callback)</code><span><a class="mark" href="#all_crypto_cryptoscryptpassword-salt-keylen-options-callback" id="all_crypto_cryptoscryptpassword-salt-keylen-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_scrypt_password_salt_keylen_options_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p>The password and salt arguments can also be ArrayBuffer instances.</p></td></tr>
<tr><td>v12.8.0, v10.17.0</td>
<td><p>The <code>maxmem</code> value can now be any safe integer.</p></td></tr>
<tr><td>v10.9.0</td>
<td><p>The <code>cost</code>, <code>blockSize</code> and <code>parallelization</code> option names have been added.</p></td></tr>
<tr><td>v10.5.0</td>
<td><p><span>Added in: v10.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>password</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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="#all_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>When passing strings for <code>password</code> or <code>salt</code>, please consider
<a href="#all_crypto_using-strings-as-inputs-to-cryptographic-apis">caveats when using strings as inputs to cryptographic APIs</a>.</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 class="with-9-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">const</span> {
  scrypt,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-comment">// Using the factory defaults.</span>
<span class="hljs-title function_">scrypt</span>(<span class="hljs-string">'password'</span>, <span class="hljs-string">'salt'</span>, <span class="hljs-number">64</span>, <span class="hljs-function">(<span class="hljs-params">err, derivedKey</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(derivedKey.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));  <span class="hljs-comment">// '3745e48...08d59ae'</span>
});
<span class="hljs-comment">// Using a custom N parameter. Must be a power of two.</span>
<span class="hljs-title function_">scrypt</span>(<span class="hljs-string">'password'</span>, <span class="hljs-string">'salt'</span>, <span class="hljs-number">64</span>, { <span class="hljs-attr">N</span>: <span class="hljs-number">1024</span> }, <span class="hljs-function">(<span class="hljs-params">err, derivedKey</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(derivedKey.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));  <span class="hljs-comment">// '3745e48...aa39b34'</span>
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
  scrypt,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-comment">// Using the factory defaults.</span>
<span class="hljs-title function_">scrypt</span>(<span class="hljs-string">'password'</span>, <span class="hljs-string">'salt'</span>, <span class="hljs-number">64</span>, <span class="hljs-function">(<span class="hljs-params">err, derivedKey</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(derivedKey.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));  <span class="hljs-comment">// '3745e48...08d59ae'</span>
});
<span class="hljs-comment">// Using a custom N parameter. Must be a power of two.</span>
<span class="hljs-title function_">scrypt</span>(<span class="hljs-string">'password'</span>, <span class="hljs-string">'salt'</span>, <span class="hljs-number">64</span>, { <span class="hljs-attr">N</span>: <span class="hljs-number">1024</span> }, <span class="hljs-function">(<span class="hljs-params">err, derivedKey</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(derivedKey.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));  <span class="hljs-comment">// '3745e48...aa39b34'</span>
});</code><button class="copy-button">copy</button></pre>
<h4><code>crypto.scryptSync(password, salt, keylen[, options])</code><span><a class="mark" href="#all_crypto_cryptoscryptsyncpassword-salt-keylen-options" id="all_crypto_cryptoscryptsyncpassword-salt-keylen-options">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_scryptsync_password_salt_keylen_options"></a></h4>
<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, v10.17.0</td>
<td><p>The <code>maxmem</code> value can now be any safe integer.</p></td></tr>
<tr><td>v10.9.0</td>
<td><p>The <code>cost</code>, <code>blockSize</code> and <code>parallelization</code> option names have been added.</p></td></tr>
<tr><td>v10.5.0</td>
<td><p><span>Added in: v10.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>password</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#all_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="#all_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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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="#all_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>When passing strings for <code>password</code> or <code>salt</code>, please consider
<a href="#all_crypto_using-strings-as-inputs-to-cryptographic-apis">caveats when using strings as inputs to cryptographic APIs</a>.</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 class="with-13-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">const</span> {
  scryptSync,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-comment">// Using the factory defaults.</span>

<span class="hljs-keyword">const</span> key1 = <span class="hljs-title function_">scryptSync</span>(<span class="hljs-string">'password'</span>, <span class="hljs-string">'salt'</span>, <span class="hljs-number">64</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(key1.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));  <span class="hljs-comment">// '3745e48...08d59ae'</span>
<span class="hljs-comment">// Using a custom N parameter. Must be a power of two.</span>
<span class="hljs-keyword">const</span> key2 = <span class="hljs-title function_">scryptSync</span>(<span class="hljs-string">'password'</span>, <span class="hljs-string">'salt'</span>, <span class="hljs-number">64</span>, { <span class="hljs-attr">N</span>: <span class="hljs-number">1024</span> });
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(key2.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));  <span class="hljs-comment">// '3745e48...aa39b34'</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
  scryptSync,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);
<span class="hljs-comment">// Using the factory defaults.</span>

<span class="hljs-keyword">const</span> key1 = <span class="hljs-title function_">scryptSync</span>(<span class="hljs-string">'password'</span>, <span class="hljs-string">'salt'</span>, <span class="hljs-number">64</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(key1.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));  <span class="hljs-comment">// '3745e48...08d59ae'</span>
<span class="hljs-comment">// Using a custom N parameter. Must be a power of two.</span>
<span class="hljs-keyword">const</span> key2 = <span class="hljs-title function_">scryptSync</span>(<span class="hljs-string">'password'</span>, <span class="hljs-string">'salt'</span>, <span class="hljs-number">64</span>, { <span class="hljs-attr">N</span>: <span class="hljs-number">1024</span> });
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(key2.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>));  <span class="hljs-comment">// '3745e48...aa39b34'</span></code><button class="copy-button">copy</button></pre>
<h4><code>crypto.secureHeapUsed()</code><span><a class="mark" href="#all_crypto_cryptosecureheapused" id="all_crypto_cryptosecureheapused">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_secureheapused"></a></h4>
<div class="api_metadata">
<span>Added in: v15.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>
<ul>
<li><code>total</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The total allocated secure heap size as specified
using the <code>--secure-heap=n</code> command-line flag.</li>
<li><code>min</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The minimum allocation from the secure heap as
specified using the <code>--secure-heap-min</code> command-line flag.</li>
<li><code>used</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The total number of bytes currently allocated from
the secure heap.</li>
<li><code>utilization</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The calculated ratio of <code>used</code> to <code>total</code>
allocated bytes.</li>
</ul>
</li>
</ul>
<h4><code>crypto.setEngine(engine[, flags])</code><span><a class="mark" href="#all_crypto_cryptosetengineengine-flags" id="all_crypto_cryptosetengineengine-flags">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_setengine_engine_flags"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.16.0</td>
<td><p>Custom engine support in OpenSSL 3 is deprecated.</p></td></tr>
<tr><td>v0.11.11</td>
<td><p><span>Added in: v0.11.11</span></p></td></tr>
</tbody></table>
</details>
</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="#all_crypto_cryptoconstants" 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).
Support for custom engines in OpenSSL is deprecated from OpenSSL 3.</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>
<h4><code>crypto.setFips(bool)</code><span><a class="mark" href="#all_crypto_cryptosetfipsbool" id="all_crypto_cryptosetfipsbool">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_setfips_bool"></a></h4>
<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>
<h4><code>crypto.sign(algorithm, data, key[, callback])</code><span><a class="mark" href="#all_crypto_cryptosignalgorithm-data-key-callback" id="all_crypto_cryptosignalgorithm-data-key-callback">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_sign_algorithm_data_key_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></tr>
<tr><td>v15.12.0</td>
<td><p>Optional callback argument added.</p></td></tr>
<tr><td>v13.2.0, v12.16.0</td>
<td><p>This function now supports IEEE-P1363 DSA and ECDSA signatures.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p><span>Added in: v12.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<!--lint disable maximum-line-length remark-lint-->
<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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_crypto_class-keyobject" class="type">&#x3C;KeyObject></a> | <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></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>
<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>signature</code> <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a></li>
</ul>
</li>
<li>Returns: <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> if the <code>callback</code> function is not provided.</li>
</ul>
<!--lint enable maximum-line-length remark-lint-->
<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="#all_crypto_class-keyobject"><code>KeyObject</code></a>, this function behaves as if <code>key</code> had been
passed to <a href="#all_crypto_cryptocreateprivatekeykey"><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>
<p>If the <code>callback</code> function is provided this function uses libuv's threadpool.</p>
<h4><code>crypto.subtle</code><span><a class="mark" href="#all_crypto_cryptosubtle" id="all_crypto_cryptosubtle">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_subtle"></a></h4>
<div class="api_metadata">
<span>Added in: v17.4.0</span>
</div>
<ul>
<li>Type: <a href="#all_webcrypto_class-subtlecrypto" class="type">&#x3C;SubtleCrypto></a></li>
</ul>
<p>A convenient alias for <a href="#all_webcrypto_class-subtlecrypto"><code>crypto.webcrypto.subtle</code></a>.</p>
<h4><code>crypto.timingSafeEqual(a, b)</code><span><a class="mark" href="#all_crypto_cryptotimingsafeequala-b" id="all_crypto_cryptotimingsafeequala-b">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_timingsafeequal_a_b"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>The a and b arguments can also be ArrayBuffer.</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><code>a</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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 compares the underlying bytes that represent the given
<code>ArrayBuffer</code>, <code>TypedArray</code>, or <code>DataView</code> instances using a constant-time
algorithm.</p>
<p>This function does not leak 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 byte length. An error is thrown if <code>a</code> and <code>b</code> have
different byte lengths.</p>
<p>If at least one of <code>a</code> and <code>b</code> is a <code>TypedArray</code> with more than one byte per
entry, such as <code>Uint16Array</code>, the result will be computed using the platform
byte order.</p>
<p><strong class="critical">When both of the inputs are <code>Float32Array</code>s or
<code>Float64Array</code>s, this function might return unexpected results due to IEEE 754
encoding of floating-point numbers. In particular, neither <code>x === y</code> nor
<code>Object.is(x, y)</code> implies that the byte representations of two floating-point
numbers <code>x</code> and <code>y</code> are equal.</strong></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>
<h4><code>crypto.verify(algorithm, data, key, signature[, callback])</code><span><a class="mark" href="#all_crypto_cryptoverifyalgorithm-data-key-signature-callback" id="all_crypto_cryptoverifyalgorithm-data-key-signature-callback">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_verify_algorithm_data_key_signature_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></tr>
<tr><td>v15.12.0</td>
<td><p>Optional callback argument added.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p>The data, key, and signature arguments can also be ArrayBuffer.</p></td></tr>
<tr><td>v13.2.0, v12.16.0</td>
<td><p>This function now supports IEEE-P1363 DSA and ECDSA signatures.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p><span>Added in: v12.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<!--lint disable maximum-line-length remark-lint-->
<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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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="#all_crypto_class-keyobject" class="type">&#x3C;KeyObject></a> | <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></a></li>
<li><code>signature</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="#all_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>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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>result</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
</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 if the <code>callback</code> function is not
provided.</li>
</ul>
<!--lint enable maximum-line-length remark-lint-->
<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="#all_crypto_class-keyobject"><code>KeyObject</code></a>, this function behaves as if <code>key</code> had been
passed to <a href="#all_crypto_cryptocreatepublickeykey"><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 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>
<p>If the <code>callback</code> function is provided this function uses libuv's threadpool.</p>
<h4><code>crypto.webcrypto</code><span><a class="mark" href="#all_crypto_cryptowebcrypto" id="all_crypto_cryptowebcrypto">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_webcrypto"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>Type: <a href="#all_webcrypto_class-crypto" class="type">&#x3C;Crypto></a> An implementation of the Web Crypto API standard.</p>
<p>See the <a href="webcrypto.html">Web Crypto API documentation</a> for details.</p>
</section><section><h3>Notes<span><a class="mark" href="#all_crypto_notes" id="all_crypto_notes">#</a></span><a aria-hidden="true" class="legacy" id="crypto_notes"></a></h3>
<h4>Using strings as inputs to cryptographic APIs<span><a class="mark" href="#all_crypto_using-strings-as-inputs-to-cryptographic-apis" id="all_crypto_using-strings-as-inputs-to-cryptographic-apis">#</a></span><a aria-hidden="true" class="legacy" id="crypto_using_strings_as_inputs_to_cryptographic_apis"></a></h4>
<p>For historical reasons, many cryptographic APIs provided by Node.js accept
strings as inputs where the underlying cryptographic algorithm works on byte
sequences. These instances include plaintexts, ciphertexts, symmetric keys,
initialization vectors, passphrases, salts, authentication tags,
and additional authenticated data.</p>
<p>When passing strings to cryptographic APIs, consider the following factors.</p>
<ul>
<li>
<p>Not all byte sequences are valid UTF-8 strings. Therefore, when a byte
sequence of length <code>n</code> is derived from a string, its entropy is generally
lower than the entropy of a random or pseudorandom <code>n</code> byte sequence.
For example, no UTF-8 string will result in the byte sequence <code>c0 af</code>. Secret
keys should almost exclusively be random or pseudorandom byte sequences.</p>
</li>
<li>
<p>Similarly, when converting random or pseudorandom byte sequences to UTF-8
strings, subsequences that do not represent valid code points may be replaced
by the Unicode replacement character (<code>U+FFFD</code>). The byte representation of
the resulting Unicode string may, therefore, not be equal to the byte sequence
that the string was created from.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> original = [<span class="hljs-number">0xc0</span>, <span class="hljs-number">0xaf</span>];
<span class="hljs-keyword">const</span> bytesAsString = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(original).<span class="hljs-title function_">toString</span>(<span class="hljs-string">'utf8'</span>);
<span class="hljs-keyword">const</span> stringAsBytes = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(bytesAsString, <span class="hljs-string">'utf8'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(stringAsBytes);
<span class="hljs-comment">// Prints '&#x3C;Buffer ef bf bd ef bf bd>'.</span></code> <button class="copy-button">copy</button></pre>
<p>The outputs of ciphers, hash functions, signature algorithms, and key
derivation functions are pseudorandom byte sequences and should not be
used as Unicode strings.</p>
</li>
<li>
<p>When strings are obtained from user input, some Unicode characters can be
represented in multiple equivalent ways that result in different byte
sequences. For example, when passing a user passphrase to a key derivation
function, such as PBKDF2 or scrypt, the result of the key derivation function
depends on whether the string uses composed or decomposed characters. Node.js
does not normalize character representations. Developers should consider using
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize"><code>String.prototype.normalize()</code></a> on user inputs before passing them to
cryptographic APIs.</p>
</li>
</ul>
<h4>Legacy streams API (prior to Node.js 0.10)<span><a class="mark" href="#all_crypto_legacy-streams-api-prior-to-nodejs-010" id="all_crypto_legacy-streams-api-prior-to-nodejs-010">#</a></span><a aria-hidden="true" class="legacy" id="crypto_legacy_streams_api_prior_to_node_js_0_10"></a></h4>
<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, many <code>crypto</code> 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>
<h4>Support for weak or compromised algorithms<span><a class="mark" href="#all_crypto_support-for-weak-or-compromised-algorithms" id="all_crypto_support-for-weak-or-compromised-algorithms">#</a></span><a aria-hidden="true" class="legacy" id="crypto_support_for_weak_or_compromised_algorithms"></a></h4>
<p>The <code>node:crypto</code> module still supports some algorithms which are already
compromised and are not 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-131Ar2.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>
<p>Some algorithms that have known weaknesses and are of little relevance in
practice are only available through the <a href="#all_cli_--openssl-legacy-provider">legacy provider</a>, which is not
enabled by default.</p>
<h4>CCM mode<span><a class="mark" href="#all_crypto_ccm-mode" id="all_crypto_ccm-mode">#</a></span><a aria-hidden="true" class="legacy" id="crypto_ccm_mode"></a></h4>
<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> must be called exactly
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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;
<span class="hljs-keyword">const</span> {
  createCipheriv,
  createDecipheriv,
  randomBytes,
} = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> key = <span class="hljs-string">'keykeykeykeykeykeykeykey'</span>;
<span class="hljs-keyword">const</span> nonce = <span class="hljs-title function_">randomBytes</span>(<span class="hljs-number">12</span>);

<span class="hljs-keyword">const</span> aad = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'0123456789'</span>, <span class="hljs-string">'hex'</span>);

<span class="hljs-keyword">const</span> cipher = <span class="hljs-title function_">createCipheriv</span>(<span class="hljs-string">'aes-192-ccm'</span>, key, nonce, {
  <span class="hljs-attr">authTagLength</span>: <span class="hljs-number">16</span>,
});
<span class="hljs-keyword">const</span> plaintext = <span class="hljs-string">'Hello world'</span>;
cipher.<span class="hljs-title function_">setAAD</span>(aad, {
  <span class="hljs-attr">plaintextLength</span>: <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">byteLength</span>(plaintext),
});
<span class="hljs-keyword">const</span> ciphertext = cipher.<span class="hljs-title function_">update</span>(plaintext, <span class="hljs-string">'utf8'</span>);
cipher.<span class="hljs-title function_">final</span>();
<span class="hljs-keyword">const</span> tag = cipher.<span class="hljs-title function_">getAuthTag</span>();

<span class="hljs-comment">// Now transmit { ciphertext, nonce, tag }.</span>

<span class="hljs-keyword">const</span> decipher = <span class="hljs-title function_">createDecipheriv</span>(<span class="hljs-string">'aes-192-ccm'</span>, key, nonce, {
  <span class="hljs-attr">authTagLength</span>: <span class="hljs-number">16</span>,
});
decipher.<span class="hljs-title function_">setAuthTag</span>(tag);
decipher.<span class="hljs-title function_">setAAD</span>(aad, {
  <span class="hljs-attr">plaintextLength</span>: ciphertext.<span class="hljs-property">length</span>,
});
<span class="hljs-keyword">const</span> receivedPlaintext = decipher.<span class="hljs-title function_">update</span>(ciphertext, <span class="hljs-literal">null</span>, <span class="hljs-string">'utf8'</span>);

<span class="hljs-keyword">try</span> {
  decipher.<span class="hljs-title function_">final</span>();
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Authentication failed!'</span>, { <span class="hljs-attr">cause</span>: err });
}

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(receivedPlaintext);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);
<span class="hljs-keyword">const</span> {
  createCipheriv,
  createDecipheriv,
  randomBytes,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">const</span> key = <span class="hljs-string">'keykeykeykeykeykeykeykey'</span>;
<span class="hljs-keyword">const</span> nonce = <span class="hljs-title function_">randomBytes</span>(<span class="hljs-number">12</span>);

<span class="hljs-keyword">const</span> aad = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'0123456789'</span>, <span class="hljs-string">'hex'</span>);

<span class="hljs-keyword">const</span> cipher = <span class="hljs-title function_">createCipheriv</span>(<span class="hljs-string">'aes-192-ccm'</span>, key, nonce, {
  <span class="hljs-attr">authTagLength</span>: <span class="hljs-number">16</span>,
});
<span class="hljs-keyword">const</span> plaintext = <span class="hljs-string">'Hello world'</span>;
cipher.<span class="hljs-title function_">setAAD</span>(aad, {
  <span class="hljs-attr">plaintextLength</span>: <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">byteLength</span>(plaintext),
});
<span class="hljs-keyword">const</span> ciphertext = cipher.<span class="hljs-title function_">update</span>(plaintext, <span class="hljs-string">'utf8'</span>);
cipher.<span class="hljs-title function_">final</span>();
<span class="hljs-keyword">const</span> tag = cipher.<span class="hljs-title function_">getAuthTag</span>();

<span class="hljs-comment">// Now transmit { ciphertext, nonce, tag }.</span>

<span class="hljs-keyword">const</span> decipher = <span class="hljs-title function_">createDecipheriv</span>(<span class="hljs-string">'aes-192-ccm'</span>, key, nonce, {
  <span class="hljs-attr">authTagLength</span>: <span class="hljs-number">16</span>,
});
decipher.<span class="hljs-title function_">setAuthTag</span>(tag);
decipher.<span class="hljs-title function_">setAAD</span>(aad, {
  <span class="hljs-attr">plaintextLength</span>: ciphertext.<span class="hljs-property">length</span>,
});
<span class="hljs-keyword">const</span> receivedPlaintext = decipher.<span class="hljs-title function_">update</span>(ciphertext, <span class="hljs-literal">null</span>, <span class="hljs-string">'utf8'</span>);

<span class="hljs-keyword">try</span> {
  decipher.<span class="hljs-title function_">final</span>();
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Authentication failed!'</span>, { <span class="hljs-attr">cause</span>: err });
}

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(receivedPlaintext);</code><button class="copy-button">copy</button></pre>
<h4>FIPS mode<span><a class="mark" href="#all_crypto_fips-mode" id="all_crypto_fips-mode">#</a></span><a aria-hidden="true" class="legacy" id="crypto_fips_mode"></a></h4>
<p>When using OpenSSL 3, Node.js supports FIPS 140-2 when used with an appropriate
OpenSSL 3 provider, such as the <a href="https://www.openssl.org/docs/man3.0/man7/crypto.html#FIPS-provider">FIPS provider from OpenSSL 3</a> which can be
installed by following the instructions in <a href="https://github.com/openssl/openssl/blob/openssl-3.0/README-FIPS.md">OpenSSL's FIPS README file</a>.</p>
<p>For FIPS support in Node.js you will need:</p>
<ul>
<li>A correctly installed OpenSSL 3 FIPS provider.</li>
<li>An OpenSSL 3 <a href="https://www.openssl.org/docs/man3.0/man5/fips_config.html">FIPS module configuration file</a>.</li>
<li>An OpenSSL 3 configuration file that references the FIPS module
configuration file.</li>
</ul>
<p>Node.js will need to be configured with an OpenSSL configuration file that
points to the FIPS provider. An example configuration file looks like this:</p>
<pre><code class="language-text">nodejs_conf = nodejs_init

.include /&#x3C;absolute path>/fipsmodule.cnf

[nodejs_init]
providers = provider_sect

[provider_sect]
default = default_sect
# The fips section name should match the section name inside the
# included fipsmodule.cnf.
fips = fips_sect

[default_sect]
activate = 1</code> <button class="copy-button">copy</button></pre>
<p>where <code>fipsmodule.cnf</code> is the FIPS module configuration file generated from the
FIPS provider installation step:</p>
<pre><code class="language-bash">openssl fipsinstall</code> <button class="copy-button">copy</button></pre>
<p>Set the <code>OPENSSL_CONF</code> environment variable to point to
your configuration file and <code>OPENSSL_MODULES</code> to the location of the FIPS
provider dynamic library. e.g.</p>
<pre><code class="language-bash"><span class="hljs-built_in">export</span> OPENSSL_CONF=/&#x3C;path to configuration file>/nodejs.cnf
<span class="hljs-built_in">export</span> OPENSSL_MODULES=/&#x3C;path to openssl lib>/ossl-modules</code> <button class="copy-button">copy</button></pre>
<p>FIPS mode can then be enabled in Node.js either by:</p>
<ul>
<li>Starting Node.js with <code>--enable-fips</code> or <code>--force-fips</code> command line flags.</li>
<li>Programmatically calling <code>crypto.setFips(true)</code>.</li>
</ul>
<p>Optionally FIPS mode can be enabled in Node.js via the OpenSSL configuration
file. e.g.</p>
<pre><code class="language-text">nodejs_conf = nodejs_init

.include /&#x3C;absolute path>/fipsmodule.cnf

[nodejs_init]
providers = provider_sect
alg_section = algorithm_sect

[provider_sect]
default = default_sect
# The fips section name should match the section name inside the
# included fipsmodule.cnf.
fips = fips_sect

[default_sect]
activate = 1

[algorithm_sect]
default_properties = fips=yes</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Crypto constants<span><a class="mark" href="#all_crypto_crypto-constants" id="all_crypto_crypto-constants">#</a></span><a aria-hidden="true" class="legacy" id="crypto_crypto_constants_1"></a></h3>
<p>The following constants exported by <code>crypto.constants</code> apply to various uses of
the <code>node:crypto</code>, <code>node:tls</code>, and <code>node:https</code> modules and are generally
specific to OpenSSL.</p>
<h4>OpenSSL options<span><a class="mark" href="#all_crypto_openssl-options" id="all_crypto_openssl-options">#</a></span><a aria-hidden="true" class="legacy" id="crypto_openssl_options"></a></h4>
<p>See the <a href="https://wiki.openssl.org/index.php/List_of_SSL_OP_Flags#Table_of_Options">list of SSL OP Flags</a> for details.</p>
<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/man3.0/man3/SSL_CTX_set_options.html">https://www.openssl.org/docs/man3.0/man3/SSL_CTX_set_options.html</a>
    for detail.</td>
  </tr>
  <tr>
    <td><code>SSL_OP_ALLOW_NO_DHE_KEX</code></td>
    <td>Instructs OpenSSL to allow a non-[EC]DHE-based key exchange mode
    for TLS v1.3</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/man3.0/man3/SSL_CTX_set_options.html">https://www.openssl.org/docs/man3.0/man3/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/man3.0/man3/SSL_CTX_set_options.html">https://www.openssl.org/docs/man3.0/man3/SSL_CTX_set_options.html</a>.</td>
  </tr>
  <tr>
    <td><code>SSL_OP_CISCO_ANYCONNECT</code></td>
    <td>Instructs OpenSSL to use Cisco's version identifier 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_LEGACY_SERVER_CONNECT</code></td>
    <td>Allows initial connection to servers that do not support RI.</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_ENCRYPT_THEN_MAC</code></td>
    <td>Instructs OpenSSL to disable encrypt-then-MAC.</td>
  </tr>
  <tr>
    <td><code>SSL_OP_NO_QUERY_MTU</code></td>
    <td></td>
  </tr>
  <tr>
    <td><code>SSL_OP_NO_RENEGOTIATION</code></td>
    <td>Instructs OpenSSL to disable renegotiation.</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_NO_TLSv1_3</code></td>
    <td>Instructs OpenSSL to turn off TLS v1.3</td>
  </tr>
  <tr>
    <td><code>SSL_OP_PRIORITIZE_CHACHA</code></td>
    <td>Instructs OpenSSL server to prioritize ChaCha20-Poly1305
    when the client does.
    This option has no effect if
    <code>SSL_OP_CIPHER_SERVER_PREFERENCE</code>
    is not enabled.</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>
<h4>OpenSSL engine constants<span><a class="mark" href="#all_crypto_openssl-engine-constants" id="all_crypto_openssl-engine-constants">#</a></span><a aria-hidden="true" class="legacy" id="crypto_openssl_engine_constants"></a></h4>
<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>
<h4>Other OpenSSL constants<span><a class="mark" href="#all_crypto_other-openssl-constants" id="all_crypto_other-openssl-constants">#</a></span><a aria-hidden="true" class="legacy" id="crypto_other_openssl_constants"></a></h4>
<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>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>
<h4>Node.js crypto constants<span><a class="mark" href="#all_crypto_nodejs-crypto-constants" id="all_crypto_nodejs-crypto-constants">#</a></span><a aria-hidden="true" class="legacy" id="crypto_node_js_crypto_constants"></a></h4>
<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></section>
        </section>
<section><h2>Debugger<span><a class="mark" href="#all_debugger_debugger" id="all_debugger_debugger">#</a></span><a aria-hidden="true" class="legacy" id="debugger_debugger"></a></h2>

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

<p>Node.js includes a command-line debugging utility. The Node.js debugger client
is not a full-featured debugger, but simple stepping and inspection are
possible.</p>
<p>To use it, start Node.js with the <code>inspect</code> argument followed by the path to the
script to debug.</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node inspect myscript.js</span>
&#x3C; Debugger listening on ws://127.0.0.1:9229/621111f9-ffcb-4e82-b718-48a145fa5db8
&#x3C; For help, see: https://nodejs.org/en/docs/inspector
&#x3C;
connecting to 127.0.0.1:9229 ... ok
&#x3C; Debugger attached.
&#x3C;
 ok
Break on start in myscript.js:2
  1 // myscript.js
<span class="hljs-meta prompt_">> </span><span class="language-bash">2 global.x = 5;</span>
  3 setTimeout(() => {
  4   debugger;
<span class="hljs-meta prompt_">debug></span></code> <button class="copy-button">copy</button></pre>
<p>The debugger automatically breaks on the first executable line. To instead
run until the first breakpoint (specified by a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/debugger"><code>debugger</code></a> statement), set
the <code>NODE_INSPECT_RESUME_ON_START</code> environment variable to <code>1</code>.</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash"><span class="hljs-built_in">cat</span> myscript.js</span>
// myscript.js
global.x = 5;
setTimeout(() => {
  debugger;
  console.log('world');
}, 1000);
console.log('hello');
<span class="hljs-meta prompt_">$ </span><span class="language-bash">NODE_INSPECT_RESUME_ON_START=1 node inspect myscript.js</span>
&#x3C; Debugger listening on ws://127.0.0.1:9229/f1ed133e-7876-495b-83ae-c32c6fc319c2
&#x3C; For help, see: https://nodejs.org/en/docs/inspector
&#x3C;
connecting to 127.0.0.1:9229 ... ok
&#x3C; Debugger attached.
&#x3C;
&#x3C; hello
&#x3C;
break in myscript.js:4
  2 global.x = 5;
  3 setTimeout(() => {
<span class="hljs-meta prompt_">> </span><span class="language-bash">4   debugger;</span>
  5   console.log('world');
  6 }, 1000);
<span class="hljs-meta prompt_">debug> </span><span class="language-bash">next</span>
break in myscript.js:5
  3 setTimeout(() => {
  4   debugger;
<span class="hljs-meta prompt_">> </span><span class="language-bash">5   console.log(<span class="hljs-string">'world'</span>);</span>
  6 }, 1000);
  7 console.log('hello');
<span class="hljs-meta prompt_">debug> </span><span class="language-bash">repl</span>
Press Ctrl+C to leave debug repl
<span class="hljs-meta prompt_">> </span><span class="language-bash">x</span>
5
<span class="hljs-meta prompt_">> </span><span class="language-bash">2 + 2</span>
4
<span class="hljs-meta prompt_">debug> </span><span class="language-bash">next</span>
&#x3C; world
&#x3C;
break in myscript.js:6
  4   debugger;
  5   console.log('world');
<span class="hljs-meta prompt_">> </span><span class="language-bash">6 }, 1000);</span>
  7 console.log('hello');
  8
<span class="hljs-meta prompt_">debug> </span><span class="language-bash">.<span class="hljs-built_in">exit</span></span>
<span class="hljs-meta prompt_">$</span></code> <button class="copy-button">copy</button></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>
<section><h3>Watchers<span><a class="mark" href="#all_debugger_watchers" id="all_debugger_watchers">#</a></span><a aria-hidden="true" class="legacy" id="debugger_watchers"></a></h3>
<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>
</section><section><h3>Command reference<span><a class="mark" href="#all_debugger_command-reference" id="all_debugger_command-reference">#</a></span><a aria-hidden="true" class="legacy" id="debugger_command_reference"></a></h3>
<h4>Stepping<span><a class="mark" href="#all_debugger_stepping" id="all_debugger_stepping">#</a></span><a aria-hidden="true" class="legacy" id="debugger_stepping"></a></h4>
<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>
<h4>Breakpoints<span><a class="mark" href="#all_debugger_breakpoints" id="all_debugger_breakpoints">#</a></span><a aria-hidden="true" class="legacy" id="debugger_breakpoints"></a></h4>
<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
function's 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>setBreakpoint('script.js', 1, 'num &#x3C; 4')</code>, <code>sb(...)</code>: Set conditional
breakpoint on first line of <code>script.js</code> that only breaks when <code>num &#x3C; 4</code>
evaluates to <code>true</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"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node inspect main.js</span>
&#x3C; Debugger listening on ws://127.0.0.1:9229/48a5b28a-550c-471b-b5e1-d13dd7165df9
&#x3C; For help, see: https://nodejs.org/en/docs/inspector
&#x3C;
connecting to 127.0.0.1:9229 ... ok
&#x3C; Debugger attached.
&#x3C;
Break on start in main.js:1
<span class="hljs-meta prompt_">> </span><span class="language-bash">1 const mod = require(<span class="hljs-string">'./mod.js'</span>);</span>
  2 mod.hello();
  3 mod.hello();
<span class="hljs-meta prompt_">debug> </span><span class="language-bash">setBreakpoint(<span class="hljs-string">'mod.js'</span>, 22)</span>
Warning: script 'mod.js' was not loaded yet.
<span class="hljs-meta prompt_">debug> </span><span class="language-bash">c</span>
break in mod.js:22
 20 // USE OR OTHER DEALINGS IN THE SOFTWARE.
 21
<span class="hljs-meta prompt_">></span><span class="language-bash">22 exports.hello = <span class="hljs-function"><span class="hljs-title">function</span></span>() {</span>
 23   return 'hello from module';
 24 };
<span class="hljs-meta prompt_">debug></span></code> <button class="copy-button">copy</button></pre>
<p>It is also possible to set a conditional breakpoint that only breaks when a
given expression evaluates to <code>true</code>:</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node inspect main.js</span>
&#x3C; Debugger listening on ws://127.0.0.1:9229/ce24daa8-3816-44d4-b8ab-8273c8a66d35
&#x3C; For help, see: https://nodejs.org/en/docs/inspector
&#x3C;
connecting to 127.0.0.1:9229 ... ok
&#x3C; Debugger attached.
Break on start in main.js:7
  5 }
  6
<span class="hljs-meta prompt_">> </span><span class="language-bash">7 addOne(10);</span>
  8 addOne(-1);
  9
<span class="hljs-meta prompt_">debug> </span><span class="language-bash">setBreakpoint(<span class="hljs-string">'main.js'</span>, 4, <span class="hljs-string">'num &#x3C; 0'</span>)</span>
  1 'use strict';
  2
  3 function addOne(num) {
<span class="hljs-meta prompt_">> </span><span class="language-bash">4   <span class="hljs-built_in">return</span> num + 1;</span>
  5 }
  6
  7 addOne(10);
  8 addOne(-1);
  9
<span class="hljs-meta prompt_">debug> </span><span class="language-bash">cont</span>
break in main.js:4
  2
  3 function addOne(num) {
<span class="hljs-meta prompt_">> </span><span class="language-bash">4   <span class="hljs-built_in">return</span> num + 1;</span>
  5 }
  6
<span class="hljs-meta prompt_">debug> </span><span class="language-bash"><span class="hljs-built_in">exec</span>(<span class="hljs-string">'num'</span>)</span>
-1
<span class="hljs-meta prompt_">debug></span></code> <button class="copy-button">copy</button></pre>
<h4>Information<span><a class="mark" href="#all_debugger_information" id="all_debugger_information">#</a></span><a aria-hidden="true" class="legacy" id="debugger_information"></a></h4>
<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>unwatch(index)</code>: Remove expression at specific index 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>, <code>p expr</code>: Execute an expression in debugging script's context and
print its value</li>
<li><code>profile</code>: Start CPU profiling session</li>
<li><code>profileEnd</code>: Stop current CPU profiling session</li>
<li><code>profiles</code>: List all completed CPU profiling sessions</li>
<li><code>profiles[n].save(filepath = 'node.cpuprofile')</code>: Save CPU profiling session
to disk as JSON</li>
<li><code>takeHeapSnapshot(filepath = 'node.heapsnapshot')</code>: Take a heap snapshot
and save to disk as JSON</li>
</ul>
<h4>Execution control<span><a class="mark" href="#all_debugger_execution-control" id="all_debugger_execution-control">#</a></span><a aria-hidden="true" class="legacy" id="debugger_execution_control"></a></h4>
<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>
<h4>Various<span><a class="mark" href="#all_debugger_various" id="all_debugger_various">#</a></span><a aria-hidden="true" class="legacy" id="debugger_various"></a></h4>
<ul>
<li><code>scripts</code>: List all loaded scripts</li>
<li><code>version</code>: Display V8's version</li>
</ul>
</section><section><h3>Advanced usage<span><a class="mark" href="#all_debugger_advanced-usage" id="all_debugger_advanced-usage">#</a></span><a aria-hidden="true" class="legacy" id="debugger_advanced_usage"></a></h3>
<h4>V8 inspector integration for Node.js<span><a class="mark" href="#all_debugger_v8-inspector-integration-for-nodejs" id="all_debugger_v8-inspector-integration-for-nodejs">#</a></span><a aria-hidden="true" class="legacy" id="debugger_v8_inspector_integration_for_node_js"></a></h4>
<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>Using the <code>--inspect</code> flag will execute the code immediately before debugger is connected.
This means that the code will start running before you can start debugging, which might
not be ideal if you want to debug from the very beginning.</p>
<p>In such cases, you have two alternatives:</p>
<ol>
<li><code>--inspect-wait</code> flag: This flag will wait for debugger to be attached before executing the code.
This allows you to start debugging right from the beginning of the execution.</li>
<li><code>--inspect-brk</code> flag: Unlike <code>--inspect</code>, this flag will break on the first line of the code
as soon as debugger is attached. This is useful when you want to debug the code step by step
from the very beginning, without any code execution prior to debugging.</li>
</ol>
<p>So, when deciding between <code>--inspect</code>, <code>--inspect-wait</code>, and <code>--inspect-brk</code>, consider whether you want
the code to start executing immediately, wait for debugger to be attached before execution,
or break on the first line for step-by-step debugging.</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node --inspect index.js</span>
Debugger listening on ws://127.0.0.1:9229/dc9010dd-f8b8-4ac5-a510-c1a114ec7d29
For help, see: https://nodejs.org/en/docs/inspector</code> <button class="copy-button">copy</button></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></section>
        </section>
<section><h2>Deprecated APIs<span><a class="mark" href="#all_deprecations_deprecated-apis" id="all_deprecations_deprecated-apis">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_deprecated_apis"></a></h2>


<p>Node.js APIs might be deprecated 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 uses four kinds of deprecations:</p>
<ul>
<li>Documentation-only</li>
<li>Application (non-<code>node_modules</code> code only)</li>
<li>Runtime (all code)</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="#all_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="#all_deprecations_list-of-deprecated-apis">list of Deprecated APIs</a>.</p>
<p>An Application deprecation for only non-<code>node_modules</code> code will, by default,
generate a process warning that will be printed to <code>stderr</code> the first time
the deprecated API is used in code that's not loaded from <code>node_modules</code>.
When the <a href="#all_cli_--throw-deprecation"><code>--throw-deprecation</code></a> command-line flag is used, a Runtime
deprecation will cause an error to be thrown. When
<a href="#all_cli_--pending-deprecation"><code>--pending-deprecation</code></a> is used, warnings will also be emitted for
code loaded from <code>node_modules</code>.</p>
<p>A runtime deprecation for all code is similar to the runtime deprecation
for non-<code>node_modules</code> code, except that it also emits a warning for
code loaded from <code>node_modules</code>.</p>
<p>An End-of-Life deprecation is used when functionality is or will soon be removed
from Node.js.</p>
<section><h3>Revoking deprecations<span><a class="mark" href="#all_deprecations_revoking-deprecations" id="all_deprecations_revoking-deprecations">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_revoking_deprecations"></a></h3>
<p>Occasionally, the deprecation of an API might 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>
</section><section><h3>List of deprecated APIs<span><a class="mark" href="#all_deprecations_list-of-deprecated-apis" id="all_deprecations_list-of-deprecated-apis">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_list_of_deprecated_apis"></a></h3>
<h4 id="DEP0001">DEP0001: <code>http.OutgoingMessage.prototype.flush</code><span><a class="mark" href="#all_deprecations_dep0001-httpoutgoingmessageprototypeflush" id="all_deprecations_dep0001-httpoutgoingmessageprototypeflush">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0001_http_outgoingmessage_prototype_flush"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v6.12.0, v4.8.6</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: End-of-Life</p>
<p><code>OutgoingMessage.prototype.flush()</code> has been removed. Use
<code>OutgoingMessage.prototype.flushHeaders()</code> instead.</p>
<h4 id="DEP0002">DEP0002: <code>require('_linklist')</code><span><a class="mark" href="#all_deprecations_dep0002-require_linklist" id="all_deprecations_dep0002-require_linklist">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0002_require_linklist"></a></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>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>
<h4 id="DEP0003">DEP0003: <code>_writableState.buffer</code><span><a class="mark" href="#all_deprecations_dep0003-_writablestatebuffer" id="all_deprecations_dep0003-_writablestatebuffer">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0003_writablestate_buffer"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v6.12.0, v4.8.6</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: End-of-Life</p>
<p>The <code>_writableState.buffer</code> has been removed. Use <code>_writableState.getBuffer()</code>
instead.</p>
<h4 id="DEP0004">DEP0004: <code>CryptoStream.prototype.readyState</code><span><a class="mark" href="#all_deprecations_dep0004-cryptostreamprototypereadystate" id="all_deprecations_dep0004-cryptostreamprototypereadystate">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0004_cryptostream_prototype_readystate"></a></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>End-of-Life.</p></td></tr>
<tr><td>v6.12.0, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v0.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>
<h4 id="DEP0005">DEP0005: <code>Buffer()</code> constructor<span><a class="mark" href="#all_deprecations_dep0005-buffer-constructor" id="all_deprecations_dep0005-buffer-constructor">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0005_buffer_constructor"></a></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>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: Application (non-<code>node_modules</code> code only)</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="#all_buffer_static-method-bufferallocsize-fill-encoding"><code>Buffer.alloc(size[, fill[, encoding]])</code></a>: Create a <code>Buffer</code> with
<em>initialized</em> memory.</li>
<li><a href="#all_buffer_static-method-bufferallocunsafesize"><code>Buffer.allocUnsafe(size)</code></a>: Create a <code>Buffer</code> with
<em>uninitialized</em> memory.</li>
<li><a href="#all_buffer_static-method-bufferallocunsafeslowsize"><code>Buffer.allocUnsafeSlow(size)</code></a>: Create a <code>Buffer</code> with <em>uninitialized</em>
memory.</li>
<li><a href="#all_buffer_static-method-bufferfromarray"><code>Buffer.from(array)</code></a>: Create a <code>Buffer</code> with a copy of <code>array</code></li>
<li><a href="#all_buffer_static-method-bufferfromarraybuffer-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="#all_buffer_static-method-bufferfrombuffer"><code>Buffer.from(buffer)</code></a>: Create a <code>Buffer</code> that copies <code>buffer</code>.</li>
<li><a href="#all_buffer_static-method-bufferfromstring-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>
<h4 id="DEP0006">DEP0006: <code>child_process</code> <code>options.customFds</code><span><a class="mark" href="#all_deprecations_dep0006-child_process-optionscustomfds" id="all_deprecations_dep0006-child_process-optionscustomfds">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0006_child_process_options_customfds"></a></h4>
<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>v6.12.0, v4.8.6</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.10</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>
<h4 id="DEP0007">DEP0007: Replace <code>cluster</code> <code>worker.suicide</code> with <code>worker.exitedAfterDisconnect</code><span><a class="mark" href="#all_deprecations_dep0007-replace-cluster-workersuicide-with-workerexitedafterdisconnect" id="all_deprecations_dep0007-replace-cluster-workersuicide-with-workerexitedafterdisconnect">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0007_replace_cluster_worker_suicide_with_worker_exitedafterdisconnect"></a></h4>
<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="#all_cluster_workerexitedafterdisconnect"><code>worker.exitedAfterDisconnect</code></a> property. The old property name did not
precisely describe the actual semantics and was unnecessarily emotion-laden.</p>
<h4 id="DEP0008">DEP0008: <code>require('node:constants')</code><span><a class="mark" href="#all_deprecations_dep0008-requirenodeconstants" id="all_deprecations_dep0008-requirenodeconstants">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0008_require_node_constants"></a></h4>
<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>node: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('node:fs').constants</code> and <code>require('node:os').constants</code>.</p>
<h4 id="DEP0009">DEP0009: <code>crypto.pbkdf2</code> without digest<span><a class="mark" href="#all_deprecations_dep0009-cryptopbkdf2-without-digest" id="all_deprecations_dep0009-cryptopbkdf2-without-digest">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0009_crypto_pbkdf2_without_digest"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.0.0</td>
<td><p>End-of-Life (for <code>digest === null</code>).</p></td></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: End-of-Life</p>
<p>Use of the <a href="#all_crypto_cryptopbkdf2password-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> would print a deprecation warning to align with the behavior when <code>digest</code>
is <code>undefined</code>.</p>
<p>Now, however, passing either <code>undefined</code> or <code>null</code> will throw a <code>TypeError</code>.</p>
<h4 id="DEP0010">DEP0010: <code>crypto.createCredentials</code><span><a class="mark" href="#all_deprecations_dep0010-cryptocreatecredentials" id="all_deprecations_dep0010-cryptocreatecredentials">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0010_crypto_createcredentials"></a></h4>
<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>v6.12.0, v4.8.6</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="#all_tls_tlscreatesecurecontextoptions"><code>tls.createSecureContext()</code></a> instead.</p>
<h4 id="DEP0011">DEP0011: <code>crypto.Credentials</code><span><a class="mark" href="#all_deprecations_dep0011-cryptocredentials" id="all_deprecations_dep0011-cryptocredentials">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0011_crypto_credentials"></a></h4>
<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>v6.12.0, v4.8.6</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="#all_tls_tlscreatesecurecontextoptions"><code>tls.SecureContext</code></a>
instead.</p>
<h4 id="DEP0012">DEP0012: <code>Domain.dispose</code><span><a class="mark" href="#all_deprecations_dep0012-domaindispose" id="all_deprecations_dep0012-domaindispose">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0012_domain_dispose"></a></h4>
<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>v6.12.0, v4.8.6</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>
<h4 id="DEP0013">DEP0013: <code>fs</code> asynchronous function without callback<span><a class="mark" href="#all_deprecations_dep0013-fs-asynchronous-function-without-callback" id="all_deprecations_dep0013-fs-asynchronous-function-without-callback">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0013_fs_asynchronous_function_without_callback"></a></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>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>
<h4 id="DEP0014">DEP0014: <code>fs.read</code> legacy String interface<span><a class="mark" href="#all_deprecations_dep0014-fsread-legacy-string-interface" id="all_deprecations_dep0014-fsread-legacy-string-interface">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0014_fs_read_legacy_string_interface"></a></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>End-of-Life.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v6.12.0, v4.8.6</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="#all_fs_fsreadfd-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>
<h4 id="DEP0015">DEP0015: <code>fs.readSync</code> legacy String interface<span><a class="mark" href="#all_deprecations_dep0015-fsreadsync-legacy-string-interface" id="all_deprecations_dep0015-fsreadsync-legacy-string-interface">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0015_fs_readsync_legacy_string_interface"></a></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>End-of-Life.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v6.12.0, v4.8.6</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="#all_fs_fsreadsyncfd-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>
<h4 id="DEP0016">DEP0016: <code>GLOBAL</code>/<code>root</code><span><a class="mark" href="#all_deprecations_dep0016-globalroot" id="all_deprecations_dep0016-globalroot">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0016_global_root"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v6.12.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v6.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The <code>GLOBAL</code> and <code>root</code> aliases for the <code>global</code> property were deprecated
in Node.js 6.0.0 and have since been removed.</p>
<h4 id="DEP0017">DEP0017: <code>Intl.v8BreakIterator</code><span><a class="mark" href="#all_deprecations_dep0017-intlv8breakiterator" id="all_deprecations_dep0017-intlv8breakiterator">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0017_intl_v8breakiterator"></a></h4>
<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>
<h4 id="DEP0018">DEP0018: Unhandled promise rejections<span><a class="mark" href="#all_deprecations_dep0018-unhandled-promise-rejections" id="all_deprecations_dep0018-unhandled-promise-rejections">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0018_unhandled_promise_rejections"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.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>Unhandled promise rejections are deprecated. By default, promise rejections
that are not handled terminate the Node.js process with a non-zero exit
code. To change the way Node.js treats unhandled rejections, use the
<a href="#all_cli_--unhandled-rejectionsmode"><code>--unhandled-rejections</code></a> command-line option.</p>
<h4 id="DEP0019">DEP0019: <code>require('.')</code> resolved outside directory<span><a class="mark" href="#all_deprecations_dep0019-require-resolved-outside-directory" id="all_deprecations_dep0019-require-resolved-outside-directory">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0019_require_resolved_outside_directory"></a></h4>
<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>v6.12.0, v4.8.6</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>
<h4 id="DEP0020">DEP0020: <code>Server.connections</code><span><a class="mark" href="#all_deprecations_dep0020-serverconnections" id="all_deprecations_dep0020-serverconnections">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0020_server_connections"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>Server.connections has been removed.</p></td></tr>
<tr><td>v6.12.0, v4.8.6</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: End-of-Life</p>
<p>The <code>Server.connections</code> property was deprecated in Node.js v0.9.7 and has
been removed. Please use the <a href="#all_net_servergetconnectionscallback"><code>Server.getConnections()</code></a> method instead.</p>
<h4 id="DEP0021">DEP0021: <code>Server.listenFD</code><span><a class="mark" href="#all_deprecations_dep0021-serverlistenfd" id="all_deprecations_dep0021-serverlistenfd">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0021_server_listenfd"></a></h4>
<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>v6.12.0, v4.8.6</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="#all_net_serverlistenhandle-backlog-callback"><code>Server.listen({fd: &#x3C;number>})</code></a> instead.</p>
<h4 id="DEP0022">DEP0022: <code>os.tmpDir()</code><span><a class="mark" href="#all_deprecations_dep0022-ostmpdir" id="all_deprecations_dep0022-ostmpdir">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0022_os_tmpdir"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.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>os.tmpDir()</code> API was deprecated in Node.js 7.0.0 and has since been
removed. Please use <a href="#all_os_ostmpdir"><code>os.tmpdir()</code></a> instead.</p>
<h4 id="DEP0023">DEP0023: <code>os.getNetworkInterfaces()</code><span><a class="mark" href="#all_deprecations_dep0023-osgetnetworkinterfaces" id="all_deprecations_dep0023-osgetnetworkinterfaces">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0023_os_getnetworkinterfaces"></a></h4>
<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>v6.12.0, v4.8.6</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="#all_os_osnetworkinterfaces"><code>os.networkInterfaces()</code></a> method instead.</p>
<h4 id="DEP0024">DEP0024: <code>REPLServer.prototype.convertToContext()</code><span><a class="mark" href="#all_deprecations_dep0024-replserverprototypeconverttocontext" id="all_deprecations_dep0024-replserverprototypeconverttocontext">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0024_replserver_prototype_converttocontext"></a></h4>
<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>
<h4 id="DEP0025">DEP0025: <code>require('node:sys')</code><span><a class="mark" href="#all_deprecations_dep0025-requirenodesys" id="all_deprecations_dep0025-requirenodesys">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0025_require_node_sys"></a></h4>
<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, v4.8.6</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>node:sys</code> module is deprecated. Please use the <a href="util.html"><code>util</code></a> module instead.</p>
<h4 id="DEP0026">DEP0026: <code>util.print()</code><span><a class="mark" href="#all_deprecations_dep0026-utilprint" id="all_deprecations_dep0026-utilprint">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0026_util_print"></a></h4>
<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>v6.12.0, v4.8.6</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="#all_console_consolelogdata-args"><code>console.log()</code></a> instead.</p>
<h4 id="DEP0027">DEP0027: <code>util.puts()</code><span><a class="mark" href="#all_deprecations_dep0027-utilputs" id="all_deprecations_dep0027-utilputs">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0027_util_puts"></a></h4>
<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>v6.12.0, v4.8.6</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="#all_console_consolelogdata-args"><code>console.log()</code></a> instead.</p>
<h4 id="DEP0028">DEP0028: <code>util.debug()</code><span><a class="mark" href="#all_deprecations_dep0028-utildebug" id="all_deprecations_dep0028-utildebug">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0028_util_debug"></a></h4>
<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>v6.12.0, v4.8.6</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="#all_console_consoleerrordata-args"><code>console.error()</code></a> instead.</p>
<h4 id="DEP0029">DEP0029: <code>util.error()</code><span><a class="mark" href="#all_deprecations_dep0029-utilerror" id="all_deprecations_dep0029-utilerror">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0029_util_error"></a></h4>
<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>v6.12.0, v4.8.6</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="#all_console_consoleerrordata-args"><code>console.error()</code></a> instead.</p>
<h4 id="DEP0030">DEP0030: <code>SlowBuffer</code><span><a class="mark" href="#all_deprecations_dep0030-slowbuffer" id="all_deprecations_dep0030-slowbuffer">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0030_slowbuffer"></a></h4>
<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="#all_buffer_class-slowbuffer"><code>SlowBuffer</code></a> class is deprecated. Please use
<a href="#all_buffer_static-method-bufferallocunsafeslowsize"><code>Buffer.allocUnsafeSlow(size)</code></a> instead.</p>
<h4 id="DEP0031">DEP0031: <code>ecdh.setPublicKey()</code><span><a class="mark" href="#all_deprecations_dep0031-ecdhsetpublickey" id="all_deprecations_dep0031-ecdhsetpublickey">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0031_ecdh_setpublickey"></a></h4>
<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="#all_crypto_ecdhsetpublickeypublickey-encoding"><code>ecdh.setPublicKey()</code></a> method is now deprecated as its inclusion in the
API is not useful.</p>
<h4 id="DEP0032">DEP0032: <code>node:domain</code> module<span><a class="mark" href="#all_deprecations_dep0032-nodedomain-module" id="all_deprecations_dep0032-nodedomain-module">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0032_node_domain_module"></a></h4>
<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, v4.8.6</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>
<h4 id="DEP0033">DEP0033: <code>EventEmitter.listenerCount()</code><span><a class="mark" href="#all_deprecations_dep0033-eventemitterlistenercount" id="all_deprecations_dep0033-eventemitterlistenercount">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0033_eventemitter_listenercount"></a></h4>
<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, v4.8.6</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="#all_events_eventslistenercountemitter-eventname"><code>events.listenerCount(emitter, eventName)</code></a> API is
deprecated. Please use <a href="#all_events_emitterlistenercounteventname-listener"><code>emitter.listenerCount(eventName)</code></a> instead.</p>
<h4 id="DEP0034">DEP0034: <code>fs.exists(path, callback)</code><span><a class="mark" href="#all_deprecations_dep0034-fsexistspath-callback" id="all_deprecations_dep0034-fsexistspath-callback">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0034_fs_exists_path_callback"></a></h4>
<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, v4.8.6</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="#all_fs_fsexistspath-callback"><code>fs.exists(path, callback)</code></a> API is deprecated. Please use
<a href="#all_fs_fsstatpath-options-callback"><code>fs.stat()</code></a> or <a href="#all_fs_fsaccesspath-mode-callback"><code>fs.access()</code></a> instead.</p>
<h4 id="DEP0035">DEP0035: <code>fs.lchmod(path, mode, callback)</code><span><a class="mark" href="#all_deprecations_dep0035-fslchmodpath-mode-callback" id="all_deprecations_dep0035-fslchmodpath-mode-callback">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0035_fs_lchmod_path_mode_callback"></a></h4>
<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, v4.8.6</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="#all_fs_fslchmodpath-mode-callback"><code>fs.lchmod(path, mode, callback)</code></a> API is deprecated.</p>
<h4 id="DEP0036">DEP0036: <code>fs.lchmodSync(path, mode)</code><span><a class="mark" href="#all_deprecations_dep0036-fslchmodsyncpath-mode" id="all_deprecations_dep0036-fslchmodsyncpath-mode">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0036_fs_lchmodsync_path_mode"></a></h4>
<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, v4.8.6</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="#all_fs_fslchmodsyncpath-mode"><code>fs.lchmodSync(path, mode)</code></a> API is deprecated.</p>
<h4 id="DEP0037">DEP0037: <code>fs.lchown(path, uid, gid, callback)</code><span><a class="mark" href="#all_deprecations_dep0037-fslchownpath-uid-gid-callback" id="all_deprecations_dep0037-fslchownpath-uid-gid-callback">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0037_fs_lchown_path_uid_gid_callback"></a></h4>
<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>v6.12.0, v4.8.6</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="#all_fs_fslchownpath-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>
<h4 id="DEP0038">DEP0038: <code>fs.lchownSync(path, uid, gid)</code><span><a class="mark" href="#all_deprecations_dep0038-fslchownsyncpath-uid-gid" id="all_deprecations_dep0038-fslchownsyncpath-uid-gid">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0038_fs_lchownsync_path_uid_gid"></a></h4>
<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>v6.12.0, v4.8.6</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="#all_fs_fslchownsyncpath-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>
<h4 id="DEP0039">DEP0039: <code>require.extensions</code><span><a class="mark" href="#all_deprecations_dep0039-requireextensions" id="all_deprecations_dep0039-requireextensions">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0039_require_extensions"></a></h4>
<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, v4.8.6</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="#all_modules_requireextensions"><code>require.extensions</code></a> property is deprecated.</p>
<h4 id="DEP0040">DEP0040: <code>node:punycode</code> module<span><a class="mark" href="#all_deprecations_dep0040-nodepunycode-module" id="all_deprecations_dep0040-nodepunycode-module">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0040_node_punycode_module"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.6.0</td>
<td><p>Added support for <code>--pending-deprecation</code>.</p></td></tr>
<tr><td>v7.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only (supports <a href="#all_cli_--pending-deprecation"><code>--pending-deprecation</code></a>)</p>
<p>The <a href="punycode.html"><code>punycode</code></a> module is deprecated. Please use a userland alternative
instead.</p>
<h4 id="DEP0041">DEP0041: <code>NODE_REPL_HISTORY_FILE</code> environment variable<span><a class="mark" href="#all_deprecations_dep0041-node_repl_history_file-environment-variable" id="all_deprecations_dep0041-node_repl_history_file-environment-variable">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0041_node_repl_history_file_environment_variable"></a></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>End-of-Life.</p></td></tr>
<tr><td>v6.12.0, v4.8.6</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>
<h4 id="DEP0042">DEP0042: <code>tls.CryptoStream</code><span><a class="mark" href="#all_deprecations_dep0042-tlscryptostream" id="all_deprecations_dep0042-tlscryptostream">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0042_tls_cryptostream"></a></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>End-of-Life.</p></td></tr>
<tr><td>v6.12.0, v4.8.6</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="#all_tls_class-tlscryptostream"><code>tls.CryptoStream</code></a> class was removed. Please use
<a href="#all_tls_class-tlstlssocket"><code>tls.TLSSocket</code></a> instead.</p>
<h4 id="DEP0043">DEP0043: <code>tls.SecurePair</code><span><a class="mark" href="#all_deprecations_dep0043-tlssecurepair" id="all_deprecations_dep0043-tlssecurepair">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0043_tls_securepair"></a></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>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="#all_tls_class-tlssecurepair"><code>tls.SecurePair</code></a> class is deprecated. Please use
<a href="#all_tls_class-tlstlssocket"><code>tls.TLSSocket</code></a> instead.</p>
<h4 id="DEP0044">DEP0044: <code>util.isArray()</code><span><a class="mark" href="#all_deprecations_dep0044-utilisarray" id="all_deprecations_dep0044-utilisarray">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0044_util_isarray"></a></h4>
<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, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v4.0.0, v3.3.1</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_util_utilisarrayobject"><code>util.isArray()</code></a> API is deprecated. Please use <code>Array.isArray()</code>
instead.</p>
<h4 id="DEP0045">DEP0045: <code>util.isBoolean()</code><span><a class="mark" href="#all_deprecations_dep0045-utilisboolean" id="all_deprecations_dep0045-utilisboolean">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0045_util_isboolean"></a></h4>
<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, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v4.0.0, v3.3.1</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_util_utilisbooleanobject"><code>util.isBoolean()</code></a> API is deprecated.</p>
<h4 id="DEP0046">DEP0046: <code>util.isBuffer()</code><span><a class="mark" href="#all_deprecations_dep0046-utilisbuffer" id="all_deprecations_dep0046-utilisbuffer">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0046_util_isbuffer"></a></h4>
<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, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v4.0.0, v3.3.1</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_util_utilisbufferobject"><code>util.isBuffer()</code></a> API is deprecated. Please use
<a href="#all_buffer_static-method-bufferisbufferobj"><code>Buffer.isBuffer()</code></a> instead.</p>
<h4 id="DEP0047">DEP0047: <code>util.isDate()</code><span><a class="mark" href="#all_deprecations_dep0047-utilisdate" id="all_deprecations_dep0047-utilisdate">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0047_util_isdate"></a></h4>
<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, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v4.0.0, v3.3.1</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_util_utilisdateobject"><code>util.isDate()</code></a> API is deprecated.</p>
<h4 id="DEP0048">DEP0048: <code>util.isError()</code><span><a class="mark" href="#all_deprecations_dep0048-utiliserror" id="all_deprecations_dep0048-utiliserror">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0048_util_iserror"></a></h4>
<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, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v4.0.0, v3.3.1</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_util_utiliserrorobject"><code>util.isError()</code></a> API is deprecated.</p>
<h4 id="DEP0049">DEP0049: <code>util.isFunction()</code><span><a class="mark" href="#all_deprecations_dep0049-utilisfunction" id="all_deprecations_dep0049-utilisfunction">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0049_util_isfunction"></a></h4>
<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, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v4.0.0, v3.3.1</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_util_utilisfunctionobject"><code>util.isFunction()</code></a> API is deprecated.</p>
<h4 id="DEP0050">DEP0050: <code>util.isNull()</code><span><a class="mark" href="#all_deprecations_dep0050-utilisnull" id="all_deprecations_dep0050-utilisnull">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0050_util_isnull"></a></h4>
<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, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v4.0.0, v3.3.1</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_util_utilisnullobject"><code>util.isNull()</code></a> API is deprecated.</p>
<h4 id="DEP0051">DEP0051: <code>util.isNullOrUndefined()</code><span><a class="mark" href="#all_deprecations_dep0051-utilisnullorundefined" id="all_deprecations_dep0051-utilisnullorundefined">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0051_util_isnullorundefined"></a></h4>
<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, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v4.0.0, v3.3.1</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_util_utilisnullorundefinedobject"><code>util.isNullOrUndefined()</code></a> API is deprecated.</p>
<h4 id="DEP0052">DEP0052: <code>util.isNumber()</code><span><a class="mark" href="#all_deprecations_dep0052-utilisnumber" id="all_deprecations_dep0052-utilisnumber">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0052_util_isnumber"></a></h4>
<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, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v4.0.0, v3.3.1</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_util_utilisnumberobject"><code>util.isNumber()</code></a> API is deprecated.</p>
<h4 id="DEP0053">DEP0053: <code>util.isObject()</code><span><a class="mark" href="#all_deprecations_dep0053-utilisobject" id="all_deprecations_dep0053-utilisobject">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0053_util_isobject"></a></h4>
<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, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v4.0.0, v3.3.1</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_util_utilisobjectobject"><code>util.isObject()</code></a> API is deprecated.</p>
<h4 id="DEP0054">DEP0054: <code>util.isPrimitive()</code><span><a class="mark" href="#all_deprecations_dep0054-utilisprimitive" id="all_deprecations_dep0054-utilisprimitive">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0054_util_isprimitive"></a></h4>
<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, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v4.0.0, v3.3.1</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_util_utilisprimitiveobject"><code>util.isPrimitive()</code></a> API is deprecated.</p>
<h4 id="DEP0055">DEP0055: <code>util.isRegExp()</code><span><a class="mark" href="#all_deprecations_dep0055-utilisregexp" id="all_deprecations_dep0055-utilisregexp">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0055_util_isregexp"></a></h4>
<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, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v4.0.0, v3.3.1</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_util_utilisregexpobject"><code>util.isRegExp()</code></a> API is deprecated.</p>
<h4 id="DEP0056">DEP0056: <code>util.isString()</code><span><a class="mark" href="#all_deprecations_dep0056-utilisstring" id="all_deprecations_dep0056-utilisstring">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0056_util_isstring"></a></h4>
<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, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v4.0.0, v3.3.1</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_util_utilisstringobject"><code>util.isString()</code></a> API is deprecated.</p>
<h4 id="DEP0057">DEP0057: <code>util.isSymbol()</code><span><a class="mark" href="#all_deprecations_dep0057-utilissymbol" id="all_deprecations_dep0057-utilissymbol">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0057_util_issymbol"></a></h4>
<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, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v4.0.0, v3.3.1</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_util_utilissymbolobject"><code>util.isSymbol()</code></a> API is deprecated.</p>
<h4 id="DEP0058">DEP0058: <code>util.isUndefined()</code><span><a class="mark" href="#all_deprecations_dep0058-utilisundefined" id="all_deprecations_dep0058-utilisundefined">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0058_util_isundefined"></a></h4>
<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, v4.8.6</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v4.0.0, v3.3.1</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_util_utilisundefinedobject"><code>util.isUndefined()</code></a> API is deprecated.</p>
<h4 id="DEP0059">DEP0059: <code>util.log()</code><span><a class="mark" href="#all_deprecations_dep0059-utillog" id="all_deprecations_dep0059-utillog">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0059_util_log"></a></h4>
<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="#all_util_utillogstring"><code>util.log()</code></a> API is deprecated.</p>
<h4 id="DEP0060">DEP0060: <code>util._extend()</code><span><a class="mark" href="#all_deprecations_dep0060-util_extend" id="all_deprecations_dep0060-util_extend">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0060_util_extend"></a></h4>
<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="#all_util_util_extendtarget-source"><code>util._extend()</code></a> API is deprecated.</p>
<h4 id="DEP0061">DEP0061: <code>fs.SyncWriteStream</code><span><a class="mark" href="#all_deprecations_dep0061-fssyncwritestream" id="all_deprecations_dep0061-fssyncwritestream">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0061_fs_syncwritestream"></a></h4>
<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>
<h4 id="DEP0062">DEP0062: <code>node --debug</code><span><a class="mark" href="#all_deprecations_dep0062-node---debug" id="all_deprecations_dep0062-node---debug">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0062_node_debug"></a></h4>
<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>
<h4 id="DEP0063">DEP0063: <code>ServerResponse.prototype.writeHeader()</code><span><a class="mark" href="#all_deprecations_dep0063-serverresponseprototypewriteheader" id="all_deprecations_dep0063-serverresponseprototypewriteheader">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0063_serverresponse_prototype_writeheader"></a></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>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <code>node: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>
<h4 id="DEP0064">DEP0064: <code>tls.createSecurePair()</code><span><a class="mark" href="#all_deprecations_dep0064-tlscreatesecurepair" id="all_deprecations_dep0064-tlscreatesecurepair">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0064_tls_createsecurepair"></a></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>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>
<h4 id="DEP0065">DEP0065: <code>repl.REPL_MODE_MAGIC</code> and <code>NODE_REPL_MODE=magic</code><span><a class="mark" href="#all_deprecations_dep0065-replrepl_mode_magic-and-node_repl_modemagic" id="all_deprecations_dep0065-replrepl_mode_magic-and-node_repl_modemagic">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0065_repl_repl_mode_magic_and_node_repl_mode_magic"></a></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>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>node: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>
<h4 id="DEP0066">DEP0066: <code>OutgoingMessage.prototype._headers, OutgoingMessage.prototype._headerNames</code><span><a class="mark" href="#all_deprecations_dep0066-outgoingmessageprototype_headers-outgoingmessageprototype_headernames" id="all_deprecations_dep0066-outgoingmessageprototype_headers-outgoingmessageprototype_headernames">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0066_outgoingmessage_prototype_headers_outgoingmessage_prototype_headernames"></a></h4>
<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>node: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.getRawHeaderNames()</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>
<h4 id="DEP0067">DEP0067: <code>OutgoingMessage.prototype._renderHeaders</code><span><a class="mark" href="#all_deprecations_dep0067-outgoingmessageprototype_renderheaders" id="all_deprecations_dep0067-outgoingmessageprototype_renderheaders">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0067_outgoingmessage_prototype_renderheaders"></a></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>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <code>node: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>
<h4 id="DEP0068">DEP0068: <code>node debug</code><span><a class="mark" href="#all_deprecations_dep0068-node-debug" id="all_deprecations_dep0068-node-debug">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0068_node_debug"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>The legacy <code>node debug</code> command was removed.</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>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>
<h4 id="DEP0069">DEP0069: <code>vm.runInDebugContext(string)</code><span><a class="mark" href="#all_deprecations_dep0069-vmrunindebugcontextstring" id="all_deprecations_dep0069-vmrunindebugcontextstring">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0069_vm_runindebugcontext_string"></a></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>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>
<h4 id="DEP0070">DEP0070: <code>async_hooks.currentId()</code><span><a class="mark" href="#all_deprecations_dep0070-async_hookscurrentid" id="all_deprecations_dep0070-async_hookscurrentid">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0070_async_hooks_currentid"></a></h4>
<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>
<h4 id="DEP0071">DEP0071: <code>async_hooks.triggerId()</code><span><a class="mark" href="#all_deprecations_dep0071-async_hookstriggerid" id="all_deprecations_dep0071-async_hookstriggerid">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0071_async_hooks_triggerid"></a></h4>
<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>
<h4 id="DEP0072">DEP0072: <code>async_hooks.AsyncResource.triggerId()</code><span><a class="mark" href="#all_deprecations_dep0072-async_hooksasyncresourcetriggerid" id="all_deprecations_dep0072-async_hooksasyncresourcetriggerid">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0072_async_hooks_asyncresource_triggerid"></a></h4>
<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>
<h4 id="DEP0073">DEP0073: Several internal properties of <code>net.Server</code><span><a class="mark" href="#all_deprecations_dep0073-several-internal-properties-of-netserver" id="all_deprecations_dep0073-several-internal-properties-of-netserver">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0073_several_internal_properties_of_net_server"></a></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>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>
<h4 id="DEP0074">DEP0074: <code>REPLServer.bufferedCommand</code><span><a class="mark" href="#all_deprecations_dep0074-replserverbufferedcommand" id="all_deprecations_dep0074-replserverbufferedcommand">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0074_replserver_bufferedcommand"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.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>The <code>REPLServer.bufferedCommand</code> property was deprecated in favor of
<a href="#all_repl_replserverclearbufferedcommand"><code>REPLServer.clearBufferedCommand()</code></a>.</p>
<h4 id="DEP0075">DEP0075: <code>REPLServer.parseREPLKeyword()</code><span><a class="mark" href="#all_deprecations_dep0075-replserverparsereplkeyword" id="all_deprecations_dep0075-replserverparsereplkeyword">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0075_replserver_parsereplkeyword"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.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><code>REPLServer.parseREPLKeyword()</code> was removed from userland visibility.</p>
<h4 id="DEP0076">DEP0076: <code>tls.parseCertString()</code><span><a class="mark" href="#all_deprecations_dep0076-tlsparsecertstring" id="all_deprecations_dep0076-tlsparsecertstring">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0076_tls_parsecertstring"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.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.6.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p><code>tls.parseCertString()</code> was a trivial parsing helper that was made public by
mistake. While it was supposed to parse certificate subject and issuer strings,
it never handled multi-value Relative Distinguished Names correctly.</p>
<p>Earlier versions of this document suggested using <code>querystring.parse()</code> as an
alternative to <code>tls.parseCertString()</code>. However, <code>querystring.parse()</code> also does
not handle all certificate subjects correctly and should not be used.</p>
<h4 id="DEP0077">DEP0077: <code>Module._debug()</code><span><a class="mark" href="#all_deprecations_dep0077-module_debug" id="all_deprecations_dep0077-module_debug">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0077_module_debug"></a></h4>
<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>
<h4 id="DEP0078">DEP0078: <code>REPLServer.turnOffEditorMode()</code><span><a class="mark" href="#all_deprecations_dep0078-replserverturnoffeditormode" id="all_deprecations_dep0078-replserverturnoffeditormode">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0078_replserver_turnoffeditormode"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.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><code>REPLServer.turnOffEditorMode()</code> was removed from userland visibility.</p>
<h4 id="DEP0079">DEP0079: Custom inspection function on objects via <code>.inspect()</code><span><a class="mark" href="#all_deprecations_dep0079-custom-inspection-function-on-objects-via-inspect" id="all_deprecations_dep0079-custom-inspection-function-on-objects-via-inspect">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0079_custom_inspection_function_on_objects_via_inspect"></a></h4>
<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="#all_util_utilinspectobject-options"><code>util.inspect()</code></a> is deprecated. Use <a href="#all_util_utilinspectcustom"><code>util.inspect.custom</code></a>
instead. For backward compatibility with Node.js prior to version 6.4.0, both
can be specified.</p>
<h4 id="DEP0080">DEP0080: <code>path._makeLong()</code><span><a class="mark" href="#all_deprecations_dep0080-path_makelong" id="all_deprecations_dep0080-path_makelong">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0080_path_makelong"></a></h4>
<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>
<h4 id="DEP0081">DEP0081: <code>fs.truncate()</code> using a file descriptor<span><a class="mark" href="#all_deprecations_dep0081-fstruncate-using-a-file-descriptor" id="all_deprecations_dep0081-fstruncate-using-a-file-descriptor">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0081_fs_truncate_using_a_file_descriptor"></a></h4>
<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>
<h4 id="DEP0082">DEP0082: <code>REPLServer.prototype.memory()</code><span><a class="mark" href="#all_deprecations_dep0082-replserverprototypememory" id="all_deprecations_dep0082-replserverprototypememory">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0082_replserver_prototype_memory"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.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><code>REPLServer.prototype.memory()</code> is only necessary for the internal mechanics of
the <code>REPLServer</code> itself. Do not use this function.</p>
<h4 id="DEP0083">DEP0083: Disabling ECDH by setting <code>ecdhCurve</code> to <code>false</code><span><a class="mark" href="#all_deprecations_dep0083-disabling-ecdh-by-setting-ecdhcurve-to-false" id="all_deprecations_dep0083-disabling-ecdh-by-setting-ecdhcurve-to-false">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0083_disabling_ecdh_by_setting_ecdhcurve_to_false"></a></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>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>
<h4 id="DEP0084">DEP0084: requiring bundled internal dependencies<span><a class="mark" href="#all_deprecations_dep0084-requiring-bundled-internal-dependencies" id="all_deprecations_dep0084-requiring-bundled-internal-dependencies">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0084_requiring_bundled_internal_dependencies"></a></h4>
<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> can 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>
<h4 id="DEP0085">DEP0085: AsyncHooks sensitive API<span><a class="mark" href="#all_deprecations_dep0085-asynchooks-sensitive-api" id="all_deprecations_dep0085-asynchooks-sensitive-api">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0085_asynchooks_sensitive_api"></a></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>End-of-Life.</p></td></tr>
<tr><td>v9.4.0, v8.10.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>
<h4 id="DEP0086">DEP0086: Remove <code>runInAsyncIdScope</code><span><a class="mark" href="#all_deprecations_dep0086-remove-runinasyncidscope" id="all_deprecations_dep0086-remove-runinasyncidscope">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0086_remove_runinasyncidscope"></a></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>End-of-Life.</p></td></tr>
<tr><td>v9.4.0, v8.10.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>
<!-- md-lint skip-deprecation DEP0087 -->
<!-- md-lint skip-deprecation DEP0088 -->
<h4 id="DEP0089">DEP0089: <code>require('node:assert')</code><span><a class="mark" href="#all_deprecations_dep0089-requirenodeassert" id="all_deprecations_dep0089-requirenodeassert">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0089_require_node_assert"></a></h4>
<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, v8.13.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>node:assert</code> module is not discouraged, and the deprecation caused developer
confusion.</p>
<h4 id="DEP0090">DEP0090: Invalid GCM authentication tag lengths<span><a class="mark" href="#all_deprecations_dep0090-invalid-gcm-authentication-tag-lengths" id="all_deprecations_dep0090-invalid-gcm-authentication-tag-lengths">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0090_invalid_gcm_authentication_tag_lengths"></a></h4>
<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="#all_crypto_deciphersetauthtagbuffer-encoding"><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>
<h4 id="DEP0091">DEP0091: <code>crypto.DEFAULT_ENCODING</code><span><a class="mark" href="#all_deprecations_dep0091-cryptodefault_encoding" id="all_deprecations_dep0091-cryptodefault_encoding">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0091_crypto_default_encoding"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.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>The <code>crypto.DEFAULT_ENCODING</code> property only existed for compatibility with
Node.js releases prior to versions 0.9.3 and has been removed.</p>
<h4 id="DEP0092">DEP0092: Top-level <code>this</code> bound to <code>module.exports</code><span><a class="mark" href="#all_deprecations_dep0092-top-level-this-bound-to-moduleexports" id="all_deprecations_dep0092-top-level-this-bound-to-moduleexports">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0092_top_level_this_bound_to_module_exports"></a></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>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>
<h4 id="DEP0093">DEP0093: <code>crypto.fips</code> is deprecated and replaced<span><a class="mark" href="#all_deprecations_dep0093-cryptofips-is-deprecated-and-replaced" id="all_deprecations_dep0093-cryptofips-is-deprecated-and-replaced">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0093_crypto_fips_is_deprecated_and_replaced"></a></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>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_crypto_cryptofips"><code>crypto.fips</code></a> property is deprecated. Please use <code>crypto.setFips()</code>
and <code>crypto.getFips()</code> instead.</p>
<h4 id="DEP0094">DEP0094: Using <code>assert.fail()</code> with more than one argument<span><a class="mark" href="#all_deprecations_dep0094-using-assertfail-with-more-than-one-argument" id="all_deprecations_dep0094-using-assertfail-with-more-than-one-argument">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0094_using_assert_fail_with_more_than_one_argument"></a></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>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>node:assert</code> module
method.</p>
<h4 id="DEP0095">DEP0095: <code>timers.enroll()</code><span><a class="mark" href="#all_deprecations_dep0095-timersenroll" id="all_deprecations_dep0095-timersenroll">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0095_timers_enroll"></a></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>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="#all_timers_settimeoutcallback-delay-args"><code>setTimeout()</code></a> or <a href="#all_timers_setintervalcallback-delay-args"><code>setInterval()</code></a> instead.</p>
<h4 id="DEP0096">DEP0096: <code>timers.unenroll()</code><span><a class="mark" href="#all_deprecations_dep0096-timersunenroll" id="all_deprecations_dep0096-timersunenroll">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0096_timers_unenroll"></a></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>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="#all_timers_cleartimeouttimeout"><code>clearTimeout()</code></a> or <a href="#all_timers_clearintervaltimeout"><code>clearInterval()</code></a> instead.</p>
<h4 id="DEP0097">DEP0097: <code>MakeCallback</code> with <code>domain</code> property<span><a class="mark" href="#all_deprecations_dep0097-makecallback-with-domain-property" id="all_deprecations_dep0097-makecallback-with-domain-property">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0097_makecallback_with_domain_property"></a></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>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>
<h4 id="DEP0098">DEP0098: AsyncHooks embedder <code>AsyncResource.emitBefore</code> and <code>AsyncResource.emitAfter</code> APIs<span><a class="mark" href="#all_deprecations_dep0098-asynchooks-embedder-asyncresourceemitbefore-and-asyncresourceemitafter-apis" id="all_deprecations_dep0098-asynchooks-embedder-asyncresourceemitbefore-and-asyncresourceemitafter-apis">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0098_asynchooks_embedder_asyncresource_emitbefore_and_asyncresource_emitafter_apis"></a></h4>
<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>v10.0.0, v9.6.0, v8.12.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="#all_async_context_asyncresourceruninasyncscopefn-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>
<h4 id="DEP0099">DEP0099: Async context-unaware <code>node::MakeCallback</code> C++ APIs<span><a class="mark" href="#all_deprecations_dep0099-async-context-unaware-nodemakecallback-c-apis" id="all_deprecations_dep0099-async-context-unaware-nodemakecallback-c-apis">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0099_async_context_unaware_node_makecallback_c_apis"></a></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>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 addons are
deprecated. Please use the versions of the API that accept an <code>async_context</code>
parameter.</p>
<h4 id="DEP0100">DEP0100: <code>process.assert()</code><span><a class="mark" href="#all_deprecations_dep0100-processassert" id="all_deprecations_dep0100-processassert">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0100_process_assert"></a></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>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>
<h4 id="DEP0101">DEP0101: <code>--with-lttng</code><span><a class="mark" href="#all_deprecations_dep0101---with-lttng" id="all_deprecations_dep0101---with-lttng">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0101_with_lttng"></a></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>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>
<h4 id="DEP0102">DEP0102: Using <code>noAssert</code> in <code>Buffer#(read|write)</code> operations<span><a class="mark" href="#all_deprecations_dep0102-using-noassert-in-bufferreadwrite-operations" id="all_deprecations_dep0102-using-noassert-in-bufferreadwrite-operations">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0102_using_noassert_in_buffer_read_write_operations"></a></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>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
verified regardless of the value of <code>noAssert</code>. Skipping the verification
could lead to hard-to-find errors and crashes.</p>
<h4 id="DEP0103">DEP0103: <code>process.binding('util').is[...]</code> typechecks<span><a class="mark" href="#all_deprecations_dep0103-processbindingutilis-typechecks" id="all_deprecations_dep0103-processbindingutilis-typechecks">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0103_process_binding_util_is_typechecks"></a></h4>
<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="#all_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="#all_util_utiltypes"><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>
<h4 id="DEP0104">DEP0104: <code>process.env</code> string coercion<span><a class="mark" href="#all_deprecations_dep0104-processenv-string-coercion" id="all_deprecations_dep0104-processenv-string-coercion">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0104_process_env_string_coercion"></a></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>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only (supports <a href="#all_cli_--pending-deprecation"><code>--pending-deprecation</code></a>)</p>
<p>When assigning a non-string property to <a href="#all_process_processenv"><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 might
result in a thrown error. Please convert the property to a string before
assigning it to <code>process.env</code>.</p>
<h4 id="DEP0105">DEP0105: <code>decipher.finaltol</code><span><a class="mark" href="#all_deprecations_dep0105-decipherfinaltol" id="all_deprecations_dep0105-decipherfinaltol">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0105_decipher_finaltol"></a></h4>
<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="#all_crypto_decipherfinaloutputencoding"><code>decipher.final()</code></a>. This API has been removed, and it is recommended to use
<a href="#all_crypto_decipherfinaloutputencoding"><code>decipher.final()</code></a> instead.</p>
<h4 id="DEP0106">DEP0106: <code>crypto.createCipher</code> and <code>crypto.createDecipher</code><span><a class="mark" href="#all_deprecations_dep0106-cryptocreatecipher-and-cryptocreatedecipher" id="all_deprecations_dep0106-cryptocreatecipher-and-cryptocreatedecipher">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0106_crypto_createcipher_and_crypto_createdecipher"></a></h4>
<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="#all_crypto_cryptocreatecipheralgorithm-password-options"><code>crypto.createCipher()</code></a> and <a href="#all_crypto_cryptocreatedecipheralgorithm-password-options"><code>crypto.createDecipher()</code></a> must 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="#all_crypto_cryptopbkdf2password-salt-iterations-keylen-digest-callback"><code>crypto.pbkdf2()</code></a> or <a href="#all_crypto_cryptoscryptpassword-salt-keylen-options-callback"><code>crypto.scrypt()</code></a> with random salts and to use
<a href="#all_crypto_cryptocreatecipherivalgorithm-key-iv-options"><code>crypto.createCipheriv()</code></a> and <a href="#all_crypto_cryptocreatedecipherivalgorithm-key-iv-options"><code>crypto.createDecipheriv()</code></a> to obtain the
<a href="#all_crypto_class-cipher"><code>Cipher</code></a> and <a href="#all_crypto_class-decipher"><code>Decipher</code></a> objects respectively.</p>
<h4 id="DEP0107">DEP0107: <code>tls.convertNPNProtocols()</code><span><a class="mark" href="#all_deprecations_dep0107-tlsconvertnpnprotocols" id="all_deprecations_dep0107-tlsconvertnpnprotocols">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0107_tls_convertnpnprotocols"></a></h4>
<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>
<h4 id="DEP0108">DEP0108: <code>zlib.bytesRead</code><span><a class="mark" href="#all_deprecations_dep0108-zlibbytesread" id="all_deprecations_dep0108-zlibbytesread">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0108_zlib_bytesread"></a></h4>
<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="#all_zlib_zlibbyteswritten"><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>
<h4 id="DEP0109">DEP0109: <code>http</code>, <code>https</code>, and <code>tls</code> support for invalid URLs<span><a class="mark" href="#all_deprecations_dep0109-http-https-and-tls-support-for-invalid-urls" id="all_deprecations_dep0109-http-https-and-tls-support-for-invalid-urls">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0109_http_https_and_tls_support_for_invalid_urls"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.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>Some previously supported (but strictly invalid) URLs were accepted through the
<a href="#all_http_httprequestoptions-callback"><code>http.request()</code></a>, <a href="#all_http_httpgetoptions-callback"><code>http.get()</code></a>, <a href="#all_https_httpsrequestoptions-callback"><code>https.request()</code></a>,
<a href="#all_https_httpsgetoptions-callback"><code>https.get()</code></a>, and <a href="#all_tls_tlscheckserveridentityhostname-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>
<h4 id="DEP0110">DEP0110: <code>vm.Script</code> cached data<span><a class="mark" href="#all_deprecations_dep0110-vmscript-cached-data" id="all_deprecations_dep0110-vmscript-cached-data">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0110_vm_script_cached_data"></a></h4>
<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="#all_vm_scriptcreatecacheddata"><code>script.createCachedData()</code></a> instead.</p>
<h4 id="DEP0111">DEP0111: <code>process.binding()</code><span><a class="mark" href="#all_deprecations_dep0111-processbinding" id="all_deprecations_dep0111-processbinding">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0111_process_binding"></a></h4>
<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="#all_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>While <code>process.binding()</code> has not reached End-of-Life status in general, it is
unavailable when <a href="#all_permissions_policies">policies</a> or the <a href="#all_permissions_permission-model">permission model</a> are enabled.</p>
<h4 id="DEP0112">DEP0112: <code>dgram</code> private APIs<span><a class="mark" href="#all_deprecations_dep0112-dgram-private-apis" id="all_deprecations_dep0112-dgram-private-apis">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0112_dgram_private_apis"></a></h4>
<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>node: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>
<h4 id="DEP0113">DEP0113: <code>Cipher.setAuthTag()</code>, <code>Decipher.getAuthTag()</code><span><a class="mark" href="#all_deprecations_dep0113-ciphersetauthtag-deciphergetauthtag" id="all_deprecations_dep0113-ciphersetauthtag-deciphergetauthtag">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0113_cipher_setauthtag_decipher_getauthtag"></a></h4>
<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>
<h4 id="DEP0114">DEP0114: <code>crypto._toBuf()</code><span><a class="mark" href="#all_deprecations_dep0114-crypto_tobuf" id="all_deprecations_dep0114-crypto_tobuf">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0114_crypto_tobuf"></a></h4>
<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>
<!--lint disable nodejs-yaml-comments -->
<h4 id="DEP0115">DEP0115: <code>crypto.prng()</code>, <code>crypto.pseudoRandomBytes()</code>, <code>crypto.rng()</code><span><a class="mark" href="#all_deprecations_dep0115-cryptoprng-cryptopseudorandombytes-cryptorng" id="all_deprecations_dep0115-cryptoprng-cryptopseudorandombytes-cryptorng">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0115_crypto_prng_crypto_pseudorandombytes_crypto_rng"></a></h4>
<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="#all_cli_--pending-deprecation"><code>--pending-deprecation</code></a>)</p>
<!--lint enable nodejs-yaml-comments -->
<p>In recent versions of Node.js, there is no difference between
<a href="#all_crypto_cryptorandombytessize-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="#all_crypto_cryptorandombytessize-callback"><code>crypto.randomBytes()</code></a> and might be removed in a
future release.</p>
<h4 id="DEP0116">DEP0116: Legacy URL API<span><a class="mark" href="#all_deprecations_dep0116-legacy-url-api" id="all_deprecations_dep0116-legacy-url-api">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0116_legacy_url_api"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0, v18.13.0</td>
<td><p>`url.parse()` is deprecated again in DEP0169.</p></td></tr>
<tr><td>v15.13.0, v14.17.0</td>
<td><p>Deprecation revoked. Status changed to "Legacy".</p></td></tr>
<tr><td>v11.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Deprecation revoked</p>
<p>The <a href="#all_url_legacy-url-api">legacy URL API</a> is deprecated. This includes <a href="#all_url_urlformaturlobject"><code>url.format()</code></a>,
<a href="#all_url_urlparseurlstring-parsequerystring-slashesdenotehost"><code>url.parse()</code></a>, <a href="#all_url_urlresolvefrom-to"><code>url.resolve()</code></a>, and the <a href="#all_url_legacy-urlobject">legacy <code>urlObject</code></a>. Please
use the <a href="#all_url_the-whatwg-url-api">WHATWG URL API</a> instead.</p>
<h4 id="DEP0117">DEP0117: Native crypto handles<span><a class="mark" href="#all_deprecations_dep0117-native-crypto-handles" id="all_deprecations_dep0117-native-crypto-handles">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0117_native_crypto_handles"></a></h4>
<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>
<h4 id="DEP0118">DEP0118: <code>dns.lookup()</code> support for a falsy host name<span><a class="mark" href="#all_deprecations_dep0118-dnslookup-support-for-a-falsy-host-name" id="all_deprecations_dep0118-dnslookup-support-for-a-falsy-host-name">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0118_dns_lookup_support_for_a_falsy_host_name"></a></h4>
<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>
<h4 id="DEP0119">DEP0119: <code>process.binding('uv').errname()</code> private API<span><a class="mark" href="#all_deprecations_dep0119-processbindinguverrname-private-api" id="all_deprecations_dep0119-processbindinguverrname-private-api">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0119_process_binding_uv_errname_private_api"></a></h4>
<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="#all_cli_--pending-deprecation"><code>--pending-deprecation</code></a>)</p>
<p><code>process.binding('uv').errname()</code> is deprecated. Please use
<a href="#all_util_utilgetsystemerrornameerr"><code>util.getSystemErrorName()</code></a> instead.</p>
<h4 id="DEP0120">DEP0120: Windows Performance Counter support<span><a class="mark" href="#all_deprecations_dep0120-windows-performance-counter-support" id="all_deprecations_dep0120-windows-performance-counter-support">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0120_windows_performance_counter_support"></a></h4>
<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>
<h4 id="DEP0121">DEP0121: <code>net._setSimultaneousAccepts()</code><span><a class="mark" href="#all_deprecations_dep0121-net_setsimultaneousaccepts" id="all_deprecations_dep0121-net_setsimultaneousaccepts">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0121_net_setsimultaneousaccepts"></a></h4>
<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>node:child_process</code> and <code>node: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>
<h4 id="DEP0122">DEP0122: <code>tls</code> <code>Server.prototype.setOptions()</code><span><a class="mark" href="#all_deprecations_dep0122-tls-serverprototypesetoptions" id="all_deprecations_dep0122-tls-serverprototypesetoptions">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0122_tls_server_prototype_setoptions"></a></h4>
<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>
<h4 id="DEP0123">DEP0123: setting the TLS ServerName to an IP address<span><a class="mark" href="#all_deprecations_dep0123-setting-the-tls-servername-to-an-ip-address" id="all_deprecations_dep0123-setting-the-tls-servername-to-an-ip-address">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0123_setting_the_tls_servername_to_an_ip_address"></a></h4>
<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>
<h4 id="DEP0124">DEP0124: using <code>REPLServer.rli</code><span><a class="mark" href="#all_deprecations_dep0124-using-replserverrli" id="all_deprecations_dep0124-using-replserverrli">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0124_using_replserver_rli"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>This property is a reference to the instance itself.</p>
<h4 id="DEP0125">DEP0125: <code>require('node:_stream_wrap')</code><span><a class="mark" href="#all_deprecations_dep0125-requirenode_stream_wrap" id="all_deprecations_dep0125-requirenode_stream_wrap">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0125_require_node_stream_wrap"></a></h4>
<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>node:_stream_wrap</code> module is deprecated.</p>
<h4 id="DEP0126">DEP0126: <code>timers.active()</code><span><a class="mark" href="#all_deprecations_dep0126-timersactive" id="all_deprecations_dep0126-timersactive">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0126_timers_active"></a></h4>
<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="#all_timers_timeoutrefresh"><code>timeout.refresh()</code></a> instead.
If re-referencing the timeout is necessary, <a href="#all_timers_timeoutref"><code>timeout.ref()</code></a> can be used
with no performance impact since Node.js 10.</p>
<h4 id="DEP0127">DEP0127: <code>timers._unrefActive()</code><span><a class="mark" href="#all_deprecations_dep0127-timers_unrefactive" id="all_deprecations_dep0127-timers_unrefactive">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0127_timers_unrefactive"></a></h4>
<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="#all_timers_timeoutrefresh"><code>timeout.refresh()</code></a> instead.
If unreferencing the timeout is necessary, <a href="#all_timers_timeoutunref"><code>timeout.unref()</code></a> can be used
with no performance impact since Node.js 10.</p>
<h4 id="DEP0128">DEP0128: modules with an invalid <code>main</code> entry and an <code>index.js</code> file<span><a class="mark" href="#all_deprecations_dep0128-modules-with-an-invalid-main-entry-and-an-indexjs-file" id="all_deprecations_dep0128-modules-with-an-invalid-main-entry-and-an-indexjs-file">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0128_modules_with_an_invalid_main_entry_and_an_index_js_file"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>Documentation-only.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</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>
<h4 id="DEP0129">DEP0129: <code>ChildProcess._channel</code><span><a class="mark" href="#all_deprecations_dep0129-childprocess_channel" id="all_deprecations_dep0129-childprocess_channel">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0129_childprocess_channel"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v11.14.0</td>
<td><p>Documentation-only.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</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>
<h4 id="DEP0130">DEP0130: <code>Module.createRequireFromPath()</code><span><a class="mark" href="#all_deprecations_dep0130-modulecreaterequirefrompath" id="all_deprecations_dep0130-modulecreaterequirefrompath">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0130_module_createrequirefrompath"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0</td>
<td><p>End-of-life.</p></td></tr>
<tr><td>v13.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v12.2.0</td>
<td><p>Documentation-only.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>Use <a href="#all_module_modulecreaterequirefilename"><code>module.createRequire()</code></a> instead.</p>
<h4 id="DEP0131">DEP0131: Legacy HTTP parser<span><a class="mark" href="#all_deprecations_dep0131-legacy-http-parser" id="all_deprecations_dep0131-legacy-http-parser">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0131_legacy_http_parser"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.0.0</td>
<td><p>This feature has been removed.</p></td></tr>
<tr><td>v12.22.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v12.3.0</td>
<td><p>Documentation-only.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The legacy HTTP parser, used by default in versions of Node.js prior to 12.0.0,
is deprecated and has been removed in v13.0.0. Prior to v13.0.0, the
<code>--http-parser=legacy</code> command-line flag could be used to revert to using the
legacy parser.</p>
<h4 id="DEP0132">DEP0132: <code>worker.terminate()</code> with callback<span><a class="mark" href="#all_deprecations_dep0132-workerterminate-with-callback" id="all_deprecations_dep0132-workerterminate-with-callback">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0132_worker_terminate_with_callback"></a></h4>
<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="#all_worker_threads_workerterminate"><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>
<h4 id="DEP0133">DEP0133: <code>http</code> <code>connection</code><span><a class="mark" href="#all_deprecations_dep0133-http-connection" id="all_deprecations_dep0133-http-connection">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0133_http_connection"></a></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>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>Prefer <a href="#all_http_responsesocket"><code>response.socket</code></a> over <a href="#all_http_responseconnection"><code>response.connection</code></a> and
<a href="#all_http_requestsocket"><code>request.socket</code></a> over <a href="#all_http_requestconnection"><code>request.connection</code></a>.</p>
<h4 id="DEP0134">DEP0134: <code>process._tickCallback</code><span><a class="mark" href="#all_deprecations_dep0134-process_tickcallback" id="all_deprecations_dep0134-process_tickcallback">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0134_process_tickcallback"></a></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>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only (supports <a href="#all_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>
<h4 id="DEP0135">DEP0135: <code>WriteStream.open()</code> and <code>ReadStream.open()</code> are internal<span><a class="mark" href="#all_deprecations_dep0135-writestreamopen-and-readstreamopen-are-internal" id="all_deprecations_dep0135-writestreamopen-and-readstreamopen-are-internal">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0135_writestream_open_and_readstream_open_are_internal"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p><a href="#all_fs_class-fswritestream"><code>WriteStream.open()</code></a> and <a href="#all_fs_class-fsreadstream"><code>ReadStream.open()</code></a> are undocumented internal
APIs that do not make sense to use in userland. File streams should always be
opened through their corresponding factory methods <a href="#all_fs_fscreatewritestreampath-options"><code>fs.createWriteStream()</code></a>
and <a href="#all_fs_fscreatereadstreampath-options"><code>fs.createReadStream()</code></a>) or by passing a file descriptor in options.</p>
<h4 id="DEP0136">DEP0136: <code>http</code> <code>finished</code><span><a class="mark" href="#all_deprecations_dep0136-http-finished" id="all_deprecations_dep0136-http-finished">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0136_http_finished"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.4.0, v12.16.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p><a href="#all_http_responsefinished"><code>response.finished</code></a> indicates whether <a href="#all_http_responseenddata-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="#all_http_responsewritablefinished"><code>response.writableFinished</code></a> or <a href="#all_http_responsewritableended"><code>response.writableEnded</code></a>
accordingly instead to avoid the ambiguity.</p>
<p>To maintain existing behavior <code>response.finished</code> should be replaced with
<code>response.writableEnded</code>.</p>
<h4 id="DEP0137">DEP0137: Closing fs.FileHandle on garbage collection<span><a class="mark" href="#all_deprecations_dep0137-closing-fsfilehandle-on-garbage-collection" id="all_deprecations_dep0137-closing-fsfilehandle-on-garbage-collection">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0137_closing_fs_filehandle_on_garbage_collection"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>Allowing a <a href="#all_fs_class-filehandle"><code>fs.FileHandle</code></a> object to be closed on garbage collection is
deprecated. In the future, doing so might result in a thrown error that will
terminate the process.</p>
<p>Please ensure that all <code>fs.FileHandle</code> objects are explicitly closed using
<code>FileHandle.prototype.close()</code> when the <code>fs.FileHandle</code> is no longer needed:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> fsPromises = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>).<span class="hljs-property">promises</span>;
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">openAndClose</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">let</span> filehandle;
  <span class="hljs-keyword">try</span> {
    filehandle = <span class="hljs-keyword">await</span> fsPromises.<span class="hljs-title function_">open</span>(<span class="hljs-string">'thefile.txt'</span>, <span class="hljs-string">'r'</span>);
  } <span class="hljs-keyword">finally</span> {
    <span class="hljs-keyword">if</span> (filehandle !== <span class="hljs-literal">undefined</span>)
      <span class="hljs-keyword">await</span> filehandle.<span class="hljs-title function_">close</span>();
  }
}</code> <button class="copy-button">copy</button></pre>
<h4 id="DEP0138">DEP0138: <code>process.mainModule</code><span><a class="mark" href="#all_deprecations_dep0138-processmainmodule" id="all_deprecations_dep0138-processmainmodule">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0138_process_mainmodule"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p><a href="#all_process_processmainmodule"><code>process.mainModule</code></a> is a CommonJS-only feature while <code>process</code> global
object is shared with non-CommonJS environment. Its use within ECMAScript
modules is unsupported.</p>
<p>It is deprecated in favor of <a href="#all_modules_accessing-the-main-module"><code>require.main</code></a>, because it serves the same
purpose and is only available on CommonJS environment.</p>
<h4 id="DEP0139">DEP0139: <code>process.umask()</code> with no arguments<span><a class="mark" href="#all_deprecations_dep0139-processumask-with-no-arguments" id="all_deprecations_dep0139-processumask-with-no-arguments">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0139_process_umask_with_no_arguments"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.0.0, v12.19.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>Calling <code>process.umask()</code> with no argument causes the process-wide umask to be
written twice. This introduces a race condition between threads, and is a
potential security vulnerability. There is no safe, cross-platform alternative
API.</p>
<h4 id="DEP0140">DEP0140: Use <code>request.destroy()</code> instead of <code>request.abort()</code><span><a class="mark" href="#all_deprecations_dep0140-use-requestdestroy-instead-of-requestabort" id="all_deprecations_dep0140-use-requestdestroy-instead-of-requestabort">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0140_use_request_destroy_instead_of_request_abort"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.1.0, v13.14.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>Use <a href="#all_http_requestdestroyerror"><code>request.destroy()</code></a> instead of <a href="#all_http_requestabort"><code>request.abort()</code></a>.</p>
<h4 id="DEP0141">DEP0141: <code>repl.inputStream</code> and <code>repl.outputStream</code><span><a class="mark" href="#all_deprecations_dep0141-replinputstream-and-reploutputstream" id="all_deprecations_dep0141-replinputstream-and-reploutputstream">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0141_repl_inputstream_and_repl_outputstream"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.3.0</td>
<td><p>Documentation-only (supports [<code>--pending-deprecation</code>][]).</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only (supports <a href="#all_cli_--pending-deprecation"><code>--pending-deprecation</code></a>)</p>
<p>The <code>node:repl</code> module exported the input and output stream twice. Use <code>.input</code>
instead of <code>.inputStream</code> and <code>.output</code> instead of <code>.outputStream</code>.</p>
<h4 id="DEP0142">DEP0142: <code>repl._builtinLibs</code><span><a class="mark" href="#all_deprecations_dep0142-repl_builtinlibs" id="all_deprecations_dep0142-repl_builtinlibs">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0142_repl_builtinlibs"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.3.0</td>
<td><p>Documentation-only (supports [<code>--pending-deprecation</code>][]).</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <code>node:repl</code> module exports a <code>_builtinLibs</code> property that contains an array
of built-in modules. It was incomplete so far and instead it's better to rely
upon <code>require('node:module').builtinModules</code>.</p>
<h4 id="DEP0143">DEP0143: <code>Transform._transformState</code><span><a class="mark" href="#all_deprecations_dep0143-transform_transformstate" id="all_deprecations_dep0143-transform_transformstate">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0143_transform_transformstate"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.5.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime
<code>Transform._transformState</code> will be removed in future versions where it is
no longer required due to simplification of the implementation.</p>
<h4 id="DEP0144">DEP0144: <code>module.parent</code><span><a class="mark" href="#all_deprecations_dep0144-moduleparent" id="all_deprecations_dep0144-moduleparent">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0144_module_parent"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.6.0, v12.19.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only (supports <a href="#all_cli_--pending-deprecation"><code>--pending-deprecation</code></a>)</p>
<p>A CommonJS module can access the first module that required it using
<code>module.parent</code>. This feature is deprecated because it does not work
consistently in the presence of ECMAScript modules and because it gives an
inaccurate representation of the CommonJS module graph.</p>
<p>Some modules use it to check if they are the entry point of the current process.
Instead, it is recommended to compare <code>require.main</code> and <code>module</code>:</p>
<pre><code class="language-js"><span class="hljs-keyword">if</span> (<span class="hljs-built_in">require</span>.<span class="hljs-property">main</span> === <span class="hljs-variable language_">module</span>) {
  <span class="hljs-comment">// Code section that will run only if current file is the entry point.</span>
}</code> <button class="copy-button">copy</button></pre>
<p>When looking for the CommonJS modules that have required the current one,
<code>require.cache</code> and <code>module.children</code> can be used:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> moduleParents = <span class="hljs-title class_">Object</span>.<span class="hljs-title function_">values</span>(<span class="hljs-built_in">require</span>.<span class="hljs-property">cache</span>)
  .<span class="hljs-title function_">filter</span>(<span class="hljs-function">(<span class="hljs-params">m</span>) =></span> m.<span class="hljs-property">children</span>.<span class="hljs-title function_">includes</span>(<span class="hljs-variable language_">module</span>));</code> <button class="copy-button">copy</button></pre>
<h4 id="DEP0145">DEP0145: <code>socket.bufferSize</code><span><a class="mark" href="#all_deprecations_dep0145-socketbuffersize" id="all_deprecations_dep0145-socketbuffersize">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0145_socket_buffersize"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.6.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p><a href="#all_net_socketbuffersize"><code>socket.bufferSize</code></a> is just an alias for <a href="#all_stream_writablewritablelength"><code>writable.writableLength</code></a>.</p>
<h4 id="DEP0146">DEP0146: <code>new crypto.Certificate()</code><span><a class="mark" href="#all_deprecations_dep0146-new-cryptocertificate" id="all_deprecations_dep0146-new-cryptocertificate">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0146_new_crypto_certificate"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.9.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_crypto_legacy-api"><code>crypto.Certificate()</code> constructor</a> is deprecated. Use
<a href="#all_crypto_class-certificate">static methods of <code>crypto.Certificate()</code></a> instead.</p>
<h4 id="DEP0147">DEP0147: <code>fs.rmdir(path, { recursive: true })</code><span><a class="mark" href="#all_deprecations_dep0147-fsrmdirpath--recursive-true-" id="all_deprecations_dep0147-fsrmdirpath--recursive-true-">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0147_fs_rmdir_path_recursive_true"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p>Runtime deprecation for permissive behavior.</p></td></tr>
<tr><td>v14.14.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>In future versions of Node.js, <code>recursive</code> option will be ignored for
<code>fs.rmdir</code>, <code>fs.rmdirSync</code>, and <code>fs.promises.rmdir</code>.</p>
<p>Use <code>fs.rm(path, { recursive: true, force: true })</code>,
<code>fs.rmSync(path, { recursive: true, force: true })</code> or
<code>fs.promises.rm(path, { recursive: true, force: true })</code> instead.</p>
<h4 id="DEP0148">DEP0148: Folder mappings in <code>"exports"</code> (trailing <code>"/"</code>)<span><a class="mark" href="#all_deprecations_dep0148-folder-mappings-in-exports-trailing-" id="all_deprecations_dep0148-folder-mappings-in-exports-trailing-">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0148_folder_mappings_in_exports_trailing"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v15.1.0</td>
<td><p>Runtime deprecation for self-referencing imports.</p></td></tr>
<tr><td>v14.13.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>Using a trailing <code>"/"</code> to define subpath folder mappings in the
<a href="#all_packages_subpath-exports">subpath exports</a> or <a href="#all_packages_subpath-imports">subpath imports</a> fields is deprecated. Use
<a href="#all_packages_subpath-patterns">subpath patterns</a> instead.</p>
<h4 id="DEP0149">DEP0149: <code>http.IncomingMessage#connection</code><span><a class="mark" href="#all_deprecations_dep0149-httpincomingmessageconnection" id="all_deprecations_dep0149-httpincomingmessageconnection">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0149_http_incomingmessage_connection"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only.</p>
<p>Prefer <a href="#all_http_messagesocket"><code>message.socket</code></a> over <a href="#all_http_messageconnection"><code>message.connection</code></a>.</p>
<h4 id="DEP0150">DEP0150: Changing the value of <code>process.config</code><span><a class="mark" href="#all_deprecations_dep0150-changing-the-value-of-processconfig" id="all_deprecations_dep0150-changing-the-value-of-processconfig">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0150_changing_the_value_of_process_config"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The <code>process.config</code> property provides access to Node.js compile-time settings.
However, the property is mutable and therefore subject to tampering. The ability
to change the value will be removed in a future version of Node.js.</p>
<h4 id="DEP0151">DEP0151: Main index lookup and extension searching<span><a class="mark" href="#all_deprecations_dep0151-main-index-lookup-and-extension-searching" id="all_deprecations_dep0151-main-index-lookup-and-extension-searching">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0151_main_index_lookup_and_extension_searching"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v15.8.0, v14.18.0</td>
<td><p>Documentation-only deprecation with <code>--pending-deprecation</code> support.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>Previously, <code>index.js</code> and extension searching lookups would apply to
<code>import 'pkg'</code> main entry point resolution, even when resolving ES modules.</p>
<p>With this deprecation, all ES module main entry point resolutions require
an explicit <a href="#all_packages_main-entry-point-export"><code>"exports"</code> or <code>"main"</code> entry</a> with the exact file extension.</p>
<h4 id="DEP0152">DEP0152: Extension PerformanceEntry properties<span><a class="mark" href="#all_deprecations_dep0152-extension-performanceentry-properties" id="all_deprecations_dep0152-extension-performanceentry-properties">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0152_extension_performanceentry_properties"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>The <code>'gc'</code>, <code>'http2'</code>, and <code>'http'</code> <a href="#all_perf_hooks_class-performanceentry" class="type">&#x3C;PerformanceEntry></a> object types have
additional properties assigned to them that provide additional information.
These properties are now available within the standard <code>detail</code> property
of the <code>PerformanceEntry</code> object. The existing accessors have been
deprecated and should no longer be used.</p>
<h4 id="DEP0153">DEP0153: <code>dns.lookup</code> and <code>dnsPromises.lookup</code> options type coercion<span><a class="mark" href="#all_deprecations_dep0153-dnslookup-and-dnspromiseslookup-options-type-coercion" id="all_deprecations_dep0153-dnslookup-and-dnspromiseslookup-options-type-coercion">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0153_dns_lookup_and_dnspromises_lookup_options_type_coercion"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v17.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v16.8.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>Using a non-nullish non-integer value for <code>family</code> option, a non-nullish
non-number value for <code>hints</code> option, a non-nullish non-boolean value for <code>all</code>
option, or a non-nullish non-boolean value for <code>verbatim</code> option in
<a href="#all_dns_dnslookuphostname-options-callback"><code>dns.lookup()</code></a> and <a href="#all_dns_dnspromiseslookuphostname-options"><code>dnsPromises.lookup()</code></a> throws an
<code>ERR_INVALID_ARG_TYPE</code> error.</p>
<h4 id="DEP0154">DEP0154: RSA-PSS generate key pair options<span><a class="mark" href="#all_deprecations_dep0154-rsa-pss-generate-key-pair-options" id="all_deprecations_dep0154-rsa-pss-generate-key-pair-options">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0154_rsa_pss_generate_key_pair_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v16.10.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>The <code>'hash'</code> and <code>'mgf1Hash'</code> options are replaced with <code>'hashAlgorithm'</code>
and <code>'mgf1HashAlgorithm'</code>.</p>
<h4 id="DEP0155">DEP0155: Trailing slashes in pattern specifier resolutions<span><a class="mark" href="#all_deprecations_dep0155-trailing-slashes-in-pattern-specifier-resolutions" id="all_deprecations_dep0155-trailing-slashes-in-pattern-specifier-resolutions">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0155_trailing_slashes_in_pattern_specifier_resolutions"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v16.10.0</td>
<td><p>Documentation-only deprecation with <code>--pending-deprecation</code> support.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>The remapping of specifiers ending in <code>"/"</code> like <code>import 'pkg/x/'</code> is deprecated
for package <code>"exports"</code> and <code>"imports"</code> pattern resolutions.</p>
<h4 id="DEP0156">DEP0156: <code>.aborted</code> property and <code>'abort'</code>, <code>'aborted'</code> event in <code>http</code><span><a class="mark" href="#all_deprecations_dep0156-aborted-property-and-abort-aborted-event-in-http" id="all_deprecations_dep0156-aborted-property-and-abort-aborted-event-in-http">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0156_aborted_property_and_abort_aborted_event_in_http"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.0.0, v16.12.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>Move to <a href="#all_stream_stream" class="type">&#x3C;Stream></a> API instead, as the <a href="#all_http_class-httpclientrequest"><code>http.ClientRequest</code></a>,
<a href="#all_http_class-httpserverresponse"><code>http.ServerResponse</code></a>, and <a href="#all_http_class-httpincomingmessage"><code>http.IncomingMessage</code></a> are all stream-based.
Check <code>stream.destroyed</code> instead of the <code>.aborted</code> property, and listen for
<code>'close'</code> instead of <code>'abort'</code>, <code>'aborted'</code> event.</p>
<p>The <code>.aborted</code> property and <code>'abort'</code> event are only useful for detecting
<code>.abort()</code> calls. For closing a request early, use the Stream
<code>.destroy([error])</code> then check the <code>.destroyed</code> property and <code>'close'</code> event
should have the same effect. The receiving end should also check the
<a href="#all_stream_readablereadableended"><code>readable.readableEnded</code></a> value on <a href="#all_http_class-httpincomingmessage"><code>http.IncomingMessage</code></a> to get whether
it was an aborted or graceful destroy.</p>
<h4 id="DEP0157">DEP0157: Thenable support in streams<span><a class="mark" href="#all_deprecations_dep0157-thenable-support-in-streams" id="all_deprecations_dep0157-thenable-support-in-streams">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0157_thenable_support_in_streams"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>End-of-life.</p></td></tr>
<tr><td>v17.2.0, v16.14.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>An undocumented feature of Node.js streams was to support thenables in
implementation methods. This is now deprecated, use callbacks instead and avoid
use of async function for streams implementation methods.</p>
<p>This feature caused users to encounter unexpected problems where the user
implements the function in callback style but uses e.g. an async method which
would cause an error since mixing promise and callback semantics is not valid.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> w = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>({
  <span class="hljs-keyword">async</span> <span class="hljs-title function_">final</span>(<span class="hljs-params">callback</span>) {
    <span class="hljs-keyword">await</span> <span class="hljs-title function_">someOp</span>();
    <span class="hljs-title function_">callback</span>();
  },
});</code> <button class="copy-button">copy</button></pre>
<h4 id="DEP0158">DEP0158: <code>buffer.slice(start, end)</code><span><a class="mark" href="#all_deprecations_dep0158-bufferslicestart-end" id="all_deprecations_dep0158-bufferslicestart-end">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0158_buffer_slice_start_end"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.5.0, v16.15.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>This method was deprecated because it is not compatible with
<code>Uint8Array.prototype.slice()</code>, which is a superclass of <code>Buffer</code>.</p>
<p>Use <a href="#all_buffer_bufsubarraystart-end"><code>buffer.subarray</code></a> which does the same thing instead.</p>
<h4 id="DEP0159">DEP0159: <code>ERR_INVALID_CALLBACK</code><span><a class="mark" href="#all_deprecations_dep0159-err_invalid_callback" id="all_deprecations_dep0159-err_invalid_callback">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0159_err_invalid_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>End-of-Life.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>This error code was removed due to adding more confusion to
the errors used for value type validation.</p>
<h4 id="DEP0160">DEP0160: <code>process.on('multipleResolves', handler)</code><span><a class="mark" href="#all_deprecations_dep0160-processonmultipleresolves-handler" id="all_deprecations_dep0160-processonmultipleresolves-handler">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0160_process_on_multipleresolves_handler"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v17.6.0, v16.15.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime.</p>
<p>This event was deprecated because it did not work with V8 promise combinators
which diminished its usefulness.</p>
<h4 id="DEP0161">DEP0161: <code>process._getActiveRequests()</code> and <code>process._getActiveHandles()</code><span><a class="mark" href="#all_deprecations_dep0161-process_getactiverequests-and-process_getactivehandles" id="all_deprecations_dep0161-process_getactiverequests-and-process_getactivehandles">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0161_process_getactiverequests_and_process_getactivehandles"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.6.0, v16.15.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <code>process._getActiveHandles()</code> and <code>process._getActiveRequests()</code>
functions are not intended for public use and can be removed in future
releases.</p>
<p>Use <a href="#all_process_processgetactiveresourcesinfo"><code>process.getActiveResourcesInfo()</code></a> to get a list of types of active
resources and not the actual references.</p>
<h4 id="DEP0162">DEP0162: <code>fs.write()</code>, <code>fs.writeFileSync()</code> coercion to string<span><a class="mark" href="#all_deprecations_dep0162-fswrite-fswritefilesync-coercion-to-string" id="all_deprecations_dep0162-fswrite-fswritefilesync-coercion-to-string">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0162_fs_write_fs_writefilesync_coercion_to_string"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v18.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v17.8.0, v16.15.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>Implicit coercion of objects with own <code>toString</code> property, passed as second
parameter in <a href="#all_fs_fswritefd-buffer-offset-length-position-callback"><code>fs.write()</code></a>, <a href="#all_fs_fswritefilefile-data-options-callback"><code>fs.writeFile()</code></a>, <a href="#all_fs_fsappendfilepath-data-options-callback"><code>fs.appendFile()</code></a>,
<a href="#all_fs_fswritefilesyncfile-data-options"><code>fs.writeFileSync()</code></a>, and <a href="#all_fs_fsappendfilesyncpath-data-options"><code>fs.appendFileSync()</code></a> is deprecated.
Convert them to primitive strings.</p>
<h4 id="DEP0163">DEP0163: <code>channel.subscribe(onMessage)</code>, <code>channel.unsubscribe(onMessage)</code><span><a class="mark" href="#all_deprecations_dep0163-channelsubscribeonmessage-channelunsubscribeonmessage" id="all_deprecations_dep0163-channelsubscribeonmessage-channelunsubscribeonmessage">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0163_channel_subscribe_onmessage_channel_unsubscribe_onmessage"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.7.0, v16.17.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>These methods were deprecated because they can be used in a way which does not
hold the channel reference alive long enough to receive the events.</p>
<p>Use <a href="#all_diagnostics_channel_diagnostics_channelsubscribename-onmessage"><code>diagnostics_channel.subscribe(name, onMessage)</code></a> or
<a href="#all_diagnostics_channel_diagnostics_channelunsubscribename-onmessage"><code>diagnostics_channel.unsubscribe(name, onMessage)</code></a> which does the same
thing instead.</p>
<h4 id="DEP0164">DEP0164: <code>process.exit(code)</code>, <code>process.exitCode</code> coercion to integer<span><a class="mark" href="#all_deprecations_dep0164-processexitcode-processexitcode-coercion-to-integer" id="all_deprecations_dep0164-processexitcode-processexitcode-coercion-to-integer">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0164_process_exit_code_process_exitcode_coercion_to_integer"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v19.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v18.10.0, v16.18.0</td>
<td><p>Documentation-only deprecation of <code>process.exitCode</code> integer coercion.</p></td></tr>
<tr><td>v18.7.0, v16.17.0</td>
<td><p>Documentation-only deprecation of <code>process.exit(code)</code> integer coercion.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>Values other than <code>undefined</code>, <code>null</code>, integer numbers, and integer strings
(e.g., <code>'1'</code>) are deprecated as value for the <code>code</code> parameter in
<a href="#all_process_processexitcode"><code>process.exit()</code></a> and as value to assign to <a href="#all_process_processexitcode_1"><code>process.exitCode</code></a>.</p>
<h4 id="DEP0165">DEP0165: <code>--trace-atomics-wait</code><span><a class="mark" href="#all_deprecations_dep0165---trace-atomics-wait" id="all_deprecations_dep0165---trace-atomics-wait">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0165_trace_atomics_wait"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.8.0, v16.18.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_cli_--trace-atomics-wait"><code>--trace-atomics-wait</code></a> flag is deprecated.</p>
<h4 id="DEP0166">DEP0166: Double slashes in imports and exports targets<span><a class="mark" href="#all_deprecations_dep0166-double-slashes-in-imports-and-exports-targets" id="all_deprecations_dep0166-double-slashes-in-imports-and-exports-targets">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0166_double_slashes_in_imports_and_exports_targets"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v18.10.0</td>
<td><p>Documentation-only deprecation with <code>--pending-deprecation</code> support.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>Package imports and exports targets mapping into paths including a double slash
(of <em>"/"</em> or <em>"\"</em>) are deprecated and will fail with a resolution validation
error in a future release. This same deprecation also applies to pattern matches
starting or ending in a slash.</p>
<h4 id="DEP0167">DEP0167: Weak <code>DiffieHellmanGroup</code> instances (<code>modp1</code>, <code>modp2</code>, <code>modp5</code>)<span><a class="mark" href="#all_deprecations_dep0167-weak-diffiehellmangroup-instances-modp1-modp2-modp5" id="all_deprecations_dep0167-weak-diffiehellmangroup-instances-modp1-modp2-modp5">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0167_weak_diffiehellmangroup_instances_modp1_modp2_modp5"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.10.0, v16.18.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The well-known MODP groups <code>modp1</code>, <code>modp2</code>, and <code>modp5</code> are deprecated because
they are not secure against practical attacks. See <a href="https://www.rfc-editor.org/rfc/rfc8247#section-2.4">RFC 8247 Section 2.4</a> for
details.</p>
<p>These groups might be removed in future versions of Node.js. Applications that
rely on these groups should evaluate using stronger MODP groups instead.</p>
<h4 id="DEP0168">DEP0168: Unhandled exception in Node-API callbacks<span><a class="mark" href="#all_deprecations_dep0168-unhandled-exception-in-node-api-callbacks" id="all_deprecations_dep0168-unhandled-exception-in-node-api-callbacks">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0168_unhandled_exception_in_node_api_callbacks"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.3.0, v16.17.0</td>
<td><p>Runtime deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>The implicit suppression of uncaught exceptions in Node-API callbacks is now
deprecated.</p>
<p>Set the flag <a href="#all_cli_--force-node-api-uncaught-exceptions-policy"><code>--force-node-api-uncaught-exceptions-policy</code></a> to force Node.js
to emit an <a href="#all_process_event-uncaughtexception"><code>'uncaughtException'</code></a> event if the exception is not handled in
Node-API callbacks.</p>
<h4 id="DEP0169">DEP0169: Insecure url.parse()<span><a class="mark" href="#all_deprecations_dep0169-insecure-urlparse" id="all_deprecations_dep0169-insecure-urlparse">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0169_insecure_url_parse"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.9.0</td>
<td><p>Added support for <code>--pending-deprecation</code>.</p></td></tr>
<tr><td>v19.0.0, v18.13.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only (supports <a href="#all_cli_--pending-deprecation"><code>--pending-deprecation</code></a>)</p>
<p><a href="#all_url_urlparseurlstring-parsequerystring-slashesdenotehost"><code>url.parse()</code></a> behavior is not standardized and prone to errors that
have security implications. Use the <a href="#all_url_the-whatwg-url-api">WHATWG URL API</a> instead. CVEs are not
issued for <code>url.parse()</code> vulnerabilities.</p>
<h4 id="DEP0170">DEP0170: Invalid port when using <code>url.parse()</code><span><a class="mark" href="#all_deprecations_dep0170-invalid-port-when-using-urlparse" id="all_deprecations_dep0170-invalid-port-when-using-urlparse">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0170_invalid_port_when_using_url_parse"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>Runtime deprecation.</p></td></tr>
<tr><td>v19.2.0, v18.13.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p><a href="#all_url_urlparseurlstring-parsequerystring-slashesdenotehost"><code>url.parse()</code></a> accepts URLs with ports that are not numbers. This behavior
might result in host name spoofing with unexpected input. These URLs will throw
an error in future versions of Node.js, as the <a href="#all_url_the-whatwg-url-api">WHATWG URL API</a> does already.</p>
<h4 id="DEP0171">DEP0171: Setters for <code>http.IncomingMessage</code> headers and trailers<span><a class="mark" href="#all_deprecations_dep0171-setters-for-httpincomingmessage-headers-and-trailers" id="all_deprecations_dep0171-setters-for-httpincomingmessage-headers-and-trailers">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0171_setters_for_http_incomingmessage_headers_and_trailers"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.3.0, v18.13.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>In a future version of Node.js, <a href="#all_http_messageheaders"><code>message.headers</code></a>,
<a href="#all_http_messageheadersdistinct"><code>message.headersDistinct</code></a>, <a href="#all_http_messagetrailers"><code>message.trailers</code></a>, and
<a href="#all_http_messagetrailersdistinct"><code>message.trailersDistinct</code></a> will be read-only.</p>
<h4 id="DEP0172">DEP0172: The <code>asyncResource</code> property of <code>AsyncResource</code> bound functions<span><a class="mark" href="#all_deprecations_dep0172-the-asyncresource-property-of-asyncresource-bound-functions" id="all_deprecations_dep0172-the-asyncresource-property-of-asyncresource-bound-functions">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0172_the_asyncresource_property_of_asyncresource_bound_functions"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>Runtime-deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Runtime</p>
<p>In a future version of Node.js, the <code>asyncResource</code> property will no longer
be added when a function is bound to an <code>AsyncResource</code>.</p>
<h4 id="DEP0173">DEP0173: the <code>assert.CallTracker</code> class<span><a class="mark" href="#all_deprecations_dep0173-the-assertcalltracker-class" id="all_deprecations_dep0173-the-assertcalltracker-class">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0173_the_assert_calltracker_class"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.1.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>In a future version of Node.js, <a href="#all_assert_class-assertcalltracker"><code>assert.CallTracker</code></a>,
will be removed.
Consider using alternatives such as the <a href="#all_test_mocking"><code>mock</code></a> helper function.</p>
<h4 id="DEP0174">DEP0174: calling <code>promisify</code> on a function that returns a <code>Promise</code><span><a class="mark" href="#all_deprecations_dep0174-calling-promisify-on-a-function-that-returns-a-promise" id="all_deprecations_dep0174-calling-promisify-on-a-function-that-returns-a-promise">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0174_calling_promisify_on_a_function_that_returns_a_promise"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.8.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>Calling <a href="#all_util_utilpromisifyoriginal"><code>util.promisify</code></a> on a function that returns a <promise> will ignore
the result of said promise, which can lead to unhandled promise rejections.</promise></p>
<h4 id="DEP0175">DEP0175: <code>util.toUSVString</code><span><a class="mark" href="#all_deprecations_dep0175-utiltousvstring" id="all_deprecations_dep0175-utiltousvstring">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0175_util_tousvstring"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.8.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_util_utiltousvstringstring"><code>util.toUSVString()</code></a> API is deprecated. Please use
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toWellFormed"><code>String.prototype.toWellFormed</code></a> instead.</p>
<h4 id="DEP0176">DEP0176: <code>fs.F_OK</code>, <code>fs.R_OK</code>, <code>fs.W_OK</code>, <code>fs.X_OK</code><span><a class="mark" href="#all_deprecations_dep0176-fsf_ok-fsr_ok-fsw_ok-fsx_ok" id="all_deprecations_dep0176-fsf_ok-fsr_ok-fsw_ok-fsx_ok">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0176_fs_f_ok_fs_r_ok_fs_w_ok_fs_x_ok"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.8.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p><code>F_OK</code>, <code>R_OK</code>, <code>W_OK</code> and <code>X_OK</code> getters exposed directly on <code>node:fs</code> are
deprecated. Get them from <code>fs.constants</code> or <code>fs.promises.constants</code> instead.</p>
<h4 id="DEP0177">DEP0177: <code>util.types.isWebAssemblyCompiledModule</code><span><a class="mark" href="#all_deprecations_dep0177-utiltypesiswebassemblycompiledmodule" id="all_deprecations_dep0177-utiltypesiswebassemblycompiledmodule">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0177_util_types_iswebassemblycompiledmodule"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.12.0</td>
<td><p>End-of-Life.</p></td></tr>
<tr><td>v20.11.0</td>
<td><p>A deprecation code has been assigned.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: End-of-Life</p>
<p>The <code>util.types.isWebAssemblyCompiledModule</code> API has been removed.
Please use <code>value instanceof WebAssembly.Module</code> instead.</p>
<h4 id="DEP0178">DEP0178: <code>dirent.path</code><span><a class="mark" href="#all_deprecations_dep0178-direntpath" id="all_deprecations_dep0178-direntpath">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0178_dirent_path"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.12.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>The <a href="#all_fs_direntpath"><code>dirent.path</code></a> is deprecated due to its lack of consistency across
release lines. Please use <a href="#all_fs_direntparentpath"><code>dirent.parentPath</code></a> instead.</p>
<h4 id="DEP0179">DEP0179: <code>Hash</code> constructor<span><a class="mark" href="#all_deprecations_dep0179-hash-constructor" id="all_deprecations_dep0179-hash-constructor">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0179_hash_constructor"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.12.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>Calling <code>Hash</code> class directly with <code>Hash()</code> or <code>new Hash()</code> is
deprecated due to being internals, not intended for public use.
Please use the <a href="#all_crypto_cryptocreatehashalgorithm-options"><code>crypto.createHash()</code></a> method to create Hash instances.</p>
<h4 id="DEP0180">DEP0180: <code>fs.Stats</code> constructor<span><a class="mark" href="#all_deprecations_dep0180-fsstats-constructor" id="all_deprecations_dep0180-fsstats-constructor">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0180_fs_stats_constructor"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.13.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>Calling <code>fs.Stats</code> class directly with <code>Stats()</code> or <code>new Stats()</code> is
deprecated due to being internals, not intended for public use.</p>
<h4 id="DEP0181">DEP0181: <code>Hmac</code> constructor<span><a class="mark" href="#all_deprecations_dep0181-hmac-constructor" id="all_deprecations_dep0181-hmac-constructor">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0181_hmac_constructor"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.13.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>Calling <code>Hmac</code> class directly with <code>Hmac()</code> or <code>new Hmac()</code> is
deprecated due to being internals, not intended for public use.
Please use the <a href="#all_crypto_cryptocreatehmacalgorithm-key-options"><code>crypto.createHmac()</code></a> method to create Hmac instances.</p>
<h4 id="DEP0182">DEP0182: Short GCM authentication tags without explicit <code>authTagLength</code><span><a class="mark" href="#all_deprecations_dep0182-short-gcm-authentication-tags-without-explicit-authtaglength" id="all_deprecations_dep0182-short-gcm-authentication-tags-without-explicit-authtaglength">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0182_short_gcm_authentication_tags_without_explicit_authtaglength"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.13.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only (supports <a href="#all_cli_--pending-deprecation"><code>--pending-deprecation</code></a>)</p>
<p>Applications that intend to use authentication tags that are shorter than the
default authentication tag length should set the <code>authTagLength</code> option of the
<a href="#all_crypto_cryptocreatedecipherivalgorithm-key-iv-options"><code>crypto.createDecipheriv()</code></a> function to the appropriate length.</p>
<p>For ciphers in GCM mode, the <a href="#all_crypto_deciphersetauthtagbuffer-encoding"><code>decipher.setAuthTag()</code></a> function accepts
authentication tags of any valid length (see <a href="#DEP0090">DEP0090</a>). This behavior
is deprecated to better align with recommendations per <a href="https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf">NIST SP 800-38D</a>.</p>
<h4 id="DEP0183">DEP0183: OpenSSL engine-based APIs<span><a class="mark" href="#all_deprecations_dep0183-openssl-engine-based-apis" id="all_deprecations_dep0183-openssl-engine-based-apis">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0183_openssl_engine_based_apis"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.16.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>OpenSSL 3 has deprecated support for custom engines with a recommendation to
switch to its new provider model. The <code>clientCertEngine</code> option for
<code>https.request()</code>, <a href="#all_tls_tlscreatesecurecontextoptions"><code>tls.createSecureContext()</code></a>, and <a href="#all_tls_tlscreateserveroptions-secureconnectionlistener"><code>tls.createServer()</code></a>;
the <code>privateKeyEngine</code> and <code>privateKeyIdentifier</code> for <a href="#all_tls_tlscreatesecurecontextoptions"><code>tls.createSecureContext()</code></a>;
and <a href="#all_crypto_cryptosetengineengine-flags"><code>crypto.setEngine()</code></a> all depend on this functionality from OpenSSL.</p>
<h4 id="DEP0184">DEP0184: Instantiating <code>node:zlib</code> classes without <code>new</code><span><a class="mark" href="#all_deprecations_dep0184-instantiating-nodezlib-classes-without-new" id="all_deprecations_dep0184-instantiating-nodezlib-classes-without-new">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0184_instantiating_node_zlib_classes_without_new"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.18.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>Instantiating classes without the <code>new</code> qualifier exported by the <code>node:zlib</code> module is deprecated.
It is recommended to use the <code>new</code> qualifier instead. This applies to all Zlib classes, such as <code>Deflate</code>,
<code>DeflateRaw</code>, <code>Gunzip</code>, <code>Inflate</code>, <code>InflateRaw</code>, <code>Unzip</code>, and <code>Zlib</code>.</p>
<h4 id="DEP0185">DEP0185: Instantiating <code>node:repl</code> classes without <code>new</code><span><a class="mark" href="#all_deprecations_dep0185-instantiating-noderepl-classes-without-new" id="all_deprecations_dep0185-instantiating-noderepl-classes-without-new">#</a></span><a aria-hidden="true" class="legacy" id="deprecations_dep0185_instantiating_node_repl_classes_without_new"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.18.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Type: Documentation-only</p>
<p>Instantiating classes without the <code>new</code> qualifier exported by the <code>node:repl</code> module is deprecated.
It is recommended to use the <code>new</code> qualifier instead. This applies to all REPL classes, including
<code>REPLServer</code> and <code>Recoverable</code>.</p></section>
        </section>
<section><h2>Diagnostics Channel<span><a class="mark" href="#all_diagnostics_channel_diagnostics-channel" id="all_diagnostics_channel_diagnostics-channel">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_diagnostics_channel"></a></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.2.0, v18.13.0</td>
<td><p>diagnostics_channel is now Stable.</p></td></tr>
<tr><td>v15.1.0, v14.17.0</td>
<td><p><span>Added in: v15.1.0, v14.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>

<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/diagnostics_channel.js">lib/diagnostics_channel.js</a></p>
<p>The <code>node:diagnostics_channel</code> module provides an API to create named channels
to report arbitrary message data for diagnostics purposes.</p>
<p>It can be accessed using:</p>

<pre class="with-64-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);</code><button class="copy-button">copy</button></pre>
<p>It is intended that a module writer wanting to report diagnostics messages
will create one or many top-level channels to report messages through.
Channels may also be acquired at runtime but it is not encouraged
due to the additional overhead of doing so. Channels may be exported for
convenience, but as long as the name is known it can be acquired anywhere.</p>
<p>If you intend for your module to produce diagnostics data for others to
consume it is recommended that you include documentation of what named
channels are used along with the shape of the message data. Channel names
should generally include the module name to avoid collisions with data from
other modules.</p>
<section><h3>Public API<span><a class="mark" href="#all_diagnostics_channel_public-api" id="all_diagnostics_channel_public-api">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_public_api"></a></h3>
<h4>Overview<span><a class="mark" href="#all_diagnostics_channel_overview" id="all_diagnostics_channel_overview">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_overview"></a></h4>
<p>Following is a simple overview of the public API.</p>

<pre class="with-64-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;

<span class="hljs-comment">// Get a reusable channel object</span>
<span class="hljs-keyword">const</span> channel = diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'my-channel'</span>);

<span class="hljs-keyword">function</span> <span class="hljs-title function_">onMessage</span>(<span class="hljs-params">message, name</span>) {
  <span class="hljs-comment">// Received data</span>
}

<span class="hljs-comment">// Subscribe to the channel</span>
diagnostics_channel.<span class="hljs-title function_">subscribe</span>(<span class="hljs-string">'my-channel'</span>, onMessage);

<span class="hljs-comment">// Check if the channel has an active subscriber</span>
<span class="hljs-keyword">if</span> (channel.<span class="hljs-property">hasSubscribers</span>) {
  <span class="hljs-comment">// Publish data to the channel</span>
  channel.<span class="hljs-title function_">publish</span>({
    <span class="hljs-attr">some</span>: <span class="hljs-string">'data'</span>,
  });
}

<span class="hljs-comment">// Unsubscribe from the channel</span>
diagnostics_channel.<span class="hljs-title function_">unsubscribe</span>(<span class="hljs-string">'my-channel'</span>, onMessage);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);

<span class="hljs-comment">// Get a reusable channel object</span>
<span class="hljs-keyword">const</span> channel = diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'my-channel'</span>);

<span class="hljs-keyword">function</span> <span class="hljs-title function_">onMessage</span>(<span class="hljs-params">message, name</span>) {
  <span class="hljs-comment">// Received data</span>
}

<span class="hljs-comment">// Subscribe to the channel</span>
diagnostics_channel.<span class="hljs-title function_">subscribe</span>(<span class="hljs-string">'my-channel'</span>, onMessage);

<span class="hljs-comment">// Check if the channel has an active subscriber</span>
<span class="hljs-keyword">if</span> (channel.<span class="hljs-property">hasSubscribers</span>) {
  <span class="hljs-comment">// Publish data to the channel</span>
  channel.<span class="hljs-title function_">publish</span>({
    <span class="hljs-attr">some</span>: <span class="hljs-string">'data'</span>,
  });
}

<span class="hljs-comment">// Unsubscribe from the channel</span>
diagnostics_channel.<span class="hljs-title function_">unsubscribe</span>(<span class="hljs-string">'my-channel'</span>, onMessage);</code><button class="copy-button">copy</button></pre>
<h5><code>diagnostics_channel.hasSubscribers(name)</code><span><a class="mark" href="#all_diagnostics_channel_diagnostics_channelhassubscribersname" id="all_diagnostics_channel_diagnostics_channelhassubscribersname">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_diagnostics_channel_hassubscribers_name"></a></h5>
<div class="api_metadata">
<span>Added in: v15.1.0, v14.17.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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type">&#x3C;symbol></a> The channel name</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If there are active subscribers</li>
</ul>
<p>Check if there are active subscribers to the named channel. This is helpful if
the message you want to send might be expensive to prepare.</p>
<p>This API is optional but helpful when trying to publish messages from very
performance-sensitive code.</p>

<pre class="with-64-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;

<span class="hljs-keyword">if</span> (diagnostics_channel.<span class="hljs-title function_">hasSubscribers</span>(<span class="hljs-string">'my-channel'</span>)) {
  <span class="hljs-comment">// There are subscribers, prepare and publish message</span>
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);

<span class="hljs-keyword">if</span> (diagnostics_channel.<span class="hljs-title function_">hasSubscribers</span>(<span class="hljs-string">'my-channel'</span>)) {
  <span class="hljs-comment">// There are subscribers, prepare and publish message</span>
}</code><button class="copy-button">copy</button></pre>
<h5><code>diagnostics_channel.channel(name)</code><span><a class="mark" href="#all_diagnostics_channel_diagnostics_channelchannelname" id="all_diagnostics_channel_diagnostics_channelchannelname">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_diagnostics_channel_channel_name"></a></h5>
<div class="api_metadata">
<span>Added in: v15.1.0, v14.17.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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type">&#x3C;symbol></a> The channel name</li>
<li>Returns: <a href="#all_diagnostics_channel_class-channel" class="type">&#x3C;Channel></a> The named channel object</li>
</ul>
<p>This is the primary entry-point for anyone wanting to publish to a named
channel. It produces a channel object which is optimized to reduce overhead at
publish time as much as possible.</p>

<pre class="with-64-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;

<span class="hljs-keyword">const</span> channel = diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'my-channel'</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);

<span class="hljs-keyword">const</span> channel = diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'my-channel'</span>);</code><button class="copy-button">copy</button></pre>
<h5><code>diagnostics_channel.subscribe(name, onMessage)</code><span><a class="mark" href="#all_diagnostics_channel_diagnostics_channelsubscribename-onmessage" id="all_diagnostics_channel_diagnostics_channelsubscribename-onmessage">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_diagnostics_channel_subscribe_name_onmessage"></a></h5>
<div class="api_metadata">
<span>Added in: v18.7.0, v16.17.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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type">&#x3C;symbol></a> The channel name</li>
<li><code>onMessage</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The handler to receive channel messages
<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> The message data</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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type">&#x3C;symbol></a> The name of the channel</li>
</ul>
</li>
</ul>
<p>Register a message handler to subscribe to this channel. This message handler
will be run synchronously whenever a message is published to the channel. Any
errors thrown in the message handler will trigger an <a href="#all_process_event-uncaughtexception"><code>'uncaughtException'</code></a>.</p>

<pre class="with-64-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;

diagnostics_channel.<span class="hljs-title function_">subscribe</span>(<span class="hljs-string">'my-channel'</span>, <span class="hljs-function">(<span class="hljs-params">message, name</span>) =></span> {
  <span class="hljs-comment">// Received data</span>
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);

diagnostics_channel.<span class="hljs-title function_">subscribe</span>(<span class="hljs-string">'my-channel'</span>, <span class="hljs-function">(<span class="hljs-params">message, name</span>) =></span> {
  <span class="hljs-comment">// Received data</span>
});</code><button class="copy-button">copy</button></pre>
<h5><code>diagnostics_channel.unsubscribe(name, onMessage)</code><span><a class="mark" href="#all_diagnostics_channel_diagnostics_channelunsubscribename-onmessage" id="all_diagnostics_channel_diagnostics_channelunsubscribename-onmessage">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_diagnostics_channel_unsubscribe_name_onmessage"></a></h5>
<div class="api_metadata">
<span>Added in: v18.7.0, v16.17.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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type">&#x3C;symbol></a> The channel name</li>
<li><code>onMessage</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The previous subscribed handler to remove</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 handler was found, <code>false</code> otherwise.</li>
</ul>
<p>Remove a message handler previously registered to this channel with
<a href="#all_diagnostics_channel_diagnostics_channelsubscribename-onmessage"><code>diagnostics_channel.subscribe(name, onMessage)</code></a>.</p>

<pre class="with-64-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;

<span class="hljs-keyword">function</span> <span class="hljs-title function_">onMessage</span>(<span class="hljs-params">message, name</span>) {
  <span class="hljs-comment">// Received data</span>
}

diagnostics_channel.<span class="hljs-title function_">subscribe</span>(<span class="hljs-string">'my-channel'</span>, onMessage);

diagnostics_channel.<span class="hljs-title function_">unsubscribe</span>(<span class="hljs-string">'my-channel'</span>, onMessage);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);

<span class="hljs-keyword">function</span> <span class="hljs-title function_">onMessage</span>(<span class="hljs-params">message, name</span>) {
  <span class="hljs-comment">// Received data</span>
}

diagnostics_channel.<span class="hljs-title function_">subscribe</span>(<span class="hljs-string">'my-channel'</span>, onMessage);

diagnostics_channel.<span class="hljs-title function_">unsubscribe</span>(<span class="hljs-string">'my-channel'</span>, onMessage);</code><button class="copy-button">copy</button></pre>
<h5><code>diagnostics_channel.tracingChannel(nameOrChannels)</code><span><a class="mark" href="#all_diagnostics_channel_diagnostics_channeltracingchannelnameorchannels" id="all_diagnostics_channel_diagnostics_channeltracingchannelnameorchannels">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_diagnostics_channel_tracingchannel_nameorchannels"></a></h5>
<div class="api_metadata">
<span>Added in: v19.9.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>nameOrChannels</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#all_diagnostics_channel_class-tracingchannel" class="type">&#x3C;TracingChannel></a> Channel name or
object containing all the <a href="#all_diagnostics_channel_tracingchannel-channels">TracingChannel Channels</a></li>
<li>Returns: <a href="#all_diagnostics_channel_class-tracingchannel" class="type">&#x3C;TracingChannel></a> Collection of channels to trace with</li>
</ul>
<p>Creates a <a href="#all_diagnostics_channel_class-tracingchannel"><code>TracingChannel</code></a> wrapper for the given
<a href="#all_diagnostics_channel_tracingchannel-channels">TracingChannel Channels</a>. If a name is given, the corresponding tracing
channels will be created in the form of <code>tracing:${name}:${eventType}</code> where
<code>eventType</code> corresponds to the types of <a href="#all_diagnostics_channel_tracingchannel-channels">TracingChannel Channels</a>.</p>

<pre class="with-64-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;

<span class="hljs-keyword">const</span> channelsByName = diagnostics_channel.<span class="hljs-title function_">tracingChannel</span>(<span class="hljs-string">'my-channel'</span>);

<span class="hljs-comment">// or...</span>

<span class="hljs-keyword">const</span> channelsByCollection = diagnostics_channel.<span class="hljs-title function_">tracingChannel</span>({
  <span class="hljs-attr">start</span>: diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'tracing:my-channel:start'</span>),
  <span class="hljs-attr">end</span>: diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'tracing:my-channel:end'</span>),
  <span class="hljs-attr">asyncStart</span>: diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'tracing:my-channel:asyncStart'</span>),
  <span class="hljs-attr">asyncEnd</span>: diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'tracing:my-channel:asyncEnd'</span>),
  <span class="hljs-attr">error</span>: diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'tracing:my-channel:error'</span>),
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);

<span class="hljs-keyword">const</span> channelsByName = diagnostics_channel.<span class="hljs-title function_">tracingChannel</span>(<span class="hljs-string">'my-channel'</span>);

<span class="hljs-comment">// or...</span>

<span class="hljs-keyword">const</span> channelsByCollection = diagnostics_channel.<span class="hljs-title function_">tracingChannel</span>({
  <span class="hljs-attr">start</span>: diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'tracing:my-channel:start'</span>),
  <span class="hljs-attr">end</span>: diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'tracing:my-channel:end'</span>),
  <span class="hljs-attr">asyncStart</span>: diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'tracing:my-channel:asyncStart'</span>),
  <span class="hljs-attr">asyncEnd</span>: diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'tracing:my-channel:asyncEnd'</span>),
  <span class="hljs-attr">error</span>: diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'tracing:my-channel:error'</span>),
});</code><button class="copy-button">copy</button></pre>
<h4>Class: <code>Channel</code><span><a class="mark" href="#all_diagnostics_channel_class-channel" id="all_diagnostics_channel_class-channel">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_class_channel"></a></h4>
<div class="api_metadata">
<span>Added in: v15.1.0, v14.17.0</span>
</div>
<p>The class <code>Channel</code> represents an individual named channel within the data
pipeline. It is used to track subscribers and to publish messages when there
are subscribers present. It exists as a separate object to avoid channel
lookups at publish time, enabling very fast publish speeds and allowing
for heavy use while incurring very minimal cost. Channels are created with
<a href="#all_diagnostics_channel_diagnostics_channelchannelname"><code>diagnostics_channel.channel(name)</code></a>, constructing a channel directly
with <code>new Channel(name)</code> is not supported.</p>
<h5><code>channel.hasSubscribers</code><span><a class="mark" href="#all_diagnostics_channel_channelhassubscribers" id="all_diagnostics_channel_channelhassubscribers">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_channel_hassubscribers"></a></h5>
<div class="api_metadata">
<span>Added in: v15.1.0, v14.17.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> If there are active subscribers</li>
</ul>
<p>Check if there are active subscribers to this channel. This is helpful if
the message you want to send might be expensive to prepare.</p>
<p>This API is optional but helpful when trying to publish messages from very
performance-sensitive code.</p>

<pre class="with-64-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;

<span class="hljs-keyword">const</span> channel = diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'my-channel'</span>);

<span class="hljs-keyword">if</span> (channel.<span class="hljs-property">hasSubscribers</span>) {
  <span class="hljs-comment">// There are subscribers, prepare and publish message</span>
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);

<span class="hljs-keyword">const</span> channel = diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'my-channel'</span>);

<span class="hljs-keyword">if</span> (channel.<span class="hljs-property">hasSubscribers</span>) {
  <span class="hljs-comment">// There are subscribers, prepare and publish message</span>
}</code><button class="copy-button">copy</button></pre>
<h5><code>channel.publish(message)</code><span><a class="mark" href="#all_diagnostics_channel_channelpublishmessage" id="all_diagnostics_channel_channelpublishmessage">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_channel_publish_message"></a></h5>
<div class="api_metadata">
<span>Added in: v15.1.0, v14.17.0</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> The message to send to the channel subscribers</li>
</ul>
<p>Publish a message to any subscribers to the channel. This will trigger
message handlers synchronously so they will execute within the same context.</p>

<pre class="with-64-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;

<span class="hljs-keyword">const</span> channel = diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'my-channel'</span>);

channel.<span class="hljs-title function_">publish</span>({
  <span class="hljs-attr">some</span>: <span class="hljs-string">'message'</span>,
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);

<span class="hljs-keyword">const</span> channel = diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'my-channel'</span>);

channel.<span class="hljs-title function_">publish</span>({
  <span class="hljs-attr">some</span>: <span class="hljs-string">'message'</span>,
});</code><button class="copy-button">copy</button></pre>
<h5><code>channel.subscribe(onMessage)</code><span><a class="mark" href="#all_diagnostics_channel_channelsubscribeonmessage" id="all_diagnostics_channel_channelsubscribeonmessage">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_channel_subscribe_onmessage"></a></h5>
<div class="api_metadata">
<span>Added in: v15.1.0, v14.17.0</span><span>Deprecated since: v18.7.0, v16.17.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_diagnostics_channel_diagnostics_channelsubscribename-onmessage"><code>diagnostics_channel.subscribe(name, onMessage)</code></a></div><p></p>
<ul>
<li><code>onMessage</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The handler to receive channel messages
<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> The message data</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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type">&#x3C;symbol></a> The name of the channel</li>
</ul>
</li>
</ul>
<p>Register a message handler to subscribe to this channel. This message handler
will be run synchronously whenever a message is published to the channel. Any
errors thrown in the message handler will trigger an <a href="#all_process_event-uncaughtexception"><code>'uncaughtException'</code></a>.</p>

<pre class="with-64-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;

<span class="hljs-keyword">const</span> channel = diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'my-channel'</span>);

channel.<span class="hljs-title function_">subscribe</span>(<span class="hljs-function">(<span class="hljs-params">message, name</span>) =></span> {
  <span class="hljs-comment">// Received data</span>
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);

<span class="hljs-keyword">const</span> channel = diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'my-channel'</span>);

channel.<span class="hljs-title function_">subscribe</span>(<span class="hljs-function">(<span class="hljs-params">message, name</span>) =></span> {
  <span class="hljs-comment">// Received data</span>
});</code><button class="copy-button">copy</button></pre>
<h5><code>channel.unsubscribe(onMessage)</code><span><a class="mark" href="#all_diagnostics_channel_channelunsubscribeonmessage" id="all_diagnostics_channel_channelunsubscribeonmessage">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_channel_unsubscribe_onmessage"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.7.0, v16.17.0</td>
<td><p><span>Deprecated since: v18.7.0, v16.17.0</span></p></td></tr>
<tr><td>v17.1.0, v16.14.0, v14.19.0</td>
<td><p>Added return value. Added to channels without subscribers.</p></td></tr>
<tr><td>v15.1.0, v14.17.0</td>
<td><p><span>Added in: v15.1.0, v14.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_diagnostics_channel_diagnostics_channelunsubscribename-onmessage"><code>diagnostics_channel.unsubscribe(name, onMessage)</code></a></div><p></p>
<ul>
<li><code>onMessage</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The previous subscribed handler to remove</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 handler was found, <code>false</code> otherwise.</li>
</ul>
<p>Remove a message handler previously registered to this channel with
<a href="#all_diagnostics_channel_channelsubscribeonmessage"><code>channel.subscribe(onMessage)</code></a>.</p>

<pre class="with-64-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;

<span class="hljs-keyword">const</span> channel = diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'my-channel'</span>);

<span class="hljs-keyword">function</span> <span class="hljs-title function_">onMessage</span>(<span class="hljs-params">message, name</span>) {
  <span class="hljs-comment">// Received data</span>
}

channel.<span class="hljs-title function_">subscribe</span>(onMessage);

channel.<span class="hljs-title function_">unsubscribe</span>(onMessage);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);

<span class="hljs-keyword">const</span> channel = diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'my-channel'</span>);

<span class="hljs-keyword">function</span> <span class="hljs-title function_">onMessage</span>(<span class="hljs-params">message, name</span>) {
  <span class="hljs-comment">// Received data</span>
}

channel.<span class="hljs-title function_">subscribe</span>(onMessage);

channel.<span class="hljs-title function_">unsubscribe</span>(onMessage);</code><button class="copy-button">copy</button></pre>
<h5><code>channel.bindStore(store[, transform])</code><span><a class="mark" href="#all_diagnostics_channel_channelbindstorestore-transform" id="all_diagnostics_channel_channelbindstorestore-transform">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_channel_bindstore_store_transform"></a></h5>
<div class="api_metadata">
<span>Added in: v19.9.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>store</code> <a href="#all_async_context_class-asynclocalstorage" class="type">&#x3C;AsyncLocalStorage></a> The store to which to bind the context data</li>
<li><code>transform</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Transform context data before setting the store context</li>
</ul>
<p>When <a href="#all_diagnostics_channel_channelrunstorescontext-fn-thisarg-args"><code>channel.runStores(context, ...)</code></a> is called, the given context data
will be applied to any store bound to the channel. If the store has already been
bound the previous <code>transform</code> function will be replaced with the new one.
The <code>transform</code> function may be omitted to set the given context data as the
context directly.</p>

<pre class="with-64-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">AsyncLocalStorage</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;

<span class="hljs-keyword">const</span> store = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AsyncLocalStorage</span>();

<span class="hljs-keyword">const</span> channel = diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'my-channel'</span>);

channel.<span class="hljs-title function_">bindStore</span>(store, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
  <span class="hljs-keyword">return</span> { data };
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">AsyncLocalStorage</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);

<span class="hljs-keyword">const</span> store = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AsyncLocalStorage</span>();

<span class="hljs-keyword">const</span> channel = diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'my-channel'</span>);

channel.<span class="hljs-title function_">bindStore</span>(store, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
  <span class="hljs-keyword">return</span> { data };
});</code><button class="copy-button">copy</button></pre>
<h5><code>channel.unbindStore(store)</code><span><a class="mark" href="#all_diagnostics_channel_channelunbindstorestore" id="all_diagnostics_channel_channelunbindstorestore">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_channel_unbindstore_store"></a></h5>
<div class="api_metadata">
<span>Added in: v19.9.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>store</code> <a href="#all_async_context_class-asynclocalstorage" class="type">&#x3C;AsyncLocalStorage></a> The store to unbind from the channel.</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 store was found, <code>false</code> otherwise.</li>
</ul>
<p>Remove a message handler previously registered to this channel with
<a href="#all_diagnostics_channel_channelbindstorestore-transform"><code>channel.bindStore(store)</code></a>.</p>

<pre class="with-64-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">AsyncLocalStorage</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;

<span class="hljs-keyword">const</span> store = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AsyncLocalStorage</span>();

<span class="hljs-keyword">const</span> channel = diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'my-channel'</span>);

channel.<span class="hljs-title function_">bindStore</span>(store);
channel.<span class="hljs-title function_">unbindStore</span>(store);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">AsyncLocalStorage</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);

<span class="hljs-keyword">const</span> store = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AsyncLocalStorage</span>();

<span class="hljs-keyword">const</span> channel = diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'my-channel'</span>);

channel.<span class="hljs-title function_">bindStore</span>(store);
channel.<span class="hljs-title function_">unbindStore</span>(store);</code><button class="copy-button">copy</button></pre>
<h5><code>channel.runStores(context, fn[, thisArg[, ...args]])</code><span><a class="mark" href="#all_diagnostics_channel_channelrunstorescontext-fn-thisarg-args" id="all_diagnostics_channel_channelrunstorescontext-fn-thisarg-args">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_channel_runstores_context_fn_thisarg_args"></a></h5>
<div class="api_metadata">
<span>Added in: v19.9.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>context</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> Message to send to subscribers and bind to stores</li>
<li><code>fn</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Handler to run within the entered storage context</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>Applies the given data to any AsyncLocalStorage instances bound to the channel
for the duration of the given function, then publishes to the channel within
the scope of that data is applied to the stores.</p>
<p>If a transform function was given to <a href="#all_diagnostics_channel_channelbindstorestore-transform"><code>channel.bindStore(store)</code></a> it will be
applied to transform the message data before it becomes the context value for
the store. The prior storage context is accessible from within the transform
function in cases where context linking is required.</p>
<p>The context applied to the store should be accessible in any async code which
continues from execution which began during the given function, however
there are some situations in which <a href="#all_async_context_troubleshooting-context-loss">context loss</a> may occur.</p>

<pre class="with-64-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">AsyncLocalStorage</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;

<span class="hljs-keyword">const</span> store = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AsyncLocalStorage</span>();

<span class="hljs-keyword">const</span> channel = diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'my-channel'</span>);

channel.<span class="hljs-title function_">bindStore</span>(store, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> {
  <span class="hljs-keyword">const</span> parent = store.<span class="hljs-title function_">getStore</span>();
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Span</span>(message, parent);
});
channel.<span class="hljs-title function_">runStores</span>({ <span class="hljs-attr">some</span>: <span class="hljs-string">'message'</span> }, <span class="hljs-function">() =></span> {
  store.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Span({ some: 'message' })</span>
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">AsyncLocalStorage</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);

<span class="hljs-keyword">const</span> store = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AsyncLocalStorage</span>();

<span class="hljs-keyword">const</span> channel = diagnostics_channel.<span class="hljs-title function_">channel</span>(<span class="hljs-string">'my-channel'</span>);

channel.<span class="hljs-title function_">bindStore</span>(store, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> {
  <span class="hljs-keyword">const</span> parent = store.<span class="hljs-title function_">getStore</span>();
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Span</span>(message, parent);
});
channel.<span class="hljs-title function_">runStores</span>({ <span class="hljs-attr">some</span>: <span class="hljs-string">'message'</span> }, <span class="hljs-function">() =></span> {
  store.<span class="hljs-title function_">getStore</span>(); <span class="hljs-comment">// Span({ some: 'message' })</span>
});</code><button class="copy-button">copy</button></pre>
<h4>Class: <code>TracingChannel</code><span><a class="mark" href="#all_diagnostics_channel_class-tracingchannel" id="all_diagnostics_channel_class-tracingchannel">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_class_tracingchannel"></a></h4>
<div class="api_metadata">
<span>Added in: v19.9.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>The class <code>TracingChannel</code> is a collection of <a href="#all_diagnostics_channel_tracingchannel-channels">TracingChannel Channels</a> which
together express a single traceable action. It is used to formalize and
simplify the process of producing events for tracing application flow.
<a href="#all_diagnostics_channel_diagnostics_channeltracingchannelnameorchannels"><code>diagnostics_channel.tracingChannel()</code></a> is used to construct a
<code>TracingChannel</code>. As with <code>Channel</code> it is recommended to create and reuse a
single <code>TracingChannel</code> at the top-level of the file rather than creating them
dynamically.</p>
<h5><code>tracingChannel.subscribe(subscribers)</code><span><a class="mark" href="#all_diagnostics_channel_tracingchannelsubscribesubscribers" id="all_diagnostics_channel_tracingchannelsubscribesubscribers">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_tracingchannel_subscribe_subscribers"></a></h5>
<div class="api_metadata">
<span>Added in: v19.9.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>subscribers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Set of <a href="#all_diagnostics_channel_tracingchannel-channels">TracingChannel Channels</a> subscribers
<ul>
<li><code>start</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The <a href="#all_diagnostics_channel_startevent"><code>start</code> event</a> subscriber</li>
<li><code>end</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The <a href="#all_diagnostics_channel_endevent"><code>end</code> event</a> subscriber</li>
<li><code>asyncStart</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The <a href="#all_diagnostics_channel_asyncstartevent"><code>asyncStart</code> event</a> subscriber</li>
<li><code>asyncEnd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The <a href="#all_diagnostics_channel_asyncendevent"><code>asyncEnd</code> event</a> subscriber</li>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The <a href="#all_diagnostics_channel_errorevent"><code>error</code> event</a> subscriber</li>
</ul>
</li>
</ul>
<p>Helper to subscribe a collection of functions to the corresponding channels.
This is the same as calling <a href="#all_diagnostics_channel_channelsubscribeonmessage"><code>channel.subscribe(onMessage)</code></a> on each channel
individually.</p>

<pre class="with-64-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;

<span class="hljs-keyword">const</span> channels = diagnostics_channel.<span class="hljs-title function_">tracingChannel</span>(<span class="hljs-string">'my-channel'</span>);

channels.<span class="hljs-title function_">subscribe</span>({
  <span class="hljs-title function_">start</span>(<span class="hljs-params">message</span>) {
    <span class="hljs-comment">// Handle start message</span>
  },
  <span class="hljs-title function_">end</span>(<span class="hljs-params">message</span>) {
    <span class="hljs-comment">// Handle end message</span>
  },
  <span class="hljs-title function_">asyncStart</span>(<span class="hljs-params">message</span>) {
    <span class="hljs-comment">// Handle asyncStart message</span>
  },
  <span class="hljs-title function_">asyncEnd</span>(<span class="hljs-params">message</span>) {
    <span class="hljs-comment">// Handle asyncEnd message</span>
  },
  <span class="hljs-title function_">error</span>(<span class="hljs-params">message</span>) {
    <span class="hljs-comment">// Handle error message</span>
  },
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);

<span class="hljs-keyword">const</span> channels = diagnostics_channel.<span class="hljs-title function_">tracingChannel</span>(<span class="hljs-string">'my-channel'</span>);

channels.<span class="hljs-title function_">subscribe</span>({
  <span class="hljs-title function_">start</span>(<span class="hljs-params">message</span>) {
    <span class="hljs-comment">// Handle start message</span>
  },
  <span class="hljs-title function_">end</span>(<span class="hljs-params">message</span>) {
    <span class="hljs-comment">// Handle end message</span>
  },
  <span class="hljs-title function_">asyncStart</span>(<span class="hljs-params">message</span>) {
    <span class="hljs-comment">// Handle asyncStart message</span>
  },
  <span class="hljs-title function_">asyncEnd</span>(<span class="hljs-params">message</span>) {
    <span class="hljs-comment">// Handle asyncEnd message</span>
  },
  <span class="hljs-title function_">error</span>(<span class="hljs-params">message</span>) {
    <span class="hljs-comment">// Handle error message</span>
  },
});</code><button class="copy-button">copy</button></pre>
<h5><code>tracingChannel.unsubscribe(subscribers)</code><span><a class="mark" href="#all_diagnostics_channel_tracingchannelunsubscribesubscribers" id="all_diagnostics_channel_tracingchannelunsubscribesubscribers">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_tracingchannel_unsubscribe_subscribers"></a></h5>
<div class="api_metadata">
<span>Added in: v19.9.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>subscribers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Set of <a href="#all_diagnostics_channel_tracingchannel-channels">TracingChannel Channels</a> subscribers
<ul>
<li><code>start</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The <a href="#all_diagnostics_channel_startevent"><code>start</code> event</a> subscriber</li>
<li><code>end</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The <a href="#all_diagnostics_channel_endevent"><code>end</code> event</a> subscriber</li>
<li><code>asyncStart</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The <a href="#all_diagnostics_channel_asyncstartevent"><code>asyncStart</code> event</a> subscriber</li>
<li><code>asyncEnd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The <a href="#all_diagnostics_channel_asyncendevent"><code>asyncEnd</code> event</a> subscriber</li>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The <a href="#all_diagnostics_channel_errorevent"><code>error</code> event</a> subscriber</li>
</ul>
</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 all handlers were successfully unsubscribed,
and <code>false</code> otherwise.</li>
</ul>
<p>Helper to unsubscribe a collection of functions from the corresponding channels.
This is the same as calling <a href="#all_diagnostics_channel_channelunsubscribeonmessage"><code>channel.unsubscribe(onMessage)</code></a> on each channel
individually.</p>

<pre class="with-64-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;

<span class="hljs-keyword">const</span> channels = diagnostics_channel.<span class="hljs-title function_">tracingChannel</span>(<span class="hljs-string">'my-channel'</span>);

channels.<span class="hljs-title function_">unsubscribe</span>({
  <span class="hljs-title function_">start</span>(<span class="hljs-params">message</span>) {
    <span class="hljs-comment">// Handle start message</span>
  },
  <span class="hljs-title function_">end</span>(<span class="hljs-params">message</span>) {
    <span class="hljs-comment">// Handle end message</span>
  },
  <span class="hljs-title function_">asyncStart</span>(<span class="hljs-params">message</span>) {
    <span class="hljs-comment">// Handle asyncStart message</span>
  },
  <span class="hljs-title function_">asyncEnd</span>(<span class="hljs-params">message</span>) {
    <span class="hljs-comment">// Handle asyncEnd message</span>
  },
  <span class="hljs-title function_">error</span>(<span class="hljs-params">message</span>) {
    <span class="hljs-comment">// Handle error message</span>
  },
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);

<span class="hljs-keyword">const</span> channels = diagnostics_channel.<span class="hljs-title function_">tracingChannel</span>(<span class="hljs-string">'my-channel'</span>);

channels.<span class="hljs-title function_">unsubscribe</span>({
  <span class="hljs-title function_">start</span>(<span class="hljs-params">message</span>) {
    <span class="hljs-comment">// Handle start message</span>
  },
  <span class="hljs-title function_">end</span>(<span class="hljs-params">message</span>) {
    <span class="hljs-comment">// Handle end message</span>
  },
  <span class="hljs-title function_">asyncStart</span>(<span class="hljs-params">message</span>) {
    <span class="hljs-comment">// Handle asyncStart message</span>
  },
  <span class="hljs-title function_">asyncEnd</span>(<span class="hljs-params">message</span>) {
    <span class="hljs-comment">// Handle asyncEnd message</span>
  },
  <span class="hljs-title function_">error</span>(<span class="hljs-params">message</span>) {
    <span class="hljs-comment">// Handle error message</span>
  },
});</code><button class="copy-button">copy</button></pre>
<h5><code>tracingChannel.traceSync(fn[, context[, thisArg[, ...args]]])</code><span><a class="mark" href="#all_diagnostics_channel_tracingchanneltracesyncfn-context-thisarg-args" id="all_diagnostics_channel_tracingchanneltracesyncfn-context-thisarg-args">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_tracingchannel_tracesync_fn_context_thisarg_args"></a></h5>
<div class="api_metadata">
<span>Added in: v19.9.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<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> Function to wrap a trace around</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> Shared object to correlate events through</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>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> The return value of the given function</li>
</ul>
<p>Trace a synchronous function call. This will always produce a <a href="#all_diagnostics_channel_startevent"><code>start</code> event</a>
and <a href="#all_diagnostics_channel_endevent"><code>end</code> event</a> around the execution and may produce an <a href="#all_diagnostics_channel_errorevent"><code>error</code> event</a>
if the given function throws an error. This will run the given function using
<a href="#all_diagnostics_channel_channelrunstorescontext-fn-thisarg-args"><code>channel.runStores(context, ...)</code></a> on the <code>start</code> channel which ensures all
events should have any bound stores set to match this trace context.</p>
<p>To ensure only correct trace graphs are formed, events will only be published
if subscribers are present prior to starting the trace. Subscriptions which are
added after the trace begins will not receive future events from that trace,
only future traces will be seen.</p>

<pre class="with-64-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;

<span class="hljs-keyword">const</span> channels = diagnostics_channel.<span class="hljs-title function_">tracingChannel</span>(<span class="hljs-string">'my-channel'</span>);

channels.<span class="hljs-title function_">traceSync</span>(<span class="hljs-function">() =></span> {
  <span class="hljs-comment">// Do something</span>
}, {
  <span class="hljs-attr">some</span>: <span class="hljs-string">'thing'</span>,
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);

<span class="hljs-keyword">const</span> channels = diagnostics_channel.<span class="hljs-title function_">tracingChannel</span>(<span class="hljs-string">'my-channel'</span>);

channels.<span class="hljs-title function_">traceSync</span>(<span class="hljs-function">() =></span> {
  <span class="hljs-comment">// Do something</span>
}, {
  <span class="hljs-attr">some</span>: <span class="hljs-string">'thing'</span>,
});</code><button class="copy-button">copy</button></pre>
<h5><code>tracingChannel.tracePromise(fn[, context[, thisArg[, ...args]]])</code><span><a class="mark" href="#all_diagnostics_channel_tracingchanneltracepromisefn-context-thisarg-args" id="all_diagnostics_channel_tracingchanneltracepromisefn-context-thisarg-args">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_tracingchannel_tracepromise_fn_context_thisarg_args"></a></h5>
<div class="api_metadata">
<span>Added in: v19.9.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<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> Promise-returning function to wrap a trace around</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> Shared object to correlate trace events through</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>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> Chained from promise returned by the given function</li>
</ul>
<p>Trace a promise-returning function call. This will always produce a
<a href="#all_diagnostics_channel_startevent"><code>start</code> event</a> and <a href="#all_diagnostics_channel_endevent"><code>end</code> event</a> around the synchronous portion of the
function execution, and will produce an <a href="#all_diagnostics_channel_asyncstartevent"><code>asyncStart</code> event</a> and
<a href="#all_diagnostics_channel_asyncendevent"><code>asyncEnd</code> event</a> when a promise continuation is reached. It may also
produce an <a href="#all_diagnostics_channel_errorevent"><code>error</code> event</a> if the given function throws an error or the
returned promise rejects. This will run the given function using
<a href="#all_diagnostics_channel_channelrunstorescontext-fn-thisarg-args"><code>channel.runStores(context, ...)</code></a> on the <code>start</code> channel which ensures all
events should have any bound stores set to match this trace context.</p>
<p>To ensure only correct trace graphs are formed, events will only be published
if subscribers are present prior to starting the trace. Subscriptions which are
added after the trace begins will not receive future events from that trace,
only future traces will be seen.</p>

<pre class="with-64-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;

<span class="hljs-keyword">const</span> channels = diagnostics_channel.<span class="hljs-title function_">tracingChannel</span>(<span class="hljs-string">'my-channel'</span>);

channels.<span class="hljs-title function_">tracePromise</span>(<span class="hljs-keyword">async</span> () => {
  <span class="hljs-comment">// Do something</span>
}, {
  <span class="hljs-attr">some</span>: <span class="hljs-string">'thing'</span>,
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);

<span class="hljs-keyword">const</span> channels = diagnostics_channel.<span class="hljs-title function_">tracingChannel</span>(<span class="hljs-string">'my-channel'</span>);

channels.<span class="hljs-title function_">tracePromise</span>(<span class="hljs-keyword">async</span> () => {
  <span class="hljs-comment">// Do something</span>
}, {
  <span class="hljs-attr">some</span>: <span class="hljs-string">'thing'</span>,
});</code><button class="copy-button">copy</button></pre>
<h5><code>tracingChannel.traceCallback(fn[, position[, context[, thisArg[, ...args]]]])</code><span><a class="mark" href="#all_diagnostics_channel_tracingchanneltracecallbackfn-position-context-thisarg-args" id="all_diagnostics_channel_tracingchanneltracecallbackfn-position-context-thisarg-args">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_tracingchannel_tracecallback_fn_position_context_thisarg_args"></a></h5>
<div class="api_metadata">
<span>Added in: v19.9.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<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> callback using function to wrap a trace around</li>
<li><code>position</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Zero-indexed argument position of expected callback
(defaults to last argument if <code>undefined</code> is passed)</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> Shared object to correlate trace events through (defaults
to <code>{}</code> if <code>undefined</code> is passed)</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> arguments to pass to the function (must include the callback)</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> The return value of the given function</li>
</ul>
<p>Trace a callback-receiving function call. The callback is expected to follow
the error as first arg convention typically used. This will always produce a
<a href="#all_diagnostics_channel_startevent"><code>start</code> event</a> and <a href="#all_diagnostics_channel_endevent"><code>end</code> event</a> around the synchronous portion of the
function execution, and will produce a <a href="#all_diagnostics_channel_asyncstartevent"><code>asyncStart</code> event</a> and
<a href="#all_diagnostics_channel_asyncendevent"><code>asyncEnd</code> event</a> around the callback execution. It may also produce an
<a href="#all_diagnostics_channel_errorevent"><code>error</code> event</a> if the given function throws or the first argument passed to
the callback is set. This will run the given function using
<a href="#all_diagnostics_channel_channelrunstorescontext-fn-thisarg-args"><code>channel.runStores(context, ...)</code></a> on the <code>start</code> channel which ensures all
events should have any bound stores set to match this trace context.</p>
<p>To ensure only correct trace graphs are formed, events will only be published
if subscribers are present prior to starting the trace. Subscriptions which are
added after the trace begins will not receive future events from that trace,
only future traces will be seen.</p>

<pre class="with-64-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;

<span class="hljs-keyword">const</span> channels = diagnostics_channel.<span class="hljs-title function_">tracingChannel</span>(<span class="hljs-string">'my-channel'</span>);

channels.<span class="hljs-title function_">traceCallback</span>(<span class="hljs-function">(<span class="hljs-params">arg1, callback</span>) =></span> {
  <span class="hljs-comment">// Do something</span>
  <span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-string">'result'</span>);
}, <span class="hljs-number">1</span>, {
  <span class="hljs-attr">some</span>: <span class="hljs-string">'thing'</span>,
}, thisArg, arg1, callback);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);

<span class="hljs-keyword">const</span> channels = diagnostics_channel.<span class="hljs-title function_">tracingChannel</span>(<span class="hljs-string">'my-channel'</span>);

channels.<span class="hljs-title function_">traceCallback</span>(<span class="hljs-function">(<span class="hljs-params">arg1, callback</span>) =></span> {
  <span class="hljs-comment">// Do something</span>
  <span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-string">'result'</span>);
}, <span class="hljs-number">1</span>, {
  <span class="hljs-attr">some</span>: <span class="hljs-string">'thing'</span>,
}, thisArg, arg1, callback);</code><button class="copy-button">copy</button></pre>
<p>The callback will also be run with <a href="#all_diagnostics_channel_channelrunstorescontext-fn-thisarg-args"><code>channel.runStores(context, ...)</code></a> which
enables context loss recovery in some cases.</p>

<pre class="with-64-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">AsyncLocalStorage</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;

<span class="hljs-keyword">const</span> channels = diagnostics_channel.<span class="hljs-title function_">tracingChannel</span>(<span class="hljs-string">'my-channel'</span>);
<span class="hljs-keyword">const</span> myStore = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AsyncLocalStorage</span>();

<span class="hljs-comment">// The start channel sets the initial store data to something</span>
<span class="hljs-comment">// and stores that store data value on the trace context object</span>
channels.<span class="hljs-property">start</span>.<span class="hljs-title function_">bindStore</span>(myStore, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
  <span class="hljs-keyword">const</span> span = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Span</span>(data);
  data.<span class="hljs-property">span</span> = span;
  <span class="hljs-keyword">return</span> span;
});

<span class="hljs-comment">// Then asyncStart can restore from that data it stored previously</span>
channels.<span class="hljs-property">asyncStart</span>.<span class="hljs-title function_">bindStore</span>(myStore, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
  <span class="hljs-keyword">return</span> data.<span class="hljs-property">span</span>;
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">AsyncLocalStorage</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);

<span class="hljs-keyword">const</span> channels = diagnostics_channel.<span class="hljs-title function_">tracingChannel</span>(<span class="hljs-string">'my-channel'</span>);
<span class="hljs-keyword">const</span> myStore = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AsyncLocalStorage</span>();

<span class="hljs-comment">// The start channel sets the initial store data to something</span>
<span class="hljs-comment">// and stores that store data value on the trace context object</span>
channels.<span class="hljs-property">start</span>.<span class="hljs-title function_">bindStore</span>(myStore, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
  <span class="hljs-keyword">const</span> span = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Span</span>(data);
  data.<span class="hljs-property">span</span> = span;
  <span class="hljs-keyword">return</span> span;
});

<span class="hljs-comment">// Then asyncStart can restore from that data it stored previously</span>
channels.<span class="hljs-property">asyncStart</span>.<span class="hljs-title function_">bindStore</span>(myStore, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
  <span class="hljs-keyword">return</span> data.<span class="hljs-property">span</span>;
});</code><button class="copy-button">copy</button></pre>
<h5><code>tracingChannel.hasSubscribers</code><span><a class="mark" href="#all_diagnostics_channel_tracingchannelhassubscribers" id="all_diagnostics_channel_tracingchannelhassubscribers">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_tracingchannel_hassubscribers"></a></h5>
<div class="api_metadata">
<span>Added in: v22.0.0, v20.13.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<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 any of the individual channels has a subscriber,
<code>false</code> if not.</li>
</ul>
<p>This is a helper method available on a <a href="#all_diagnostics_channel_class-tracingchannel"><code>TracingChannel</code></a> instance to check if
any of the <a href="#all_diagnostics_channel_tracingchannel-channels">TracingChannel Channels</a> have subscribers. A <code>true</code> is returned if
any of them have at least one subscriber, a <code>false</code> is returned otherwise.</p>

<pre class="with-64-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> diagnostics_channel <span class="hljs-keyword">from</span> <span class="hljs-string">'node:diagnostics_channel'</span>;

<span class="hljs-keyword">const</span> channels = diagnostics_channel.<span class="hljs-title function_">tracingChannel</span>(<span class="hljs-string">'my-channel'</span>);

<span class="hljs-keyword">if</span> (channels.<span class="hljs-property">hasSubscribers</span>) {
  <span class="hljs-comment">// Do something</span>
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> diagnostics_channel = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:diagnostics_channel'</span>);

<span class="hljs-keyword">const</span> channels = diagnostics_channel.<span class="hljs-title function_">tracingChannel</span>(<span class="hljs-string">'my-channel'</span>);

<span class="hljs-keyword">if</span> (channels.<span class="hljs-property">hasSubscribers</span>) {
  <span class="hljs-comment">// Do something</span>
}</code><button class="copy-button">copy</button></pre>
<h4>TracingChannel Channels<span><a class="mark" href="#all_diagnostics_channel_tracingchannel-channels" id="all_diagnostics_channel_tracingchannel-channels">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_tracingchannel_channels"></a></h4>
<p>A TracingChannel is a collection of several diagnostics_channels representing
specific points in the execution lifecycle of a single traceable action. The
behavior is split into five diagnostics_channels consisting of <code>start</code>,
<code>end</code>, <code>asyncStart</code>, <code>asyncEnd</code>, and <code>error</code>. A single traceable action will
share the same event object between all events, this can be helpful for
managing correlation through a weakmap.</p>
<p>These event objects will be extended with <code>result</code> or <code>error</code> values when
the task "completes". In the case of a synchronous task the <code>result</code> will be
the return value and the <code>error</code> will be anything thrown from the function.
With callback-based async functions the <code>result</code> will be the second argument
of the callback while the <code>error</code> will either be a thrown error visible in the
<code>end</code> event or the first callback argument in either of the <code>asyncStart</code> or
<code>asyncEnd</code> events.</p>
<p>To ensure only correct trace graphs are formed, events should only be published
if subscribers are present prior to starting the trace. Subscriptions which are
added after the trace begins should not receive future events from that trace,
only future traces will be seen.</p>
<p>Tracing channels should follow a naming pattern of:</p>
<ul>
<li><code>tracing:module.class.method:start</code> or <code>tracing:module.function:start</code></li>
<li><code>tracing:module.class.method:end</code> or <code>tracing:module.function:end</code></li>
<li><code>tracing:module.class.method:asyncStart</code> or <code>tracing:module.function:asyncStart</code></li>
<li><code>tracing:module.class.method:asyncEnd</code> or <code>tracing:module.function:asyncEnd</code></li>
<li><code>tracing:module.class.method:error</code> or <code>tracing:module.function:error</code></li>
</ul>
<h5><code>start(event)</code><span><a class="mark" href="#all_diagnostics_channel_startevent" id="all_diagnostics_channel_startevent">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_start_event"></a></h5>
<ul>
<li>Name: <code>tracing:${name}:start</code></li>
</ul>
<p>The <code>start</code> event represents the point at which a function is called. At this
point the event data may contain function arguments or anything else available
at the very start of the execution of the function.</p>
<h5><code>end(event)</code><span><a class="mark" href="#all_diagnostics_channel_endevent" id="all_diagnostics_channel_endevent">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_end_event"></a></h5>
<ul>
<li>Name: <code>tracing:${name}:end</code></li>
</ul>
<p>The <code>end</code> event represents the point at which a function call returns a value.
In the case of an async function this is when the promise returned not when the
function itself makes a return statement internally. At this point, if the
traced function was synchronous the <code>result</code> field will be set to the return
value of the function. Alternatively, the <code>error</code> field may be present to
represent any thrown errors.</p>
<p>It is recommended to listen specifically to the <code>error</code> event to track errors
as it may be possible for a traceable action to produce multiple errors. For
example, an async task which fails may be started internally before the sync
part of the task then throws an error.</p>
<h5><code>asyncStart(event)</code><span><a class="mark" href="#all_diagnostics_channel_asyncstartevent" id="all_diagnostics_channel_asyncstartevent">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_asyncstart_event"></a></h5>
<ul>
<li>Name: <code>tracing:${name}:asyncStart</code></li>
</ul>
<p>The <code>asyncStart</code> event represents the callback or continuation of a traceable
function being reached. At this point things like callback arguments may be
available, or anything else expressing the "result" of the action.</p>
<p>For callbacks-based functions, the first argument of the callback will be
assigned to the <code>error</code> field, if not <code>undefined</code> or <code>null</code>, and the second
argument will be assigned to the <code>result</code> field.</p>
<p>For promises, the argument to the <code>resolve</code> path will be assigned to <code>result</code>
or the argument to the <code>reject</code> path will be assign to <code>error</code>.</p>
<p>It is recommended to listen specifically to the <code>error</code> event to track errors
as it may be possible for a traceable action to produce multiple errors. For
example, an async task which fails may be started internally before the sync
part of the task then throws an error.</p>
<h5><code>asyncEnd(event)</code><span><a class="mark" href="#all_diagnostics_channel_asyncendevent" id="all_diagnostics_channel_asyncendevent">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_asyncend_event"></a></h5>
<ul>
<li>Name: <code>tracing:${name}:asyncEnd</code></li>
</ul>
<p>The <code>asyncEnd</code> event represents the callback of an asynchronous function
returning. It's not likely event data will change after the <code>asyncStart</code> event,
however it may be useful to see the point where the callback completes.</p>
<h5><code>error(event)</code><span><a class="mark" href="#all_diagnostics_channel_errorevent" id="all_diagnostics_channel_errorevent">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_error_event"></a></h5>
<ul>
<li>Name: <code>tracing:${name}:error</code></li>
</ul>
<p>The <code>error</code> event represents any error produced by the traceable function
either synchronously or asynchronously. If an error is thrown in the
synchronous portion of the traced function the error will be assigned to the
<code>error</code> field of the event and the <code>error</code> event will be triggered. If an error
is received asynchronously through a callback or promise rejection it will also
be assigned to the <code>error</code> field of the event and trigger the <code>error</code> event.</p>
<p>It is possible for a single traceable function call to produce errors multiple
times so this should be considered when consuming this event. For example, if
another async task is triggered internally which fails and then the sync part
of the function then throws and error two <code>error</code> events will be emitted, one
for the sync error and one for the async error.</p>
<h4>Built-in Channels<span><a class="mark" href="#all_diagnostics_channel_built-in-channels" id="all_diagnostics_channel_built-in-channels">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_built_in_channels"></a></h4>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>While the diagnostics_channel API is now considered stable, the built-in
channels currently available are not. Each channel must be declared stable
independently.</p>
<h5>HTTP<span><a class="mark" href="#all_diagnostics_channel_http" id="all_diagnostics_channel_http">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_http"></a></h5>
<p><code>http.client.request.start</code></p>
<ul>
<li><code>request</code> <a href="#all_http_class-httpclientrequest" class="type">&#x3C;http.ClientRequest></a></li>
</ul>
<p>Emitted when client starts a request.</p>
<p><code>http.client.request.error</code></p>
<ul>
<li><code>request</code> <a href="#all_http_class-httpclientrequest" class="type">&#x3C;http.ClientRequest></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>
</ul>
<p>Emitted when an error occurs during a client request.</p>
<p><code>http.client.response.finish</code></p>
<ul>
<li><code>request</code> <a href="#all_http_class-httpclientrequest" class="type">&#x3C;http.ClientRequest></a></li>
<li><code>response</code> <a href="#all_http_class-httpincomingmessage" class="type">&#x3C;http.IncomingMessage></a></li>
</ul>
<p>Emitted when client receives a response.</p>
<p><code>http.server.request.start</code></p>
<ul>
<li><code>request</code> <a href="#all_http_class-httpincomingmessage" class="type">&#x3C;http.IncomingMessage></a></li>
<li><code>response</code> <a href="#all_http_class-httpserverresponse" class="type">&#x3C;http.ServerResponse></a></li>
<li><code>socket</code> <a href="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a></li>
<li><code>server</code> <a href="#all_http_class-httpserver" class="type">&#x3C;http.Server></a></li>
</ul>
<p>Emitted when server receives a request.</p>
<p><code>http.server.response.finish</code></p>
<ul>
<li><code>request</code> <a href="#all_http_class-httpincomingmessage" class="type">&#x3C;http.IncomingMessage></a></li>
<li><code>response</code> <a href="#all_http_class-httpserverresponse" class="type">&#x3C;http.ServerResponse></a></li>
<li><code>socket</code> <a href="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a></li>
<li><code>server</code> <a href="#all_http_class-httpserver" class="type">&#x3C;http.Server></a></li>
</ul>
<p>Emitted when server sends a response.</p>
<h5>NET<span><a class="mark" href="#all_diagnostics_channel_net" id="all_diagnostics_channel_net">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_net"></a></h5>
<p><code>net.client.socket</code></p>
<ul>
<li><code>socket</code> <a href="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a></li>
</ul>
<p>Emitted when a new TCP or pipe client socket is created.</p>
<p><code>net.server.socket</code></p>
<ul>
<li><code>socket</code> <a href="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a></li>
</ul>
<p>Emitted when a new TCP or pipe connection is received.</p>
<p><code>tracing:net.server.listen:asyncStart</code></p>
<ul>
<li><code>server</code> <a href="#all_net_class-netserver" class="type">&#x3C;net.Server></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></li>
</ul>
<p>Emitted when <a href="#all_net_serverlisten"><code>net.Server.listen()</code></a> is invoked, before the port or pipe is actually setup.</p>
<p><code>tracing:net.server.listen:asyncEnd</code></p>
<ul>
<li><code>server</code> <a href="#all_net_class-netserver" class="type">&#x3C;net.Server></a></li>
</ul>
<p>Emitted when <a href="#all_net_serverlisten"><code>net.Server.listen()</code></a> has completed and thus the server is ready to accept connection.</p>
<p><code>tracing:net.server.listen:error</code></p>
<ul>
<li><code>server</code> <a href="#all_net_class-netserver" class="type">&#x3C;net.Server></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>
</ul>
<p>Emitted when <a href="#all_net_serverlisten"><code>net.Server.listen()</code></a> is returning an error.</p>
<h5>UDP<span><a class="mark" href="#all_diagnostics_channel_udp" id="all_diagnostics_channel_udp">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_udp"></a></h5>
<p><code>udp.socket</code></p>
<ul>
<li><code>socket</code> <a href="#all_dgram_class-dgramsocket" class="type">&#x3C;dgram.Socket></a></li>
</ul>
<p>Emitted when a new UDP socket is created.</p>
<h5>Process<span><a class="mark" href="#all_diagnostics_channel_process" id="all_diagnostics_channel_process">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_process"></a></h5>
<div class="api_metadata">
<span>Added in: v16.18.0</span>
</div>
<p><code>child_process</code></p>
<ul>
<li><code>process</code> <a href="#all_child_process_class-childprocess" class="type">&#x3C;ChildProcess></a></li>
</ul>
<p>Emitted when a new process is created.</p>
<h5>Worker Thread<span><a class="mark" href="#all_diagnostics_channel_worker-thread" id="all_diagnostics_channel_worker-thread">#</a></span><a aria-hidden="true" class="legacy" id="diagnostics_channel_worker_thread"></a></h5>
<div class="api_metadata">
<span>Added in: v16.18.0</span>
</div>
<p><code>worker_threads</code></p>
<ul>
<li><code>worker</code> <a href="#all_worker_threads_class-worker"><code>Worker</code></a></li>
</ul>
<p>Emitted when a new thread is created.</p></section>
        </section>
<section><h2>DNS<span><a class="mark" href="#all_dns_dns" id="all_dns_dns">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns"></a></h2>

<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/dns.js">lib/dns.js</a></p>
<p>The <code>node: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="#all_dns_dnslookuphostname-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="#all_dns_dnslookuphostname-options-callback"><code>dns.lookup()</code></a>.</p>

<pre class="with-32-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> dns <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dns'</span>;

dns.<span class="hljs-title function_">lookup</span>(<span class="hljs-string">'example.org'</span>, <span class="hljs-function">(<span class="hljs-params">err, address, family</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'address: %j family: IPv%s'</span>, address, family);
});
<span class="hljs-comment">// address: "2606:2800:21f:cb07:6820:80da:af6b:8b2c" family: IPv6</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> dns = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:dns'</span>);

dns.<span class="hljs-title function_">lookup</span>(<span class="hljs-string">'example.org'</span>, <span class="hljs-function">(<span class="hljs-params">err, address, family</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'address: %j family: IPv%s'</span>, address, family);
});
<span class="hljs-comment">// address: "2606:2800:21f:cb07:6820:80da:af6b:8b2c" family: IPv6</span></code><button class="copy-button">copy</button></pre>
<p>All other functions in the <code>node: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="#all_dns_dnslookuphostname-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 class="with-32-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> dns <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dns'</span>;

dns.<span class="hljs-title function_">resolve4</span>(<span class="hljs-string">'archive.org'</span>, <span class="hljs-function">(<span class="hljs-params">err, addresses</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;

  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`addresses: <span class="hljs-subst">${<span class="hljs-built_in">JSON</span>.stringify(addresses)}</span>`</span>);

  addresses.<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">a</span>) =></span> {
    dns.<span class="hljs-title function_">reverse</span>(a, <span class="hljs-function">(<span class="hljs-params">err, hostnames</span>) =></span> {
      <span class="hljs-keyword">if</span> (err) {
        <span class="hljs-keyword">throw</span> err;
      }
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`reverse for <span class="hljs-subst">${a}</span>: <span class="hljs-subst">${<span class="hljs-built_in">JSON</span>.stringify(hostnames)}</span>`</span>);
    });
  });
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> dns = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:dns'</span>);

dns.<span class="hljs-title function_">resolve4</span>(<span class="hljs-string">'archive.org'</span>, <span class="hljs-function">(<span class="hljs-params">err, addresses</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;

  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`addresses: <span class="hljs-subst">${<span class="hljs-built_in">JSON</span>.stringify(addresses)}</span>`</span>);

  addresses.<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">a</span>) =></span> {
    dns.<span class="hljs-title function_">reverse</span>(a, <span class="hljs-function">(<span class="hljs-params">err, hostnames</span>) =></span> {
      <span class="hljs-keyword">if</span> (err) {
        <span class="hljs-keyword">throw</span> err;
      }
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`reverse for <span class="hljs-subst">${a}</span>: <span class="hljs-subst">${<span class="hljs-built_in">JSON</span>.stringify(hostnames)}</span>`</span>);
    });
  });
});</code><button class="copy-button">copy</button></pre>
<p>See the <a href="#all_dns_implementation-considerations">Implementation considerations section</a> for more information.</p>
<section><h3>Class: <code>dns.Resolver</code><span><a class="mark" href="#all_dns_class-dnsresolver" id="all_dns_class-dnsresolver">#</a></span><a aria-hidden="true" class="legacy" id="dns_class_dns_resolver"></a></h3>
<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="#all_dns_dnssetserversservers"><code>resolver.setServers()</code></a> does not affect
other resolvers:</p>

<pre class="with-41-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Resolver</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dns'</span>;
<span class="hljs-keyword">const</span> resolver = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Resolver</span>();
resolver.<span class="hljs-title function_">setServers</span>([<span class="hljs-string">'4.4.4.4'</span>]);

<span class="hljs-comment">// This request will use the server at 4.4.4.4, independent of global settings.</span>
resolver.<span class="hljs-title function_">resolve4</span>(<span class="hljs-string">'example.org'</span>, <span class="hljs-function">(<span class="hljs-params">err, addresses</span>) =></span> {
  <span class="hljs-comment">// ...</span>
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Resolver</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:dns'</span>);
<span class="hljs-keyword">const</span> resolver = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Resolver</span>();
resolver.<span class="hljs-title function_">setServers</span>([<span class="hljs-string">'4.4.4.4'</span>]);

<span class="hljs-comment">// This request will use the server at 4.4.4.4, independent of global settings.</span>
resolver.<span class="hljs-title function_">resolve4</span>(<span class="hljs-string">'example.org'</span>, <span class="hljs-function">(<span class="hljs-params">err, addresses</span>) =></span> {
  <span class="hljs-comment">// ...</span>
});</code><button class="copy-button">copy</button></pre>
<p>The following methods from the <code>node:dns</code> module are available:</p>
<ul>
<li><a href="#all_dns_dnsgetservers"><code>resolver.getServers()</code></a></li>
<li><a href="#all_dns_dnsresolvehostname-rrtype-callback"><code>resolver.resolve()</code></a></li>
<li><a href="#all_dns_dnsresolve4hostname-options-callback"><code>resolver.resolve4()</code></a></li>
<li><a href="#all_dns_dnsresolve6hostname-options-callback"><code>resolver.resolve6()</code></a></li>
<li><a href="#all_dns_dnsresolveanyhostname-callback"><code>resolver.resolveAny()</code></a></li>
<li><a href="#all_dns_dnsresolvecaahostname-callback"><code>resolver.resolveCaa()</code></a></li>
<li><a href="#all_dns_dnsresolvecnamehostname-callback"><code>resolver.resolveCname()</code></a></li>
<li><a href="#all_dns_dnsresolvemxhostname-callback"><code>resolver.resolveMx()</code></a></li>
<li><a href="#all_dns_dnsresolvenaptrhostname-callback"><code>resolver.resolveNaptr()</code></a></li>
<li><a href="#all_dns_dnsresolvenshostname-callback"><code>resolver.resolveNs()</code></a></li>
<li><a href="#all_dns_dnsresolveptrhostname-callback"><code>resolver.resolvePtr()</code></a></li>
<li><a href="#all_dns_dnsresolvesoahostname-callback"><code>resolver.resolveSoa()</code></a></li>
<li><a href="#all_dns_dnsresolvesrvhostname-callback"><code>resolver.resolveSrv()</code></a></li>
<li><a href="#all_dns_dnsresolvetxthostname-callback"><code>resolver.resolveTxt()</code></a></li>
<li><a href="#all_dns_dnsreverseip-callback"><code>resolver.reverse()</code></a></li>
<li><a href="#all_dns_dnssetserversservers"><code>resolver.setServers()</code></a></li>
</ul>
<h4><code>Resolver([options])</code><span><a class="mark" href="#all_dns_resolveroptions" id="all_dns_resolveroptions">#</a></span><a aria-hidden="true" class="legacy" id="dns_resolver_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.7.0, v14.18.0</td>
<td><p>The <code>options</code> object now accepts a <code>tries</code> option.</p></td></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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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>
<li><code>tries</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> The number of tries the resolver will try contacting
each name server before giving up. <strong>Default:</strong> <code>4</code></li>
</ul>
</li>
</ul>
<h4><code>resolver.cancel()</code><span><a class="mark" href="#all_dns_resolvercancel" id="all_dns_resolvercancel">#</a></span><a aria-hidden="true" class="legacy" id="dns_resolver_cancel"></a></h4>
<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>
<h4><code>resolver.setLocalAddress([ipv4][, ipv6])</code><span><a class="mark" href="#all_dns_resolversetlocaladdressipv4-ipv6" id="all_dns_resolversetlocaladdressipv4-ipv6">#</a></span><a aria-hidden="true" class="legacy" id="dns_resolver_setlocaladdress_ipv4_ipv6"></a></h4>
<div class="api_metadata">
<span>Added in: v15.1.0, v14.17.0</span>
</div>
<ul>
<li><code>ipv4</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 address.
<strong>Default:</strong> <code>'0.0.0.0'</code></li>
<li><code>ipv6</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 IPv6 address.
<strong>Default:</strong> <code>'::0'</code></li>
</ul>
<p>The resolver instance will send its requests from the specified IP address.
This allows programs to specify outbound interfaces when used on multi-homed
systems.</p>
<p>If a v4 or v6 address is not specified, it is set to the default and the
operating system will choose a local address automatically.</p>
<p>The resolver will use the v4 local address when making requests to IPv4 DNS
servers, and the v6 local address when making requests to IPv6 DNS servers.
The <code>rrtype</code> of resolution requests has no impact on the local address used.</p>
</section><section><h3><code>dns.getServers()</code><span><a class="mark" href="#all_dns_dnsgetservers" id="all_dns_dnsgetservers">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_getservers"></a></h3>
<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 @stylistic/js/semi-->
<pre><code class="language-js">[
  <span class="hljs-string">'8.8.8.8'</span>,
  <span class="hljs-string">'2001:4860:4860::8888'</span>,
  <span class="hljs-string">'8.8.8.8:1053'</span>,
  <span class="hljs-string">'[2001:4860:4860::8888]:1053'</span>,
]</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>dns.lookup(hostname[, options], callback)</code><span><a class="mark" href="#all_dns_dnslookuphostname-options-callback" id="all_dns_dnslookuphostname-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_lookup_hostname_options_callback"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.13.0</td>
<td><p>The <code>verbatim</code> option is now deprecated in favor of the new <code>order</code> option.</p></td></tr>
<tr><td>v18.4.0</td>
<td><p>For compatibility with <code>node:net</code>, when passing an option object the <code>family</code> option can be the string <code>'IPv4'</code> or the string <code>'IPv6'</code>.</p></td></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></tr>
<tr><td>v17.0.0</td>
<td><p>The <code>verbatim</code> options defaults to <code>true</code> now.</p></td></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><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>
<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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The record family. Must be <code>4</code>, <code>6</code>, or <code>0</code>. For
backward compatibility reasons,<code>'IPv4'</code> and <code>'IPv6'</code> are interpreted as <code>4</code>
and <code>6</code> respectively. The value <code>0</code> indicates that either an IPv4 or IPv6
address is returned. If the value <code>0</code> is used with <code>{ all: true }</code> (see
below), either one of or both IPv4 and IPv6 addresses are returned,
depending on the system's DNS resolver. <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="#all_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>order</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> When <code>verbatim</code>, the resolved addresses are return
unsorted. When <code>ipv4first</code>, the resolved addresses are sorted by placing
IPv4 addresses before IPv6 addresses. When <code>ipv6first</code>, the resolved
addresses are sorted by placing IPv6 addresses before IPv4 addresses.
<strong>Default:</strong> <code>verbatim</code> (addresses are not reordered).
Default value is configurable using <a href="#all_dns_dnssetdefaultresultorderorder"><code>dns.setDefaultResultOrder()</code></a> or
<a href="#all_cli_--dns-result-orderorder"><code>--dns-result-order</code></a>.</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.
This option will be deprecated in favor of <code>order</code>. When both are specified,
<code>order</code> has higher precedence. New code should only use <code>order</code>.
<strong>Default:</strong> <code>true</code> (addresses are not reordered). Default value is
configurable using <a href="#all_dns_dnssetdefaultresultorderorder"><code>dns.setDefaultResultOrder()</code></a> or
<a href="#all_cli_--dns-result-orderorder"><code>--dns-result-order</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>
<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
either IPv4 or IPv6 addresses, or both, are 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="#all_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="#all_dns_implementation-considerations">Implementation considerations section</a> before using
<code>dns.lookup()</code>.</p>
<p>Example usage:</p>

<pre class="with-32-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> dns <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dns'</span>;
<span class="hljs-keyword">const</span> options = {
  <span class="hljs-attr">family</span>: <span class="hljs-number">6</span>,
  <span class="hljs-attr">hints</span>: dns.<span class="hljs-property">ADDRCONFIG</span> | dns.<span class="hljs-property">V4MAPPED</span>,
};
dns.<span class="hljs-title function_">lookup</span>(<span class="hljs-string">'example.org'</span>, options, <span class="hljs-function">(<span class="hljs-params">err, address, family</span>) =></span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'address: %j family: IPv%s'</span>, address, family));
<span class="hljs-comment">// address: "2606:2800:21f:cb07:6820:80da:af6b:8b2c" family: IPv6</span>

<span class="hljs-comment">// When options.all is true, the result will be an Array.</span>
options.<span class="hljs-property">all</span> = <span class="hljs-literal">true</span>;
dns.<span class="hljs-title function_">lookup</span>(<span class="hljs-string">'example.org'</span>, options, <span class="hljs-function">(<span class="hljs-params">err, addresses</span>) =></span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'addresses: %j'</span>, addresses));
<span class="hljs-comment">// addresses: [{"address":"2606:2800:21f:cb07:6820:80da:af6b:8b2c","family":6}]</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> dns = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:dns'</span>);
<span class="hljs-keyword">const</span> options = {
  <span class="hljs-attr">family</span>: <span class="hljs-number">6</span>,
  <span class="hljs-attr">hints</span>: dns.<span class="hljs-property">ADDRCONFIG</span> | dns.<span class="hljs-property">V4MAPPED</span>,
};
dns.<span class="hljs-title function_">lookup</span>(<span class="hljs-string">'example.org'</span>, options, <span class="hljs-function">(<span class="hljs-params">err, address, family</span>) =></span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'address: %j family: IPv%s'</span>, address, family));
<span class="hljs-comment">// address: "2606:2800:21f:cb07:6820:80da:af6b:8b2c" family: IPv6</span>

<span class="hljs-comment">// When options.all is true, the result will be an Array.</span>
options.<span class="hljs-property">all</span> = <span class="hljs-literal">true</span>;
dns.<span class="hljs-title function_">lookup</span>(<span class="hljs-string">'example.org'</span>, options, <span class="hljs-function">(<span class="hljs-params">err, addresses</span>) =></span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'addresses: %j'</span>, addresses));
<span class="hljs-comment">// addresses: [{"address":"2606:2800:21f:cb07:6820:80da:af6b:8b2c","family":6}]</span></code><button class="copy-button">copy</button></pre>
<p>If this method is invoked as its <a href="#all_util_utilpromisifyoriginal"><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>
<h4>Supported getaddrinfo flags<span><a class="mark" href="#all_dns_supported-getaddrinfo-flags" id="all_dns_supported-getaddrinfo-flags">#</a></span><a aria-hidden="true" class="legacy" id="dns_supported_getaddrinfo_flags"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.13.0, 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="#all_dns_dnslookuphostname-options-callback"><code>dns.lookup()</code></a>.</p>
<ul>
<li><code>dns.ADDRCONFIG</code>: Limits returned address types to the types of non-loopback
addresses configured on the system. For example, IPv4 addresses are only
returned if the current system has at least one IPv4 address configured.</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>
</section><section><h3><code>dns.lookupService(address, port, callback)</code><span><a class="mark" href="#all_dns_dnslookupserviceaddress-port-callback" id="all_dns_dnslookupserviceaddress-port-callback">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_lookupservice_address_port_callback"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</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>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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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="#all_errors_class-error"><code>Error</code></a> object, where <code>err.code</code> is the error code.</p>

<pre class="with-64-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> dns <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dns'</span>;
dns.<span class="hljs-title function_">lookupService</span>(<span class="hljs-string">'127.0.0.1'</span>, <span class="hljs-number">22</span>, <span class="hljs-function">(<span class="hljs-params">err, hostname, service</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(hostname, service);
  <span class="hljs-comment">// Prints: localhost ssh</span>
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> dns = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:dns'</span>);
dns.<span class="hljs-title function_">lookupService</span>(<span class="hljs-string">'127.0.0.1'</span>, <span class="hljs-number">22</span>, <span class="hljs-function">(<span class="hljs-params">err, hostname, service</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(hostname, service);
  <span class="hljs-comment">// Prints: localhost ssh</span>
});</code><button class="copy-button">copy</button></pre>
<p>If this method is invoked as its <a href="#all_util_utilpromisifyoriginal"><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>
</section><section><h3><code>dns.resolve(hostname[, rrtype], callback)</code><span><a class="mark" href="#all_dns_dnsresolvehostname-rrtype-callback" id="all_dns_dnsresolvehostname-rrtype-callback">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_resolve_hostname_rrtype_callback"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</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><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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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="#all_dns_dnsresolve4hostname-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="#all_dns_dnsresolve6hostname-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="#all_dns_dnsresolveanyhostname-callback"><code>dns.resolveAny()</code></a></td></tr><tr><td><code>'CAA'</code></td><td>CA authorization 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="#all_dns_dnsresolvecaahostname-callback"><code>dns.resolveCaa()</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="#all_dns_dnsresolvecnamehostname-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="#all_dns_dnsresolvemxhostname-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="#all_dns_dnsresolvenaptrhostname-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="#all_dns_dnsresolvenshostname-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="#all_dns_dnsresolveptrhostname-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="#all_dns_dnsresolvesoahostname-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="#all_dns_dnsresolvesrvhostname-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="#all_dns_dnsresolvetxthostname-callback"><code>dns.resolveTxt()</code></a></td></tr></tbody></table>
<p>On error, <code>err</code> is an <a href="#all_errors_class-error"><code>Error</code></a> object, where <code>err.code</code> is one of the
<a href="#all_dns_error-codes">DNS error codes</a>.</p>
</section><section><h3><code>dns.resolve4(hostname[, options], callback)</code><span><a class="mark" href="#all_dns_dnsresolve4hostname-options-callback" id="all_dns_dnsresolve4hostname-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_resolve4_hostname_options_callback"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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> Retrieves the Time-To-Live value (TTL) of each record.
When <code>true</code>, the callback receives an array of
<code>{ address: '1.2.3.4', ttl: 60 }</code> objects rather than an array of strings,
with the TTL expressed in seconds.</li>
</ul>
</li>
<li><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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>
</section><section><h3><code>dns.resolve6(hostname[, options], callback)</code><span><a class="mark" href="#all_dns_dnsresolve6hostname-options-callback" id="all_dns_dnsresolve6hostname-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_resolve6_hostname_options_callback"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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 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>
</section><section><h3><code>dns.resolveAny(hostname, callback)</code><span><a class="mark" href="#all_dns_dnsresolveanyhostname-callback" id="all_dns_dnsresolveanyhostname-callback">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_resolveany_hostname_callback"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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="#all_dns_dnsresolvemxhostname-callback"><code>dns.resolveMx()</code></a></td></tr><tr><td><code>'NAPTR'</code></td><td>Refer to <a href="#all_dns_dnsresolvenaptrhostname-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="#all_dns_dnsresolvesoahostname-callback"><code>dns.resolveSoa()</code></a></td></tr><tr><td><code>'SRV'</code></td><td>Refer to <a href="#all_dns_dnsresolvesrvhostname-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="#all_dns_dnsresolvetxthostname-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 @stylistic/js/semi -->
<pre><code class="language-js">[ { <span class="hljs-attr">type</span>: <span class="hljs-string">'A'</span>, <span class="hljs-attr">address</span>: <span class="hljs-string">'127.0.0.1'</span>, <span class="hljs-attr">ttl</span>: <span class="hljs-number">299</span> },
  { <span class="hljs-attr">type</span>: <span class="hljs-string">'CNAME'</span>, <span class="hljs-attr">value</span>: <span class="hljs-string">'example.com'</span> },
  { <span class="hljs-attr">type</span>: <span class="hljs-string">'MX'</span>, <span class="hljs-attr">exchange</span>: <span class="hljs-string">'alt4.aspmx.l.example.com'</span>, <span class="hljs-attr">priority</span>: <span class="hljs-number">50</span> },
  { <span class="hljs-attr">type</span>: <span class="hljs-string">'NS'</span>, <span class="hljs-attr">value</span>: <span class="hljs-string">'ns1.example.com'</span> },
  { <span class="hljs-attr">type</span>: <span class="hljs-string">'TXT'</span>, <span class="hljs-attr">entries</span>: [ <span class="hljs-string">'v=spf1 include:_spf.example.com ~all'</span> ] },
  { <span class="hljs-attr">type</span>: <span class="hljs-string">'SOA'</span>,
    <span class="hljs-attr">nsname</span>: <span class="hljs-string">'ns1.example.com'</span>,
    <span class="hljs-attr">hostmaster</span>: <span class="hljs-string">'admin.example.com'</span>,
    <span class="hljs-attr">serial</span>: <span class="hljs-number">156696742</span>,
    <span class="hljs-attr">refresh</span>: <span class="hljs-number">900</span>,
    <span class="hljs-attr">retry</span>: <span class="hljs-number">900</span>,
    <span class="hljs-attr">expire</span>: <span class="hljs-number">1800</span>,
    <span class="hljs-attr">minttl</span>: <span class="hljs-number">60</span> } ]</code> <button class="copy-button">copy</button></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="#all_dns_dnsresolve4hostname-options-callback"><code>dns.resolve4()</code></a>,
<a href="#all_dns_dnsresolvemxhostname-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>
</section><section><h3><code>dns.resolveCname(hostname, callback)</code><span><a class="mark" href="#all_dns_dnsresolvecnamehostname-callback" id="all_dns_dnsresolvecnamehostname-callback">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_resolvecname_hostname_callback"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</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><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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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>
</section><section><h3><code>dns.resolveCaa(hostname, callback)</code><span><a class="mark" href="#all_dns_dnsresolvecaahostname-callback" id="all_dns_dnsresolvecaahostname-callback">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_resolvecaa_hostname_callback"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></tr>
<tr><td>v15.0.0, v14.17.0</td>
<td><p><span>Added in: v15.0.0, v14.17.0</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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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/Reference/Global_Objects/Object" class="type">&#x3C;Object[]></a></li>
</ul>
</li>
</ul>
<p>Uses the DNS protocol to resolve <code>CAA</code> records for the <code>hostname</code>. The
<code>addresses</code> argument passed to the <code>callback</code> function
will contain an array of certification authority authorization records
available for the <code>hostname</code> (e.g. <code>[{critical: 0, iodef: 'mailto:pki@example.com'}, {critical: 128, issue: 'pki.example.com'}]</code>).</p>
</section><section><h3><code>dns.resolveMx(hostname, callback)</code><span><a class="mark" href="#all_dns_dnsresolvemxhostname-callback" id="all_dns_dnsresolvemxhostname-callback">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_resolvemx_hostname_callback"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</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><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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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>
</section><section><h3><code>dns.resolveNaptr(hostname, callback)</code><span><a class="mark" href="#all_dns_dnsresolvenaptrhostname-callback" id="all_dns_dnsresolvenaptrhostname-callback">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_resolvenaptr_hostname_callback"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></tr>
<tr><td>v0.9.12</td>
<td><p><span>Added in: v0.9.12</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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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">{
  <span class="hljs-attr">flags</span>: <span class="hljs-string">'s'</span>,
  <span class="hljs-attr">service</span>: <span class="hljs-string">'SIP+D2U'</span>,
  <span class="hljs-attr">regexp</span>: <span class="hljs-string">''</span>,
  <span class="hljs-attr">replacement</span>: <span class="hljs-string">'_sip._udp.example.com'</span>,
  <span class="hljs-attr">order</span>: <span class="hljs-number">30</span>,
  <span class="hljs-attr">preference</span>: <span class="hljs-number">100</span>
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>dns.resolveNs(hostname, callback)</code><span><a class="mark" href="#all_dns_dnsresolvenshostname-callback" id="all_dns_dnsresolvenshostname-callback">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_resolvens_hostname_callback"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</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>hostname</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>
<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>
</section><section><h3><code>dns.resolvePtr(hostname, callback)</code><span><a class="mark" href="#all_dns_dnsresolveptrhostname-callback" id="all_dns_dnsresolveptrhostname-callback">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_resolveptr_hostname_callback"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</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>hostname</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>
<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>
</section><section><h3><code>dns.resolveSoa(hostname, callback)</code><span><a class="mark" href="#all_dns_dnsresolvesoahostname-callback" id="all_dns_dnsresolvesoahostname-callback">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_resolvesoa_hostname_callback"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></tr>
<tr><td>v0.11.10</td>
<td><p><span>Added in: v0.11.10</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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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">{
  <span class="hljs-attr">nsname</span>: <span class="hljs-string">'ns.example.com'</span>,
  <span class="hljs-attr">hostmaster</span>: <span class="hljs-string">'root.example.com'</span>,
  <span class="hljs-attr">serial</span>: <span class="hljs-number">2013101809</span>,
  <span class="hljs-attr">refresh</span>: <span class="hljs-number">10000</span>,
  <span class="hljs-attr">retry</span>: <span class="hljs-number">2400</span>,
  <span class="hljs-attr">expire</span>: <span class="hljs-number">604800</span>,
  <span class="hljs-attr">minttl</span>: <span class="hljs-number">3600</span>
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>dns.resolveSrv(hostname, callback)</code><span><a class="mark" href="#all_dns_dnsresolvesrvhostname-callback" id="all_dns_dnsresolvesrvhostname-callback">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_resolvesrv_hostname_callback"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</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><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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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">{
  <span class="hljs-attr">priority</span>: <span class="hljs-number">10</span>,
  <span class="hljs-attr">weight</span>: <span class="hljs-number">5</span>,
  <span class="hljs-attr">port</span>: <span class="hljs-number">21223</span>,
  <span class="hljs-attr">name</span>: <span class="hljs-string">'service.example.com'</span>
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>dns.resolveTxt(hostname, callback)</code><span><a class="mark" href="#all_dns_dnsresolvetxthostname-callback" id="all_dns_dnsresolvetxthostname-callback">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_resolvetxt_hostname_callback"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</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>
<!--lint disable no-undefined-references list-item-bullet-indent-->
<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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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>
<!--lint enable no-undefined-references list-item-bullet-indent-->
<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>
</section><section><h3><code>dns.reverse(ip, callback)</code><span><a class="mark" href="#all_dns_dnsreverseip-callback" id="all_dns_dnsreverseip-callback">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_reverse_ip_callback"></a></h3>
<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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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="#all_errors_class-error"><code>Error</code></a> object, where <code>err.code</code> is
one of the <a href="#all_dns_error-codes">DNS error codes</a>.</p>
</section><section><h3><code>dns.setDefaultResultOrder(order)</code><span><a class="mark" href="#all_dns_dnssetdefaultresultorderorder" id="all_dns_dnssetdefaultresultorderorder">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_setdefaultresultorder_order"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.13.0</td>
<td><p>The <code>ipv6first</code> value is supported now.</p></td></tr>
<tr><td>v17.0.0</td>
<td><p>Changed default value to <code>verbatim</code>.</p></td></tr>
<tr><td>v16.4.0, v14.18.0</td>
<td><p><span>Added in: v16.4.0, v14.18.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>order</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> must be <code>'ipv4first'</code>, <code>'ipv6first'</code> or <code>'verbatim'</code>.</li>
</ul>
<p>Set the default value of <code>order</code> in <a href="#all_dns_dnslookuphostname-options-callback"><code>dns.lookup()</code></a> and
<a href="#all_dns_dnspromiseslookuphostname-options"><code>dnsPromises.lookup()</code></a>. The value could be:</p>
<ul>
<li><code>ipv4first</code>: sets default <code>order</code> to <code>ipv4first</code>.</li>
<li><code>ipv6first</code>: sets default <code>order</code> to <code>ipv6first</code>.</li>
<li><code>verbatim</code>: sets default <code>order</code> to <code>verbatim</code>.</li>
</ul>
<p>The default is <code>verbatim</code> and <a href="#all_dns_dnssetdefaultresultorderorder"><code>dns.setDefaultResultOrder()</code></a> have higher
priority than <a href="#all_cli_--dns-result-orderorder"><code>--dns-result-order</code></a>. When using <a href="worker_threads.html">worker threads</a>,
<a href="#all_dns_dnssetdefaultresultorderorder"><code>dns.setDefaultResultOrder()</code></a> from the main thread won't affect the default
dns orders in workers.</p>
</section><section><h3><code>dns.getDefaultResultOrder()</code><span><a class="mark" href="#all_dns_dnsgetdefaultresultorder" id="all_dns_dnsgetdefaultresultorder">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_getdefaultresultorder"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.13.0</td>
<td><p>The <code>ipv6first</code> value is supported now.</p></td></tr>
<tr><td>v20.1.0, v18.17.0</td>
<td><p><span>Added in: v20.1.0, v18.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Get the default value for <code>order</code> in <a href="#all_dns_dnslookuphostname-options-callback"><code>dns.lookup()</code></a> and
<a href="#all_dns_dnspromiseslookuphostname-options"><code>dnsPromises.lookup()</code></a>. The value could be:</p>
<ul>
<li><code>ipv4first</code>: for <code>order</code> defaulting to <code>ipv4first</code>.</li>
<li><code>ipv6first</code>: for <code>order</code> defaulting to <code>ipv6first</code>.</li>
<li><code>verbatim</code>: for <code>order</code> defaulting to <code>verbatim</code>.</li>
</ul>
</section><section><h3><code>dns.setServers(servers)</code><span><a class="mark" href="#all_dns_dnssetserversservers" id="all_dns_dnssetserversservers">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_setservers_servers"></a></h3>
<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.<span class="hljs-title function_">setServers</span>([
  <span class="hljs-string">'8.8.8.8'</span>,
  <span class="hljs-string">'[2001:4860:4860::8888]'</span>,
  <span class="hljs-string">'8.8.8.8:1053'</span>,
  <span class="hljs-string">'[2001:4860:4860::8888]:1053'</span>,
]);</code> <button class="copy-button">copy</button></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="#all_dns_dnssetserversservers"><code>dns.setServers()</code></a> method affects only <a href="#all_dns_dnsresolvehostname-rrtype-callback"><code>dns.resolve()</code></a>,
<code>dns.resolve*()</code> and <a href="#all_dns_dnsreverseip-callback"><code>dns.reverse()</code></a> (and specifically <em>not</em>
<a href="#all_dns_dnslookuphostname-options-callback"><code>dns.lookup()</code></a>).</p>
<p>This method works much like
<a href="https://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>
</section><section><h3>DNS promises API<span><a class="mark" href="#all_dns_dns-promises-api" id="all_dns_dns-promises-api">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_promises_api"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>Exposed as <code>require('dns/promises')</code>.</p></td></tr>
<tr><td>v11.14.0, v10.17.0</td>
<td><p>This API is no longer experimental.</p></td></tr>
<tr><td>v10.6.0</td>
<td><p><span>Added in: v10.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<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('node:dns').promises</code> or <code>require('node:dns/promises')</code>.</p>
<h4>Class: <code>dnsPromises.Resolver</code><span><a class="mark" href="#all_dns_class-dnspromisesresolver" id="all_dns_class-dnspromisesresolver">#</a></span><a aria-hidden="true" class="legacy" id="dns_class_dnspromises_resolver"></a></h4>
<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="#all_dns_dnspromisessetserversservers"><code>resolver.setServers()</code></a> does not affect
other resolvers:</p>

<pre class="with-50-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Resolver</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dns/promises'</span>;
<span class="hljs-keyword">const</span> resolver = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Resolver</span>();
resolver.<span class="hljs-title function_">setServers</span>([<span class="hljs-string">'4.4.4.4'</span>]);

<span class="hljs-comment">// This request will use the server at 4.4.4.4, independent of global settings.</span>
<span class="hljs-keyword">const</span> addresses = <span class="hljs-keyword">await</span> resolver.<span class="hljs-title function_">resolve4</span>(<span class="hljs-string">'example.org'</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Resolver</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:dns'</span>).<span class="hljs-property">promises</span>;
<span class="hljs-keyword">const</span> resolver = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Resolver</span>();
resolver.<span class="hljs-title function_">setServers</span>([<span class="hljs-string">'4.4.4.4'</span>]);

<span class="hljs-comment">// This request will use the server at 4.4.4.4, independent of global settings.</span>
resolver.<span class="hljs-title function_">resolve4</span>(<span class="hljs-string">'example.org'</span>).<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">addresses</span>) =></span> {
  <span class="hljs-comment">// ...</span>
});

<span class="hljs-comment">// Alternatively, the same code can be written using async-await style.</span>
(<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">const</span> addresses = <span class="hljs-keyword">await</span> resolver.<span class="hljs-title function_">resolve4</span>(<span class="hljs-string">'example.org'</span>);
})();</code><button class="copy-button">copy</button></pre>
<p>The following methods from the <code>dnsPromises</code> API are available:</p>
<ul>
<li><a href="#all_dns_dnspromisesgetservers"><code>resolver.getServers()</code></a></li>
<li><a href="#all_dns_dnspromisesresolvehostname-rrtype"><code>resolver.resolve()</code></a></li>
<li><a href="#all_dns_dnspromisesresolve4hostname-options"><code>resolver.resolve4()</code></a></li>
<li><a href="#all_dns_dnspromisesresolve6hostname-options"><code>resolver.resolve6()</code></a></li>
<li><a href="#all_dns_dnspromisesresolveanyhostname"><code>resolver.resolveAny()</code></a></li>
<li><a href="#all_dns_dnspromisesresolvecaahostname"><code>resolver.resolveCaa()</code></a></li>
<li><a href="#all_dns_dnspromisesresolvecnamehostname"><code>resolver.resolveCname()</code></a></li>
<li><a href="#all_dns_dnspromisesresolvemxhostname"><code>resolver.resolveMx()</code></a></li>
<li><a href="#all_dns_dnspromisesresolvenaptrhostname"><code>resolver.resolveNaptr()</code></a></li>
<li><a href="#all_dns_dnspromisesresolvenshostname"><code>resolver.resolveNs()</code></a></li>
<li><a href="#all_dns_dnspromisesresolveptrhostname"><code>resolver.resolvePtr()</code></a></li>
<li><a href="#all_dns_dnspromisesresolvesoahostname"><code>resolver.resolveSoa()</code></a></li>
<li><a href="#all_dns_dnspromisesresolvesrvhostname"><code>resolver.resolveSrv()</code></a></li>
<li><a href="#all_dns_dnspromisesresolvetxthostname"><code>resolver.resolveTxt()</code></a></li>
<li><a href="#all_dns_dnspromisesreverseip"><code>resolver.reverse()</code></a></li>
<li><a href="#all_dns_dnspromisessetserversservers"><code>resolver.setServers()</code></a></li>
</ul>
<h4><code>resolver.cancel()</code><span><a class="mark" href="#all_dns_resolvercancel_1" id="all_dns_resolvercancel_1">#</a></span><a aria-hidden="true" class="legacy" id="dns_resolver_cancel_1"></a></h4>
<div class="api_metadata">
<span>Added in: v15.3.0, v14.17.0</span>
</div>
<p>Cancel all outstanding DNS queries made by this resolver. The corresponding
promises will be rejected with an error with the code <code>ECANCELLED</code>.</p>
<h4><code>dnsPromises.getServers()</code><span><a class="mark" href="#all_dns_dnspromisesgetservers" id="all_dns_dnspromisesgetservers">#</a></span><a aria-hidden="true" class="legacy" id="dns_dnspromises_getservers"></a></h4>
<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 @stylistic/js/semi-->
<pre><code class="language-js">[
  <span class="hljs-string">'8.8.8.8'</span>,
  <span class="hljs-string">'2001:4860:4860::8888'</span>,
  <span class="hljs-string">'8.8.8.8:1053'</span>,
  <span class="hljs-string">'[2001:4860:4860::8888]:1053'</span>,
]</code> <button class="copy-button">copy</button></pre>
<h4><code>dnsPromises.lookup(hostname[, options])</code><span><a class="mark" href="#all_dns_dnspromiseslookuphostname-options" id="all_dns_dnspromiseslookuphostname-options">#</a></span><a aria-hidden="true" class="legacy" id="dns_dnspromises_lookup_hostname_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.13.0</td>
<td><p>The <code>verbatim</code> option is now deprecated in favor of the new <code>order</code> option.</p></td></tr>
<tr><td>v10.6.0</td>
<td><p><span>Added in: v10.6.0</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><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>
<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 either an IPv4 or IPv6 address is returned. If the
value <code>0</code> is used with <code>{ all: true }</code> (see below), either one of or both
IPv4 and IPv6 addresses are returned, depending on the system's DNS
resolver. <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="#all_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>order</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> When <code>verbatim</code>, the <code>Promise</code> is resolved with IPv4 and
IPv6 addresses in the order the DNS resolver returned them. When <code>ipv4first</code>,
IPv4 addresses are placed before IPv6 addresses. When <code>ipv6first</code>,
IPv6 addresses are placed before IPv4 addresses.
<strong>Default:</strong> <code>verbatim</code> (addresses are not reordered).
Default value is configurable using <a href="#all_dns_dnssetdefaultresultorderorder"><code>dns.setDefaultResultOrder()</code></a> or
<a href="#all_cli_--dns-result-orderorder"><code>--dns-result-order</code></a>. New code should use <code>{ order: 'verbatim' }</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.
This option will be deprecated in favor of <code>order</code>. When both are specified,
<code>order</code> has higher precedence. New code should only use <code>order</code>.
<strong>Default:</strong> currently <code>false</code> (addresses are reordered) but this is
expected to change in the not too distant future. Default value is
configurable using <a href="#all_dns_dnssetdefaultresultorderorder"><code>dns.setDefaultResultOrder()</code></a> or
<a href="#all_cli_--dns-result-orderorder"><code>--dns-result-order</code></a>.</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
either IPv4 or IPv6 addresses, or both, are 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="#all_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="#all_dns_dnspromiseslookuphostname-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="#all_dns_implementation-considerations">Implementation considerations section</a> before
using <code>dnsPromises.lookup()</code>.</p>
<p>Example usage:</p>

<pre class="with-33-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> dns <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dns'</span>;
<span class="hljs-keyword">const</span> dnsPromises = dns.<span class="hljs-property">promises</span>;
<span class="hljs-keyword">const</span> options = {
  <span class="hljs-attr">family</span>: <span class="hljs-number">6</span>,
  <span class="hljs-attr">hints</span>: dns.<span class="hljs-property">ADDRCONFIG</span> | dns.<span class="hljs-property">V4MAPPED</span>,
};

<span class="hljs-keyword">await</span> dnsPromises.<span class="hljs-title function_">lookup</span>(<span class="hljs-string">'example.org'</span>, options).<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">result</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'address: %j family: IPv%s'</span>, result.<span class="hljs-property">address</span>, result.<span class="hljs-property">family</span>);
  <span class="hljs-comment">// address: "2606:2800:21f:cb07:6820:80da:af6b:8b2c" family: IPv6</span>
});

<span class="hljs-comment">// When options.all is true, the result will be an Array.</span>
options.<span class="hljs-property">all</span> = <span class="hljs-literal">true</span>;
<span class="hljs-keyword">await</span> dnsPromises.<span class="hljs-title function_">lookup</span>(<span class="hljs-string">'example.org'</span>, options).<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">result</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'addresses: %j'</span>, result);
  <span class="hljs-comment">// addresses: [{"address":"2606:2800:21f:cb07:6820:80da:af6b:8b2c","family":6}]</span>
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> dns = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:dns'</span>);
<span class="hljs-keyword">const</span> dnsPromises = dns.<span class="hljs-property">promises</span>;
<span class="hljs-keyword">const</span> options = {
  <span class="hljs-attr">family</span>: <span class="hljs-number">6</span>,
  <span class="hljs-attr">hints</span>: dns.<span class="hljs-property">ADDRCONFIG</span> | dns.<span class="hljs-property">V4MAPPED</span>,
};

dnsPromises.<span class="hljs-title function_">lookup</span>(<span class="hljs-string">'example.org'</span>, options).<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">result</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'address: %j family: IPv%s'</span>, result.<span class="hljs-property">address</span>, result.<span class="hljs-property">family</span>);
  <span class="hljs-comment">// address: "2606:2800:21f:cb07:6820:80da:af6b:8b2c" family: IPv6</span>
});

<span class="hljs-comment">// When options.all is true, the result will be an Array.</span>
options.<span class="hljs-property">all</span> = <span class="hljs-literal">true</span>;
dnsPromises.<span class="hljs-title function_">lookup</span>(<span class="hljs-string">'example.org'</span>, options).<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">result</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'addresses: %j'</span>, result);
  <span class="hljs-comment">// addresses: [{"address":"2606:2800:21f:cb07:6820:80da:af6b:8b2c","family":6}]</span>
});</code><button class="copy-button">copy</button></pre>
<h4><code>dnsPromises.lookupService(address, port)</code><span><a class="mark" href="#all_dns_dnspromiseslookupserviceaddress-port" id="all_dns_dnspromiseslookupserviceaddress-port">#</a></span><a aria-hidden="true" class="legacy" id="dns_dnspromises_lookupservice_address_port"></a></h4>
<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="#all_errors_class-error"><code>Error</code></a> object, where <code>err.code</code>
is the error code.</p>

<pre class="with-64-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> dnsPromises <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dns/promises'</span>;
<span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> dnsPromises.<span class="hljs-title function_">lookupService</span>(<span class="hljs-string">'127.0.0.1'</span>, <span class="hljs-number">22</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result.<span class="hljs-property">hostname</span>, result.<span class="hljs-property">service</span>); <span class="hljs-comment">// Prints: localhost ssh</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> dnsPromises = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:dns'</span>).<span class="hljs-property">promises</span>;
dnsPromises.<span class="hljs-title function_">lookupService</span>(<span class="hljs-string">'127.0.0.1'</span>, <span class="hljs-number">22</span>).<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">result</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result.<span class="hljs-property">hostname</span>, result.<span class="hljs-property">service</span>);
  <span class="hljs-comment">// Prints: localhost ssh</span>
});</code><button class="copy-button">copy</button></pre>
<h4><code>dnsPromises.resolve(hostname[, rrtype])</code><span><a class="mark" href="#all_dns_dnspromisesresolvehostname-rrtype" id="all_dns_dnspromisesresolvehostname-rrtype">#</a></span><a aria-hidden="true" class="legacy" id="dns_dnspromises_resolve_hostname_rrtype"></a></h4>
<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="#all_dns_dnspromisesresolve4hostname-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="#all_dns_dnspromisesresolve6hostname-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="#all_dns_dnspromisesresolveanyhostname"><code>dnsPromises.resolveAny()</code></a></td></tr><tr><td><code>'CAA'</code></td><td>CA authorization 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="#all_dns_dnspromisesresolvecaahostname"><code>dnsPromises.resolveCaa()</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="#all_dns_dnspromisesresolvecnamehostname"><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="#all_dns_dnspromisesresolvemxhostname"><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="#all_dns_dnspromisesresolvenaptrhostname"><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="#all_dns_dnspromisesresolvenshostname"><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="#all_dns_dnspromisesresolveptrhostname"><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="#all_dns_dnspromisesresolvesoahostname"><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="#all_dns_dnspromisesresolvesrvhostname"><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="#all_dns_dnspromisesresolvetxthostname"><code>dnsPromises.resolveTxt()</code></a></td></tr></tbody></table>
<p>On error, the <code>Promise</code> is rejected with an <a href="#all_errors_class-error"><code>Error</code></a> object, where <code>err.code</code>
is one of the <a href="#all_dns_error-codes">DNS error codes</a>.</p>
<h4><code>dnsPromises.resolve4(hostname[, options])</code><span><a class="mark" href="#all_dns_dnspromisesresolve4hostname-options" id="all_dns_dnspromisesresolve4hostname-options">#</a></span><a aria-hidden="true" class="legacy" id="dns_dnspromises_resolve4_hostname_options"></a></h4>
<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>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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>
<h4><code>dnsPromises.resolve6(hostname[, options])</code><span><a class="mark" href="#all_dns_dnspromisesresolve6hostname-options" id="all_dns_dnspromisesresolve6hostname-options">#</a></span><a aria-hidden="true" class="legacy" id="dns_dnspromises_resolve6_hostname_options"></a></h4>
<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>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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>
<h4><code>dnsPromises.resolveAny(hostname)</code><span><a class="mark" href="#all_dns_dnspromisesresolveanyhostname" id="all_dns_dnspromisesresolveanyhostname">#</a></span><a aria-hidden="true" class="legacy" id="dns_dnspromises_resolveany_hostname"></a></h4>
<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="#all_dns_dnspromisesresolvemxhostname"><code>dnsPromises.resolveMx()</code></a></td></tr><tr><td><code>'NAPTR'</code></td><td>Refer to <a href="#all_dns_dnspromisesresolvenaptrhostname"><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="#all_dns_dnspromisesresolvesoahostname"><code>dnsPromises.resolveSoa()</code></a></td></tr><tr><td><code>'SRV'</code></td><td>Refer to <a href="#all_dns_dnspromisesresolvesrvhostname"><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="#all_dns_dnspromisesresolvetxthostname"><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 @stylistic/js/semi -->
<pre><code class="language-js">[ { <span class="hljs-attr">type</span>: <span class="hljs-string">'A'</span>, <span class="hljs-attr">address</span>: <span class="hljs-string">'127.0.0.1'</span>, <span class="hljs-attr">ttl</span>: <span class="hljs-number">299</span> },
  { <span class="hljs-attr">type</span>: <span class="hljs-string">'CNAME'</span>, <span class="hljs-attr">value</span>: <span class="hljs-string">'example.com'</span> },
  { <span class="hljs-attr">type</span>: <span class="hljs-string">'MX'</span>, <span class="hljs-attr">exchange</span>: <span class="hljs-string">'alt4.aspmx.l.example.com'</span>, <span class="hljs-attr">priority</span>: <span class="hljs-number">50</span> },
  { <span class="hljs-attr">type</span>: <span class="hljs-string">'NS'</span>, <span class="hljs-attr">value</span>: <span class="hljs-string">'ns1.example.com'</span> },
  { <span class="hljs-attr">type</span>: <span class="hljs-string">'TXT'</span>, <span class="hljs-attr">entries</span>: [ <span class="hljs-string">'v=spf1 include:_spf.example.com ~all'</span> ] },
  { <span class="hljs-attr">type</span>: <span class="hljs-string">'SOA'</span>,
    <span class="hljs-attr">nsname</span>: <span class="hljs-string">'ns1.example.com'</span>,
    <span class="hljs-attr">hostmaster</span>: <span class="hljs-string">'admin.example.com'</span>,
    <span class="hljs-attr">serial</span>: <span class="hljs-number">156696742</span>,
    <span class="hljs-attr">refresh</span>: <span class="hljs-number">900</span>,
    <span class="hljs-attr">retry</span>: <span class="hljs-number">900</span>,
    <span class="hljs-attr">expire</span>: <span class="hljs-number">1800</span>,
    <span class="hljs-attr">minttl</span>: <span class="hljs-number">60</span> } ]</code> <button class="copy-button">copy</button></pre>
<h4><code>dnsPromises.resolveCaa(hostname)</code><span><a class="mark" href="#all_dns_dnspromisesresolvecaahostname" id="all_dns_dnspromisesresolvecaahostname">#</a></span><a aria-hidden="true" class="legacy" id="dns_dnspromises_resolvecaa_hostname"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0, v14.17.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>CAA</code> records for the <code>hostname</code>. On success,
the <code>Promise</code> is resolved with an array of objects containing available
certification authority authorization records available for the <code>hostname</code>
(e.g. <code>[{critical: 0, iodef: 'mailto:pki@example.com'},{critical: 128, issue: 'pki.example.com'}]</code>).</p>
<h4><code>dnsPromises.resolveCname(hostname)</code><span><a class="mark" href="#all_dns_dnspromisesresolvecnamehostname" id="all_dns_dnspromisesresolvecnamehostname">#</a></span><a aria-hidden="true" class="legacy" id="dns_dnspromises_resolvecname_hostname"></a></h4>
<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>
<h4><code>dnsPromises.resolveMx(hostname)</code><span><a class="mark" href="#all_dns_dnspromisesresolvemxhostname" id="all_dns_dnspromisesresolvemxhostname">#</a></span><a aria-hidden="true" class="legacy" id="dns_dnspromises_resolvemx_hostname"></a></h4>
<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>
<h4><code>dnsPromises.resolveNaptr(hostname)</code><span><a class="mark" href="#all_dns_dnspromisesresolvenaptrhostname" id="all_dns_dnspromisesresolvenaptrhostname">#</a></span><a aria-hidden="true" class="legacy" id="dns_dnspromises_resolvenaptr_hostname"></a></h4>
<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">{
  <span class="hljs-attr">flags</span>: <span class="hljs-string">'s'</span>,
  <span class="hljs-attr">service</span>: <span class="hljs-string">'SIP+D2U'</span>,
  <span class="hljs-attr">regexp</span>: <span class="hljs-string">''</span>,
  <span class="hljs-attr">replacement</span>: <span class="hljs-string">'_sip._udp.example.com'</span>,
  <span class="hljs-attr">order</span>: <span class="hljs-number">30</span>,
  <span class="hljs-attr">preference</span>: <span class="hljs-number">100</span>
}</code> <button class="copy-button">copy</button></pre>
<h4><code>dnsPromises.resolveNs(hostname)</code><span><a class="mark" href="#all_dns_dnspromisesresolvenshostname" id="all_dns_dnspromisesresolvenshostname">#</a></span><a aria-hidden="true" class="legacy" id="dns_dnspromises_resolvens_hostname"></a></h4>
<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>
<h4><code>dnsPromises.resolvePtr(hostname)</code><span><a class="mark" href="#all_dns_dnspromisesresolveptrhostname" id="all_dns_dnspromisesresolveptrhostname">#</a></span><a aria-hidden="true" class="legacy" id="dns_dnspromises_resolveptr_hostname"></a></h4>
<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>
<h4><code>dnsPromises.resolveSoa(hostname)</code><span><a class="mark" href="#all_dns_dnspromisesresolvesoahostname" id="all_dns_dnspromisesresolvesoahostname">#</a></span><a aria-hidden="true" class="legacy" id="dns_dnspromises_resolvesoa_hostname"></a></h4>
<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">{
  <span class="hljs-attr">nsname</span>: <span class="hljs-string">'ns.example.com'</span>,
  <span class="hljs-attr">hostmaster</span>: <span class="hljs-string">'root.example.com'</span>,
  <span class="hljs-attr">serial</span>: <span class="hljs-number">2013101809</span>,
  <span class="hljs-attr">refresh</span>: <span class="hljs-number">10000</span>,
  <span class="hljs-attr">retry</span>: <span class="hljs-number">2400</span>,
  <span class="hljs-attr">expire</span>: <span class="hljs-number">604800</span>,
  <span class="hljs-attr">minttl</span>: <span class="hljs-number">3600</span>
}</code> <button class="copy-button">copy</button></pre>
<h4><code>dnsPromises.resolveSrv(hostname)</code><span><a class="mark" href="#all_dns_dnspromisesresolvesrvhostname" id="all_dns_dnspromisesresolvesrvhostname">#</a></span><a aria-hidden="true" class="legacy" id="dns_dnspromises_resolvesrv_hostname"></a></h4>
<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">{
  <span class="hljs-attr">priority</span>: <span class="hljs-number">10</span>,
  <span class="hljs-attr">weight</span>: <span class="hljs-number">5</span>,
  <span class="hljs-attr">port</span>: <span class="hljs-number">21223</span>,
  <span class="hljs-attr">name</span>: <span class="hljs-string">'service.example.com'</span>
}</code> <button class="copy-button">copy</button></pre>
<h4><code>dnsPromises.resolveTxt(hostname)</code><span><a class="mark" href="#all_dns_dnspromisesresolvetxthostname" id="all_dns_dnspromisesresolvetxthostname">#</a></span><a aria-hidden="true" class="legacy" id="dns_dnspromises_resolvetxt_hostname"></a></h4>
<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>
<h4><code>dnsPromises.reverse(ip)</code><span><a class="mark" href="#all_dns_dnspromisesreverseip" id="all_dns_dnspromisesreverseip">#</a></span><a aria-hidden="true" class="legacy" id="dns_dnspromises_reverse_ip"></a></h4>
<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="#all_errors_class-error"><code>Error</code></a> object, where <code>err.code</code>
is one of the <a href="#all_dns_error-codes">DNS error codes</a>.</p>
<h4><code>dnsPromises.setDefaultResultOrder(order)</code><span><a class="mark" href="#all_dns_dnspromisessetdefaultresultorderorder" id="all_dns_dnspromisessetdefaultresultorderorder">#</a></span><a aria-hidden="true" class="legacy" id="dns_dnspromises_setdefaultresultorder_order"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.13.0</td>
<td><p>The <code>ipv6first</code> value is supported now.</p></td></tr>
<tr><td>v17.0.0</td>
<td><p>Changed default value to <code>verbatim</code>.</p></td></tr>
<tr><td>v16.4.0, v14.18.0</td>
<td><p><span>Added in: v16.4.0, v14.18.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>order</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> must be <code>'ipv4first'</code>, <code>'ipv6first'</code> or <code>'verbatim'</code>.</li>
</ul>
<p>Set the default value of <code>order</code> in <a href="#all_dns_dnslookuphostname-options-callback"><code>dns.lookup()</code></a> and
<a href="#all_dns_dnspromiseslookuphostname-options"><code>dnsPromises.lookup()</code></a>. The value could be:</p>
<ul>
<li><code>ipv4first</code>: sets default <code>order</code> to <code>ipv4first</code>.</li>
<li><code>ipv6first</code>: sets default <code>order</code> to <code>ipv6first</code>.</li>
<li><code>verbatim</code>: sets default <code>order</code> to <code>verbatim</code>.</li>
</ul>
<p>The default is <code>verbatim</code> and <a href="#all_dns_dnspromisessetdefaultresultorderorder"><code>dnsPromises.setDefaultResultOrder()</code></a> have
higher priority than <a href="#all_cli_--dns-result-orderorder"><code>--dns-result-order</code></a>. When using <a href="worker_threads.html">worker threads</a>,
<a href="#all_dns_dnspromisessetdefaultresultorderorder"><code>dnsPromises.setDefaultResultOrder()</code></a> from the main thread won't affect the
default dns orders in workers.</p>
<h4><code>dnsPromises.getDefaultResultOrder()</code><span><a class="mark" href="#all_dns_dnspromisesgetdefaultresultorder" id="all_dns_dnspromisesgetdefaultresultorder">#</a></span><a aria-hidden="true" class="legacy" id="dns_dnspromises_getdefaultresultorder"></a></h4>
<div class="api_metadata">
<span>Added in: v20.1.0</span>
</div>
<p>Get the value of <code>dnsOrder</code>.</p>
<h4><code>dnsPromises.setServers(servers)</code><span><a class="mark" href="#all_dns_dnspromisessetserversservers" id="all_dns_dnspromisessetserversservers">#</a></span><a aria-hidden="true" class="legacy" id="dns_dnspromises_setservers_servers"></a></h4>
<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.<span class="hljs-title function_">setServers</span>([
  <span class="hljs-string">'8.8.8.8'</span>,
  <span class="hljs-string">'[2001:4860:4860::8888]'</span>,
  <span class="hljs-string">'8.8.8.8:1053'</span>,
  <span class="hljs-string">'[2001:4860:4860::8888]:1053'</span>,
]);</code> <button class="copy-button">copy</button></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="https://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>
</section><section><h3>Error codes<span><a class="mark" href="#all_dns_error-codes" id="all_dns_error-codes">#</a></span><a aria-hidden="true" class="legacy" id="dns_error_codes"></a></h3>
<p>Each DNS query can return one of the following error codes:</p>
<ul>
<li><code>dns.NODATA</code>: DNS server returned an 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 the 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>
<p>The <code>dnsPromises</code> API also exports the above error codes, e.g., <code>dnsPromises.NODATA</code>.</p>
</section><section><h3>Implementation considerations<span><a class="mark" href="#all_dns_implementation-considerations" id="all_dns_implementation-considerations">#</a></span><a aria-hidden="true" class="legacy" id="dns_implementation_considerations"></a></h3>
<p>Although <a href="#all_dns_dnslookuphostname-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>
<h4><code>dns.lookup()</code><span><a class="mark" href="#all_dns_dnslookup" id="all_dns_dnslookup">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_lookup"></a></h4>
<p>Under the hood, <a href="#all_dns_dnslookuphostname-options-callback"><code>dns.lookup()</code></a> uses the same operating system facilities
as most other programs. For instance, <a href="#all_dns_dnslookuphostname-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="#all_dns_dnslookuphostname-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="#all_cli_uv_threadpool_sizesize"><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="#all_net_socketconnectoptions-connectlistener"><code>socket.connect()</code></a> and <a href="#all_dgram_dgramcreatesocketoptions-callback"><code>dgram.createSocket()</code></a>)
allow the default resolver, <code>dns.lookup()</code>, to be replaced.</p>
<h4><code>dns.resolve()</code>, <code>dns.resolve*()</code>, and <code>dns.reverse()</code><span><a class="mark" href="#all_dns_dnsresolve-dnsresolve-and-dnsreverse" id="all_dns_dnsresolve-dnsresolve-and-dnsreverse">#</a></span><a aria-hidden="true" class="legacy" id="dns_dns_resolve_dns_resolve_and_dns_reverse"></a></h4>
<p>These functions are implemented quite differently than <a href="#all_dns_dnslookuphostname-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="#all_dns_dnslookuphostname-options-callback"><code>dns.lookup()</code></a> can have.</p>
<p>They do not use the same set of configuration files that <a href="#all_dns_dnslookuphostname-options-callback"><code>dns.lookup()</code></a>
uses. For instance, they do not use the configuration from <code>/etc/hosts</code>.</p></section>
        </section>
<section><h2>Domain<span><a class="mark" href="#all_domain_domain" id="all_domain_domain">#</a></span><a aria-hidden="true" class="legacy" id="domain_domain"></a></h2>
<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>
<tr><td>v1.4.2</td>
<td><p><span>Deprecated since: v1.4.2</span></p></td></tr>
</tbody></table>
</details>
</div>

<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/domain.js">lib/domain.js</a></p>
<p><strong>This module is pending deprecation.</strong> Once a replacement API has been
finalized, this module will be fully deprecated. Most developers 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>
<section><h3>Warning: Don't ignore errors!<span><a class="mark" href="#all_domain_warning-dont-ignore-errors" id="all_domain_warning-dont-ignore-errors">#</a></span><a aria-hidden="true" class="legacy" id="domain_warning_don_t_ignore_errors"></a></h3>

<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 primary 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"><span class="hljs-comment">// XXX WARNING! BAD IDEA!</span>

<span class="hljs-keyword">const</span> d = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:domain'</span>).<span class="hljs-title function_">create</span>();
d.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">er</span>) =></span> {
  <span class="hljs-comment">// The error won't crash the process, but what it does is worse!</span>
  <span class="hljs-comment">// Though we've prevented abrupt process restarting, we are leaking</span>
  <span class="hljs-comment">// a lot of resources if this ever happens.</span>
  <span class="hljs-comment">// This is no better than process.on('uncaughtException')!</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`error, but oh well <span class="hljs-subst">${er.message}</span>`</span>);
});
d.<span class="hljs-title function_">run</span>(<span class="hljs-function">() =></span> {
  <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>).<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
    <span class="hljs-title function_">handleRequest</span>(req, res);
  }).<span class="hljs-title function_">listen</span>(<span class="hljs-variable constant_">PORT</span>);
});</code> <button class="copy-button">copy</button></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"><span class="hljs-comment">// Much better!</span>

<span class="hljs-keyword">const</span> cluster = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:cluster'</span>);
<span class="hljs-keyword">const</span> <span class="hljs-variable constant_">PORT</span> = +process.<span class="hljs-property">env</span>.<span class="hljs-property">PORT</span> || <span class="hljs-number">1337</span>;

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

  cluster.<span class="hljs-title function_">fork</span>();
  cluster.<span class="hljs-title function_">fork</span>();

  cluster.<span class="hljs-title function_">on</span>(<span class="hljs-string">'disconnect'</span>, <span class="hljs-function">(<span class="hljs-params">worker</span>) =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'disconnect!'</span>);
    cluster.<span class="hljs-title function_">fork</span>();
  });

} <span class="hljs-keyword">else</span> {
  <span class="hljs-comment">// the worker</span>
  <span class="hljs-comment">//</span>
  <span class="hljs-comment">// This is where we put our bugs!</span>

  <span class="hljs-keyword">const</span> domain = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:domain'</span>);

  <span class="hljs-comment">// See the cluster documentation for more details about using</span>
  <span class="hljs-comment">// worker processes to serve requests. How it works, caveats, etc.</span>

  <span class="hljs-keyword">const</span> server = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>).<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
    <span class="hljs-keyword">const</span> d = domain.<span class="hljs-title function_">create</span>();
    d.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">er</span>) =></span> {
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`error <span class="hljs-subst">${er.stack}</span>`</span>);

      <span class="hljs-comment">// We're in dangerous territory!</span>
      <span class="hljs-comment">// By definition, something unexpected occurred,</span>
      <span class="hljs-comment">// which we probably didn't want.</span>
      <span class="hljs-comment">// Anything can happen now! Be very careful!</span>

      <span class="hljs-keyword">try</span> {
        <span class="hljs-comment">// Make sure we close down within 30 seconds</span>
        <span class="hljs-keyword">const</span> killtimer = <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
          process.<span class="hljs-title function_">exit</span>(<span class="hljs-number">1</span>);
        }, <span class="hljs-number">30000</span>);
        <span class="hljs-comment">// But don't keep the process open just for that!</span>
        killtimer.<span class="hljs-title function_">unref</span>();

        <span class="hljs-comment">// Stop taking new requests.</span>
        server.<span class="hljs-title function_">close</span>();

        <span class="hljs-comment">// Let the primary know we're dead. This will trigger a</span>
        <span class="hljs-comment">// 'disconnect' in the cluster primary, and then it will fork</span>
        <span class="hljs-comment">// a new worker.</span>
        cluster.<span class="hljs-property">worker</span>.<span class="hljs-title function_">disconnect</span>();

        <span class="hljs-comment">// Try to send an error to the request that triggered the problem</span>
        res.<span class="hljs-property">statusCode</span> = <span class="hljs-number">500</span>;
        res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'content-type'</span>, <span class="hljs-string">'text/plain'</span>);
        res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'Oops, there was a problem!\n'</span>);
      } <span class="hljs-keyword">catch</span> (er2) {
        <span class="hljs-comment">// Oh well, not much we can do at this point.</span>
        <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`Error sending 500! <span class="hljs-subst">${er2.stack}</span>`</span>);
      }
    });

    <span class="hljs-comment">// Because req and res were created before this domain existed,</span>
    <span class="hljs-comment">// we need to explicitly add them.</span>
    <span class="hljs-comment">// See the explanation of implicit vs explicit binding below.</span>
    d.<span class="hljs-title function_">add</span>(req);
    d.<span class="hljs-title function_">add</span>(res);

    <span class="hljs-comment">// Now run the handler function in the domain.</span>
    d.<span class="hljs-title function_">run</span>(<span class="hljs-function">() =></span> {
      <span class="hljs-title function_">handleRequest</span>(req, res);
    });
  });
  server.<span class="hljs-title function_">listen</span>(<span class="hljs-variable constant_">PORT</span>);
}

<span class="hljs-comment">// This part is not important. Just an example routing thing.</span>
<span class="hljs-comment">// Put fancy application logic here.</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">handleRequest</span>(<span class="hljs-params">req, res</span>) {
  <span class="hljs-keyword">switch</span> (req.<span class="hljs-property">url</span>) {
    <span class="hljs-keyword">case</span> <span class="hljs-string">'/error'</span>:
      <span class="hljs-comment">// We do some async stuff, and then...</span>
      <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
        <span class="hljs-comment">// Whoops!</span>
        flerb.<span class="hljs-title function_">bark</span>();
      }, timeout);
      <span class="hljs-keyword">break</span>;
    <span class="hljs-attr">default</span>:
      res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'ok'</span>);
  }
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Additions to <code>Error</code> objects<span><a class="mark" href="#all_domain_additions-to-error-objects" id="all_domain_additions-to-error-objects">#</a></span><a aria-hidden="true" class="legacy" id="domain_additions_to_error_objects"></a></h3>

<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>
</section><section><h3>Implicit binding<span><a class="mark" href="#all_domain_implicit-binding" id="all_domain_implicit-binding">#</a></span><a aria-hidden="true" class="legacy" id="domain_implicit_binding"></a></h3>

<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 low-level 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>
</section><section><h3>Explicit binding<span><a class="mark" href="#all_domain_explicit-binding" id="all_domain_explicit-binding">#</a></span><a aria-hidden="true" class="legacy" id="domain_explicit_binding"></a></h3>

<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"><span class="hljs-comment">// Create a top-level domain for the server</span>
<span class="hljs-keyword">const</span> domain = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:domain'</span>);
<span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);
<span class="hljs-keyword">const</span> serverDomain = domain.<span class="hljs-title function_">create</span>();

serverDomain.<span class="hljs-title function_">run</span>(<span class="hljs-function">() =></span> {
  <span class="hljs-comment">// Server is created in the scope of serverDomain</span>
  http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
    <span class="hljs-comment">// Req and res are also created in the scope of serverDomain</span>
    <span class="hljs-comment">// however, we'd prefer to have a separate domain for each request.</span>
    <span class="hljs-comment">// create it first thing, and add req and res to it.</span>
    <span class="hljs-keyword">const</span> reqd = domain.<span class="hljs-title function_">create</span>();
    reqd.<span class="hljs-title function_">add</span>(req);
    reqd.<span class="hljs-title function_">add</span>(res);
    reqd.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">er</span>) =></span> {
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'Error'</span>, er, req.<span class="hljs-property">url</span>);
      <span class="hljs-keyword">try</span> {
        res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">500</span>);
        res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'Error occurred, sorry.'</span>);
      } <span class="hljs-keyword">catch</span> (er2) {
        <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'Error sending 500'</span>, er2, req.<span class="hljs-property">url</span>);
      }
    });
  }).<span class="hljs-title function_">listen</span>(<span class="hljs-number">1337</span>);
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>domain.create()</code><span><a class="mark" href="#all_domain_domaincreate" id="all_domain_domaincreate">#</a></span><a aria-hidden="true" class="legacy" id="domain_domain_create"></a></h3>
<ul>
<li>Returns: <a href="#all_domain_class-domain" class="type">&#x3C;Domain></a></li>
</ul>
</section><section><h3>Class: <code>Domain</code><span><a class="mark" href="#all_domain_class-domain" id="all_domain_class-domain">#</a></span><a aria-hidden="true" class="legacy" id="domain_class_domain"></a></h3>
<ul>
<li>Extends: <a href="#all_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>
<h4><code>domain.members</code><span><a class="mark" href="#all_domain_domainmembers" id="all_domain_domainmembers">#</a></span><a aria-hidden="true" class="legacy" id="domain_domain_members"></a></h4>
<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>
<h4><code>domain.add(emitter)</code><span><a class="mark" href="#all_domain_domainaddemitter" id="all_domain_domainaddemitter">#</a></span><a aria-hidden="true" class="legacy" id="domain_domain_add_emitter"></a></h4>
<ul>
<li><code>emitter</code> <a href="#all_events_class-eventemitter" class="type">&#x3C;EventEmitter></a> | <a href="#all_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="#all_timers_setintervalcallback-delay-args"><code>setInterval()</code></a> and
<a href="#all_timers_settimeoutcallback-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>
<h4><code>domain.bind(callback)</code><span><a class="mark" href="#all_domain_domainbindcallback" id="all_domain_domainbindcallback">#</a></span><a aria-hidden="true" class="legacy" id="domain_domain_bind_callback"></a></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> 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"><span class="hljs-keyword">const</span> d = domain.<span class="hljs-title function_">create</span>();

<span class="hljs-keyword">function</span> <span class="hljs-title function_">readSomeFile</span>(<span class="hljs-params">filename, cb</span>) {
  fs.<span class="hljs-title function_">readFile</span>(filename, <span class="hljs-string">'utf8'</span>, d.<span class="hljs-title function_">bind</span>(<span class="hljs-function">(<span class="hljs-params">er, data</span>) =></span> {
    <span class="hljs-comment">// If this throws, it will also be passed to the domain.</span>
    <span class="hljs-keyword">return</span> <span class="hljs-title function_">cb</span>(er, data ? <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(data) : <span class="hljs-literal">null</span>);
  }));
}

d.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">er</span>) =></span> {
  <span class="hljs-comment">// An error occurred somewhere. If we throw it now, it will crash the program</span>
  <span class="hljs-comment">// with the normal line number and stack message.</span>
});</code> <button class="copy-button">copy</button></pre>
<h4><code>domain.enter()</code><span><a class="mark" href="#all_domain_domainenter" id="all_domain_domainenter">#</a></span><a aria-hidden="true" class="legacy" id="domain_domain_enter"></a></h4>
<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="#all_domain_domainexit"><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>
<h4><code>domain.exit()</code><span><a class="mark" href="#all_domain_domainexit" id="all_domain_domainexit">#</a></span><a aria-hidden="true" class="legacy" id="domain_domain_exit"></a></h4>
<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>
<h4><code>domain.intercept(callback)</code><span><a class="mark" href="#all_domain_domaininterceptcallback" id="all_domain_domaininterceptcallback">#</a></span><a aria-hidden="true" class="legacy" id="domain_domain_intercept_callback"></a></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> 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="#all_domain_domainbindcallback"><code>domain.bind(callback)</code></a>. However, in
addition to catching thrown errors, it will also intercept <a href="#all_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"><span class="hljs-keyword">const</span> d = domain.<span class="hljs-title function_">create</span>();

<span class="hljs-keyword">function</span> <span class="hljs-title function_">readSomeFile</span>(<span class="hljs-params">filename, cb</span>) {
  fs.<span class="hljs-title function_">readFile</span>(filename, <span class="hljs-string">'utf8'</span>, d.<span class="hljs-title function_">intercept</span>(<span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
    <span class="hljs-comment">// Note, the first argument is never passed to the</span>
    <span class="hljs-comment">// callback since it is assumed to be the 'Error' argument</span>
    <span class="hljs-comment">// and thus intercepted by the domain.</span>

    <span class="hljs-comment">// If this throws, it will also be passed to the domain</span>
    <span class="hljs-comment">// so the error-handling logic can be moved to the 'error'</span>
    <span class="hljs-comment">// event on the domain instead of being repeated throughout</span>
    <span class="hljs-comment">// the program.</span>
    <span class="hljs-keyword">return</span> <span class="hljs-title function_">cb</span>(<span class="hljs-literal">null</span>, <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(data));
  }));
}

d.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">er</span>) =></span> {
  <span class="hljs-comment">// An error occurred somewhere. If we throw it now, it will crash the program</span>
  <span class="hljs-comment">// with the normal line number and stack message.</span>
});</code> <button class="copy-button">copy</button></pre>
<h4><code>domain.remove(emitter)</code><span><a class="mark" href="#all_domain_domainremoveemitter" id="all_domain_domainremoveemitter">#</a></span><a aria-hidden="true" class="legacy" id="domain_domain_remove_emitter"></a></h4>
<ul>
<li><code>emitter</code> <a href="#all_events_class-eventemitter" class="type">&#x3C;EventEmitter></a> | <a href="#all_timers_timers" class="type">&#x3C;Timer></a> emitter or timer to be removed from the domain</li>
</ul>
<p>The opposite of <a href="#all_domain_domainaddemitter"><code>domain.add(emitter)</code></a>. Removes domain handling from the
specified emitter.</p>
<h4><code>domain.run(fn[, ...args])</code><span><a class="mark" href="#all_domain_domainrunfn-args" id="all_domain_domainrunfn-args">#</a></span><a aria-hidden="true" class="legacy" id="domain_domain_run_fn_args"></a></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></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 low-level 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"><span class="hljs-keyword">const</span> domain = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:domain'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> d = domain.<span class="hljs-title function_">create</span>();
d.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">er</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'Caught error!'</span>, er);
});
d.<span class="hljs-title function_">run</span>(<span class="hljs-function">() =></span> {
  process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> {
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> { <span class="hljs-comment">// Simulating some various async stuff</span>
      fs.<span class="hljs-title function_">open</span>(<span class="hljs-string">'non-existent file'</span>, <span class="hljs-string">'r'</span>, <span class="hljs-function">(<span class="hljs-params">er, fd</span>) =></span> {
        <span class="hljs-keyword">if</span> (er) <span class="hljs-keyword">throw</span> er;
        <span class="hljs-comment">// proceed...</span>
      });
    }, <span class="hljs-number">100</span>);
  });
});</code> <button class="copy-button">copy</button></pre>
<p>In this example, the <code>d.on('error')</code> handler will be triggered, rather
than crashing the program.</p>
</section><section><h3>Domains and promises<span><a class="mark" href="#all_domain_domains-and-promises" id="all_domain_domains-and-promises">#</a></span><a aria-hidden="true" class="legacy" id="domain_domains_and_promises"></a></h3>
<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"><span class="hljs-keyword">const</span> d1 = domain.<span class="hljs-title function_">create</span>();
<span class="hljs-keyword">const</span> d2 = domain.<span class="hljs-title function_">create</span>();

<span class="hljs-keyword">let</span> p;
d1.<span class="hljs-title function_">run</span>(<span class="hljs-function">() =></span> {
  p = <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">resolve</span>(<span class="hljs-number">42</span>);
});

d2.<span class="hljs-title function_">run</span>(<span class="hljs-function">() =></span> {
  p.<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">v</span>) =></span> {
    <span class="hljs-comment">// running in d2</span>
  });
});</code> <button class="copy-button">copy</button></pre>
<p>A callback may be bound to a specific domain using <a href="#all_domain_domainbindcallback"><code>domain.bind(callback)</code></a>:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> d1 = domain.<span class="hljs-title function_">create</span>();
<span class="hljs-keyword">const</span> d2 = domain.<span class="hljs-title function_">create</span>();

<span class="hljs-keyword">let</span> p;
d1.<span class="hljs-title function_">run</span>(<span class="hljs-function">() =></span> {
  p = <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">resolve</span>(<span class="hljs-number">42</span>);
});

d2.<span class="hljs-title function_">run</span>(<span class="hljs-function">() =></span> {
  p.<span class="hljs-title function_">then</span>(p.<span class="hljs-property">domain</span>.<span class="hljs-title function_">bind</span>(<span class="hljs-function">(<span class="hljs-params">v</span>) =></span> {
    <span class="hljs-comment">// running in d1</span>
  }));
});</code> <button class="copy-button">copy</button></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></section>
        </section>
<section><h2>Errors<span><a class="mark" href="#all_errors_errors" id="all_errors_errors">#</a></span><a aria-hidden="true" class="legacy" id="errors_errors"></a></h2>


<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>node: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>
<section><h3>Error propagation and interception<span><a class="mark" href="#all_errors_error-propagation-and-interception" id="all_errors_error-propagation-and-interception">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_propagation_and_interception"></a></h3>

<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"><span class="hljs-comment">// Throws with a ReferenceError because z is not defined.</span>
<span class="hljs-keyword">try</span> {
  <span class="hljs-keyword">const</span> m = <span class="hljs-number">1</span>;
  <span class="hljs-keyword">const</span> n = m + z;
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-comment">// Handle the error here.</span>
}</code> <button class="copy-button">copy</button></pre>
<p>Any use of the JavaScript <code>throw</code> mechanism will raise an exception that
<em>must</em> be handled or the Node.js process will exit immediately.</p>
<p>With few exceptions, <em>Synchronous</em> APIs (any blocking method that does not
return a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> nor accept a <code>callback</code> function, such as
<a href="#all_fs_fsreadfilesyncpath-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>
<p>Some asynchronous methods returns a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a>, you should always take into
account that it might be rejected. See <a href="#all_cli_--unhandled-rejectionsmode"><code>--unhandled-rejections</code></a> flag for
how the process will react to an unhandled promise rejection.</p>
<!-- eslint-disable no-useless-return -->
<pre><code class="language-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs/promises'</span>);

(<span class="hljs-keyword">async</span> () => {
  <span class="hljs-keyword">let</span> data;
  <span class="hljs-keyword">try</span> {
    data = <span class="hljs-keyword">await</span> fs.<span class="hljs-title function_">readFile</span>(<span class="hljs-string">'a file that does not exist'</span>);
  } <span class="hljs-keyword">catch</span> (err) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'There was an error reading the file!'</span>, err);
    <span class="hljs-keyword">return</span>;
  }
  <span class="hljs-comment">// Otherwise handle the data</span>
})();</code> <button class="copy-button">copy</button></pre>
</li>
<li>
<p>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.</p>
<!-- eslint-disable no-useless-return -->
<pre><code class="language-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
fs.<span class="hljs-title function_">readFile</span>(<span class="hljs-string">'a file that does not exist'</span>, <span class="hljs-function">(<span class="hljs-params">err, data</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'There was an error reading the file!'</span>, err);
    <span class="hljs-keyword">return</span>;
  }
  <span class="hljs-comment">// Otherwise handle the data</span>
});</code> <button class="copy-button">copy</button></pre>
</li>
<li>
<p>When an asynchronous method is called on an object that is an
<a href="#all_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"><span class="hljs-keyword">const</span> net = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:net'</span>);
<span class="hljs-keyword">const</span> connection = net.<span class="hljs-title function_">connect</span>(<span class="hljs-string">'localhost'</span>);

<span class="hljs-comment">// Adding an 'error' event handler to a stream:</span>
connection.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-comment">// If the connection is reset by the server, or if it can't</span>
  <span class="hljs-comment">// connect at all, or on any sort of error encountered by</span>
  <span class="hljs-comment">// the connection, the error will be sent here.</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err);
});

connection.<span class="hljs-title function_">pipe</span>(process.<span class="hljs-property">stdout</span>);</code> <button class="copy-button">copy</button></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="#all_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="#all_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: a handler has been registered for
the <a href="#all_process_event-uncaughtexception"><code>'uncaughtException'</code></a> event, or the deprecated <a href="domain.html"><code>node:domain</code></a>
module is used.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();

<span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></span> {
  <span class="hljs-comment">// This will crash the process because no 'error' event</span>
  <span class="hljs-comment">// handler has been added.</span>
  ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'error'</span>, <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'This will crash'</span>));
});</code> <button class="copy-button">copy</button></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>
</section><section><h3>Class: <code>Error</code><span><a class="mark" href="#all_errors_class-error" id="all_errors_class-error">#</a></span><a aria-hidden="true" class="legacy" id="errors_class_error"></a></h3>

<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>
<h4><code>new Error(message[, options])</code><span><a class="mark" href="#all_errors_new-errormessage-options" id="all_errors_new-errormessage-options">#</a></span><a aria-hidden="true" class="legacy" id="errors_new_error_message_options"></a></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>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>cause</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> The error that caused the newly created error.</li>
</ul>
</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>String(message)</code>. If the <code>cause</code> option is provided,
it is assigned to the <code>error.cause</code> property. 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://v8.dev/docs/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>
<h4><code>Error.captureStackTrace(targetObject[, constructorOpt])</code><span><a class="mark" href="#all_errors_errorcapturestacktracetargetobject-constructoropt" id="all_errors_errorcapturestacktracetargetobject-constructoropt">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_capturestacktrace_targetobject_constructoropt"></a></h4>
<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"><span class="hljs-keyword">const</span> myObject = {};
<span class="hljs-title class_">Error</span>.<span class="hljs-title function_">captureStackTrace</span>(myObject);
myObject.<span class="hljs-property">stack</span>;  <span class="hljs-comment">// Similar to `new Error().stack`</span></code> <button class="copy-button">copy</button></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 the user. For instance:</p>
<pre><code class="language-js"><span class="hljs-keyword">function</span> <span class="hljs-title function_">a</span>(<span class="hljs-params"></span>) {
  <span class="hljs-title function_">b</span>();
}

<span class="hljs-keyword">function</span> <span class="hljs-title function_">b</span>(<span class="hljs-params"></span>) {
  <span class="hljs-title function_">c</span>();
}

<span class="hljs-keyword">function</span> <span class="hljs-title function_">c</span>(<span class="hljs-params"></span>) {
  <span class="hljs-comment">// Create an error without stack trace to avoid calculating the stack trace twice.</span>
  <span class="hljs-keyword">const</span> { stackTraceLimit } = <span class="hljs-title class_">Error</span>;
  <span class="hljs-title class_">Error</span>.<span class="hljs-property">stackTraceLimit</span> = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">const</span> error = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>();
  <span class="hljs-title class_">Error</span>.<span class="hljs-property">stackTraceLimit</span> = stackTraceLimit;

  <span class="hljs-comment">// Capture the stack trace above function b</span>
  <span class="hljs-title class_">Error</span>.<span class="hljs-title function_">captureStackTrace</span>(error, b); <span class="hljs-comment">// Neither function c, nor b is included in the stack trace</span>
  <span class="hljs-keyword">throw</span> error;
}

<span class="hljs-title function_">a</span>();</code> <button class="copy-button">copy</button></pre>
<h4><code>Error.stackTraceLimit</code><span><a class="mark" href="#all_errors_errorstacktracelimit" id="all_errors_errorstacktracelimit">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_stacktracelimit"></a></h4>
<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>
<h4><code>error.cause</code><span><a class="mark" href="#all_errors_errorcause" id="all_errors_errorcause">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_cause"></a></h4>
<div class="api_metadata">
<span>Added in: v16.9.0</span>
</div>
<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 present, the <code>error.cause</code> property is the underlying cause of the <code>Error</code>.
It is used when catching an error and throwing a new one with a different
message or code in order to still have access to the original error.</p>
<p>The <code>error.cause</code> property is typically set by calling
<code>new Error(message, { cause })</code>. It is not set by the constructor if the
<code>cause</code> option is not provided.</p>
<p>This property allows errors to be chained. When serializing <code>Error</code> objects,
<a href="#all_util_utilinspectobject-options"><code>util.inspect()</code></a> recursively serializes <code>error.cause</code> if it is set.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> cause = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'The remote HTTP server responded with a 500 status'</span>);
<span class="hljs-keyword">const</span> symptom = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'The message failed to send'</span>, { cause });

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(symptom);
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   Error: The message failed to send</span>
<span class="hljs-comment">//       at REPL2:1:17</span>
<span class="hljs-comment">//       at Script.runInThisContext (node:vm:130:12)</span>
<span class="hljs-comment">//       ... 7 lines matching cause stack trace ...</span>
<span class="hljs-comment">//       at [_line] [as _line] (node:internal/readline/interface:886:18) {</span>
<span class="hljs-comment">//     [cause]: Error: The remote HTTP server responded with a 500 status</span>
<span class="hljs-comment">//         at REPL1:1:15</span>
<span class="hljs-comment">//         at Script.runInThisContext (node:vm:130:12)</span>
<span class="hljs-comment">//         at REPLServer.defaultEval (node:repl:574:29)</span>
<span class="hljs-comment">//         at bound (node:domain:426:15)</span>
<span class="hljs-comment">//         at REPLServer.runBound [as eval] (node:domain:437:12)</span>
<span class="hljs-comment">//         at REPLServer.onLine (node:repl:902:10)</span>
<span class="hljs-comment">//         at REPLServer.emit (node:events:549:35)</span>
<span class="hljs-comment">//         at REPLServer.emit (node:domain:482:12)</span>
<span class="hljs-comment">//         at [_onLine] [as _onLine] (node:internal/readline/interface:425:12)</span>
<span class="hljs-comment">//         at [_line] [as _line] (node:internal/readline/interface:886:18)</span></code> <button class="copy-button">copy</button></pre>
<h4><code>error.code</code><span><a class="mark" href="#all_errors_errorcode" id="all_errors_errorcode">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_code"></a></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>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="#all_errors_nodejs-error-codes">Node.js error codes</a> for details
about specific codes.</p>
<h4><code>error.message</code><span><a class="mark" href="#all_errors_errormessage" id="all_errors_errormessage">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_message"></a></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>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"><span class="hljs-keyword">const</span> err = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'The message'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err.<span class="hljs-property">message</span>);
<span class="hljs-comment">// Prints: The message</span></code> <button class="copy-button">copy</button></pre>
<h4><code>error.stack</code><span><a class="mark" href="#all_errors_errorstack" id="all_errors_errorstack">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_stack"></a></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>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> <button class="copy-button">copy</button></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"><span class="hljs-keyword">const</span> cheetahify = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./native-binding.node'</span>);

<span class="hljs-keyword">function</span> <span class="hljs-title function_">makeFaster</span>(<span class="hljs-params"></span>) {
  <span class="hljs-comment">// `cheetahify()` *synchronously* calls speedy.</span>
  <span class="hljs-title function_">cheetahify</span>(<span class="hljs-keyword">function</span> <span class="hljs-title function_">speedy</span>(<span class="hljs-params"></span>) {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'oh no!'</span>);
  });
}

<span class="hljs-title function_">makeFaster</span>();
<span class="hljs-comment">// will throw:</span>
<span class="hljs-comment">//   /home/gbusey/file.js:6</span>
<span class="hljs-comment">//       throw new Error('oh no!');</span>
<span class="hljs-comment">//           ^</span>
<span class="hljs-comment">//   Error: oh no!</span>
<span class="hljs-comment">//       at speedy (/home/gbusey/file.js:6:11)</span>
<span class="hljs-comment">//       at makeFaster (/home/gbusey/file.js:5:3)</span>
<span class="hljs-comment">//       at Object.&#x3C;anonymous> (/home/gbusey/file.js:10:1)</span>
<span class="hljs-comment">//       at Module._compile (module.js:456:26)</span>
<span class="hljs-comment">//       at Object.Module._extensions..js (module.js:474:10)</span>
<span class="hljs-comment">//       at Module.load (module.js:356:32)</span>
<span class="hljs-comment">//       at Function.Module._load (module.js:312:12)</span>
<span class="hljs-comment">//       at Function.Module.runMain (module.js:497:10)</span>
<span class="hljs-comment">//       at startup (node.js:119:16)</span>
<span class="hljs-comment">//       at node.js:906:3</span></code> <button class="copy-button">copy</button></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 (using CommonJS module system), or its dependencies.</li>
<li><code>&#x3C;transport-protocol>:///url/to/module/file.mjs:line:column</code>, if the frame
represents a call in a user program (using ES module system), 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>
</section><section><h3>Class: <code>AssertionError</code><span><a class="mark" href="#all_errors_class-assertionerror" id="all_errors_class-assertionerror">#</a></span><a aria-hidden="true" class="legacy" id="errors_class_assertionerror"></a></h3>
<ul>
<li>Extends: <a href="#all_errors_class-error" class="type">&#x3C;errors.Error></a></li>
</ul>
<p>Indicates the failure of an assertion. For details, see
<a href="#all_assert_class-assertassertionerror"><code>Class: assert.AssertionError</code></a>.</p>
</section><section><h3>Class: <code>RangeError</code><span><a class="mark" href="#all_errors_class-rangeerror" id="all_errors_class-rangeerror">#</a></span><a aria-hidden="true" class="legacy" id="errors_class_rangeerror"></a></h3>
<ul>
<li>Extends: <a href="#all_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"><span class="hljs-built_in">require</span>(<span class="hljs-string">'node:net'</span>).<span class="hljs-title function_">connect</span>(-<span class="hljs-number">1</span>);
<span class="hljs-comment">// Throws "RangeError: "port" option should be >= 0 and &#x3C; 65536: -1"</span></code> <button class="copy-button">copy</button></pre>
<p>Node.js will generate and throw <code>RangeError</code> instances <em>immediately</em> as a form
of argument validation.</p>
</section><section><h3>Class: <code>ReferenceError</code><span><a class="mark" href="#all_errors_class-referenceerror" id="all_errors_class-referenceerror">#</a></span><a aria-hidden="true" class="legacy" id="errors_class_referenceerror"></a></h3>
<ul>
<li>Extends: <a href="#all_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;
<span class="hljs-comment">// Throws ReferenceError, doesNotExist is not a variable in this program.</span></code> <button class="copy-button">copy</button></pre>
<p>Unless an application is dynamically generating and running code,
<code>ReferenceError</code> instances indicate a bug in the code or its dependencies.</p>
</section><section><h3>Class: <code>SyntaxError</code><span><a class="mark" href="#all_errors_class-syntaxerror" id="all_errors_class-syntaxerror">#</a></span><a aria-hidden="true" class="legacy" id="errors_class_syntaxerror"></a></h3>
<ul>
<li>Extends: <a href="#all_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"><span class="hljs-keyword">try</span> {
  <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>).<span class="hljs-title function_">runInThisContext</span>(<span class="hljs-string">'binary ! isNotOk'</span>);
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-comment">// 'err' will be a SyntaxError.</span>
}</code> <button class="copy-button">copy</button></pre>
<p><code>SyntaxError</code> instances are unrecoverable in the context that created them –
they may only be caught by other contexts.</p>
</section><section><h3>Class: <code>SystemError</code><span><a class="mark" href="#all_errors_class-systemerror" id="all_errors_class-systemerror">#</a></span><a aria-hidden="true" class="legacy" id="errors_class_systemerror"></a></h3>
<ul>
<li>Extends: <a href="#all_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> 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>
<h4><code>error.address</code><span><a class="mark" href="#all_errors_erroraddress" id="all_errors_erroraddress">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_address"></a></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>If present, <code>error.address</code> is a string describing the address to which a
network connection failed.</p>
<h4><code>error.code</code><span><a class="mark" href="#all_errors_errorcode_1" id="all_errors_errorcode_1">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_code_1"></a></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>The <code>error.code</code> property is a string representing the error code.</p>
<h4><code>error.dest</code><span><a class="mark" href="#all_errors_errordest" id="all_errors_errordest">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_dest"></a></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>If present, <code>error.dest</code> is the file path destination when reporting a file
system error.</p>
<h4><code>error.errno</code><span><a class="mark" href="#all_errors_errorerrno" id="all_errors_errorerrno">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_errno"></a></h4>
<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.errno</code> property is a negative number which corresponds
to the error code defined in <a href="https://docs.libuv.org/en/v1.x/errors.html"><code>libuv Error handling</code></a>.</p>
<p>On Windows the error number provided by the system will be normalized by libuv.</p>
<p>To get the string representation of the error code, use
<a href="#all_util_utilgetsystemerrornameerr"><code>util.getSystemErrorName(error.errno)</code></a>.</p>
<h4><code>error.info</code><span><a class="mark" href="#all_errors_errorinfo" id="all_errors_errorinfo">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_info"></a></h4>
<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>
<h4><code>error.message</code><span><a class="mark" href="#all_errors_errormessage_1" id="all_errors_errormessage_1">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_message_1"></a></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><code>error.message</code> is a system-provided human-readable description of the error.</p>
<h4><code>error.path</code><span><a class="mark" href="#all_errors_errorpath" id="all_errors_errorpath">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_path"></a></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>If present, <code>error.path</code> is a string containing a relevant invalid pathname.</p>
<h4><code>error.port</code><span><a class="mark" href="#all_errors_errorport" id="all_errors_errorport">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_port"></a></h4>
<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>
<h4><code>error.syscall</code><span><a class="mark" href="#all_errors_errorsyscall" id="all_errors_errorsyscall">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_syscall"></a></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>The <code>error.syscall</code> property is a string describing the <a href="https://man7.org/linux/man-pages/man2/syscalls.2.html">syscall</a> that failed.</p>
<h4>Common system errors<span><a class="mark" href="#all_errors_common-system-errors" id="all_errors_common-system-errors">#</a></span><a aria-hidden="true" class="legacy" id="errors_common_system_errors"></a></h4>
<p>This is a list of system errors commonly-encountered when writing a Node.js
program. For a comprehensive list, see the <a href="https://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="#all_fs_fsreaddirpath-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="#all_fs_fsunlinkpath-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>
</section><section><h3>Class: <code>TypeError</code><span><a class="mark" href="#all_errors_class-typeerror" id="all_errors_class-typeerror">#</a></span><a aria-hidden="true" class="legacy" id="errors_class_typeerror"></a></h3>
<ul>
<li>Extends <a href="#all_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 a <code>TypeError</code>.</p>
<pre><code class="language-js"><span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>).<span class="hljs-title function_">parse</span>(<span class="hljs-function">() =></span> { });
<span class="hljs-comment">// Throws TypeError, since it expected a string.</span></code> <button class="copy-button">copy</button></pre>
<p>Node.js will generate and throw <code>TypeError</code> instances <em>immediately</em> as a form
of argument validation.</p>
</section><section><h3>Exceptions vs. errors<span><a class="mark" href="#all_errors_exceptions-vs-errors" id="all_errors_exceptions-vs-errors">#</a></span><a aria-hidden="true" class="legacy" id="errors_exceptions_vs_errors"></a></h3>

<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>
</section><section><h3>OpenSSL errors<span><a class="mark" href="#all_errors_openssl-errors" id="all_errors_openssl-errors">#</a></span><a aria-hidden="true" class="legacy" id="errors_openssl_errors"></a></h3>
<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>
<h4><code>error.opensslErrorStack</code><span><a class="mark" href="#all_errors_erroropensslerrorstack" id="all_errors_erroropensslerrorstack">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_opensslerrorstack"></a></h4>
<p>An array of errors that can give context to where in the OpenSSL library an
error originates from.</p>
<h4><code>error.function</code><span><a class="mark" href="#all_errors_errorfunction" id="all_errors_errorfunction">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_function"></a></h4>
<p>The OpenSSL function the error originates in.</p>
<h4><code>error.library</code><span><a class="mark" href="#all_errors_errorlibrary" id="all_errors_errorlibrary">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_library"></a></h4>
<p>The OpenSSL library the error originates in.</p>
<h4><code>error.reason</code><span><a class="mark" href="#all_errors_errorreason" id="all_errors_errorreason">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_reason"></a></h4>
<p>A human-readable string describing the reason for the error.</p>
<p><a id="nodejs-error-codes"></a></p>
</section><section><h3>Node.js error codes<span><a class="mark" href="#all_errors_nodejs-error-codes" id="all_errors_nodejs-error-codes">#</a></span><a aria-hidden="true" class="legacy" id="errors_node_js_error_codes"></a></h3>
<p><a id="ABORT_ERR"></a></p>
<h4><code>ABORT_ERR</code><span><a class="mark" href="#all_errors_abort_err" id="all_errors_abort_err">#</a></span><a aria-hidden="true" class="legacy" id="errors_abort_err"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>Used when an operation has been aborted (typically using an <code>AbortController</code>).</p>
<p>APIs <em>not</em> using <code>AbortSignal</code>s typically do not raise an error with this code.</p>
<p>This code does not use the regular <code>ERR_*</code> convention Node.js errors use in
order to be compatible with the web platform's <code>AbortError</code>.</p>
<p><a id="ERR_ACCESS_DENIED"></a></p>
<h4><code>ERR_ACCESS_DENIED</code><span><a class="mark" href="#all_errors_err_access_denied" id="all_errors_err_access_denied">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_access_denied"></a></h4>
<p>A special type of error that is triggered whenever Node.js tries to get access
to a resource restricted by the <a href="#all_permissions_permission-model">Permission Model</a>.</p>
<p><a id="ERR_AMBIGUOUS_ARGUMENT"></a></p>
<h4><code>ERR_AMBIGUOUS_ARGUMENT</code><span><a class="mark" href="#all_errors_err_ambiguous_argument" id="all_errors_err_ambiguous_argument">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_ambiguous_argument"></a></h4>
<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>node: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>
<h4><code>ERR_ARG_NOT_ITERABLE</code><span><a class="mark" href="#all_errors_err_arg_not_iterable" id="all_errors_err_arg_not_iterable">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_arg_not_iterable"></a></h4>
<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>
<h4><code>ERR_ASSERTION</code><span><a class="mark" href="#all_errors_err_assertion" id="all_errors_err_assertion">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_assertion"></a></h4>
<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>node:assert</code> module.</p>
<p><a id="ERR_ASYNC_CALLBACK"></a></p>
<h4><code>ERR_ASYNC_CALLBACK</code><span><a class="mark" href="#all_errors_err_async_callback" id="all_errors_err_async_callback">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_async_callback"></a></h4>
<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>
<h4><code>ERR_ASYNC_TYPE</code><span><a class="mark" href="#all_errors_err_async_type" id="all_errors_err_async_type">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_async_type"></a></h4>
<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>
<h4><code>ERR_BROTLI_COMPRESSION_FAILED</code><span><a class="mark" href="#all_errors_err_brotli_compression_failed" id="all_errors_err_brotli_compression_failed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_brotli_compression_failed"></a></h4>
<p>Data passed to a Brotli stream was not successfully compressed.</p>
<p><a id="ERR_BROTLI_INVALID_PARAM"></a></p>
<h4><code>ERR_BROTLI_INVALID_PARAM</code><span><a class="mark" href="#all_errors_err_brotli_invalid_param" id="all_errors_err_brotli_invalid_param">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_brotli_invalid_param"></a></h4>
<p>An invalid parameter key was passed during construction of a Brotli stream.</p>
<p><a id="ERR_BUFFER_CONTEXT_NOT_AVAILABLE"></a></p>
<h4><code>ERR_BUFFER_CONTEXT_NOT_AVAILABLE</code><span><a class="mark" href="#all_errors_err_buffer_context_not_available" id="all_errors_err_buffer_context_not_available">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_buffer_context_not_available"></a></h4>
<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>
<h4><code>ERR_BUFFER_OUT_OF_BOUNDS</code><span><a class="mark" href="#all_errors_err_buffer_out_of_bounds" id="all_errors_err_buffer_out_of_bounds">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_buffer_out_of_bounds"></a></h4>
<p>An operation outside the bounds of a <code>Buffer</code> was attempted.</p>
<p><a id="ERR_BUFFER_TOO_LARGE"></a></p>
<h4><code>ERR_BUFFER_TOO_LARGE</code><span><a class="mark" href="#all_errors_err_buffer_too_large" id="all_errors_err_buffer_too_large">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_buffer_too_large"></a></h4>
<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>
<h4><code>ERR_CANNOT_WATCH_SIGINT</code><span><a class="mark" href="#all_errors_err_cannot_watch_sigint" id="all_errors_err_cannot_watch_sigint">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_cannot_watch_sigint"></a></h4>
<p>Node.js was unable to watch for the <code>SIGINT</code> signal.</p>
<p><a id="ERR_CHILD_CLOSED_BEFORE_REPLY"></a></p>
<h4><code>ERR_CHILD_CLOSED_BEFORE_REPLY</code><span><a class="mark" href="#all_errors_err_child_closed_before_reply" id="all_errors_err_child_closed_before_reply">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_child_closed_before_reply"></a></h4>
<p>A child process was closed before the parent received a reply.</p>
<p><a id="ERR_CHILD_PROCESS_IPC_REQUIRED"></a></p>
<h4><code>ERR_CHILD_PROCESS_IPC_REQUIRED</code><span><a class="mark" href="#all_errors_err_child_process_ipc_required" id="all_errors_err_child_process_ipc_required">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_child_process_ipc_required"></a></h4>
<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>
<h4><code>ERR_CHILD_PROCESS_STDIO_MAXBUFFER</code><span><a class="mark" href="#all_errors_err_child_process_stdio_maxbuffer" id="all_errors_err_child_process_stdio_maxbuffer">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_child_process_stdio_maxbuffer"></a></h4>
<p>Used when the main process is trying to read data from the child process's
STDERR/STDOUT, and the data's length is longer than the <code>maxBuffer</code> option.</p>
<p><a id="ERR_CLOSED_MESSAGE_PORT"></a></p>
<h4><code>ERR_CLOSED_MESSAGE_PORT</code><span><a class="mark" href="#all_errors_err_closed_message_port" id="all_errors_err_closed_message_port">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_closed_message_port"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.2.0, v14.17.1</td>
<td><p>The error message was reintroduced.</p></td></tr>
<tr><td>v11.12.0</td>
<td><p>The error message was removed.</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>
<p>There was an attempt to use a <code>MessagePort</code> instance in a closed
state, usually after <code>.close()</code> has been called.</p>
<p><a id="ERR_CONSOLE_WRITABLE_STREAM"></a></p>
<h4><code>ERR_CONSOLE_WRITABLE_STREAM</code><span><a class="mark" href="#all_errors_err_console_writable_stream" id="all_errors_err_console_writable_stream">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_console_writable_stream"></a></h4>
<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_INVALID"></a></p>
<h4><code>ERR_CONSTRUCT_CALL_INVALID</code><span><a class="mark" href="#all_errors_err_construct_call_invalid" id="all_errors_err_construct_call_invalid">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_construct_call_invalid"></a></h4>
<div class="api_metadata">
<span>Added in: v12.5.0</span>
</div>
<p>A class constructor was called that is not callable.</p>
<p><a id="ERR_CONSTRUCT_CALL_REQUIRED"></a></p>
<h4><code>ERR_CONSTRUCT_CALL_REQUIRED</code><span><a class="mark" href="#all_errors_err_construct_call_required" id="all_errors_err_construct_call_required">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_construct_call_required"></a></h4>
<p>A constructor for a class was called without <code>new</code>.</p>
<p><a id="ERR_CONTEXT_NOT_INITIALIZED"></a></p>
<h4><code>ERR_CONTEXT_NOT_INITIALIZED</code><span><a class="mark" href="#all_errors_err_context_not_initialized" id="all_errors_err_context_not_initialized">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_context_not_initialized"></a></h4>
<p>The vm context passed into the API is not yet initialized. This could happen
when an error occurs (and is caught) during the creation of the
context, for example, when the allocation fails or the maximum call stack
size is reached when the context is created.</p>
<p><a id="ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED"></a></p>
<h4><code>ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED</code><span><a class="mark" href="#all_errors_err_crypto_custom_engine_not_supported" id="all_errors_err_crypto_custom_engine_not_supported">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_custom_engine_not_supported"></a></h4>
<p>An OpenSSL engine was requested (for example, through the <code>clientCertEngine</code> or
<code>privateKeyEngine</code> TLS options) that is not supported by the version of OpenSSL
being used, likely due to the compile-time flag <code>OPENSSL_NO_ENGINE</code>.</p>
<p><a id="ERR_CRYPTO_ECDH_INVALID_FORMAT"></a></p>
<h4><code>ERR_CRYPTO_ECDH_INVALID_FORMAT</code><span><a class="mark" href="#all_errors_err_crypto_ecdh_invalid_format" id="all_errors_err_crypto_ecdh_invalid_format">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_ecdh_invalid_format"></a></h4>
<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>
<h4><code>ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY</code><span><a class="mark" href="#all_errors_err_crypto_ecdh_invalid_public_key" id="all_errors_err_crypto_ecdh_invalid_public_key">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_ecdh_invalid_public_key"></a></h4>
<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>
<h4><code>ERR_CRYPTO_ENGINE_UNKNOWN</code><span><a class="mark" href="#all_errors_err_crypto_engine_unknown" id="all_errors_err_crypto_engine_unknown">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_engine_unknown"></a></h4>
<p>An invalid crypto engine identifier was passed to
<a href="#all_crypto_cryptosetengineengine-flags"><code>require('node:crypto').setEngine()</code></a>.</p>
<p><a id="ERR_CRYPTO_FIPS_FORCED"></a></p>
<h4><code>ERR_CRYPTO_FIPS_FORCED</code><span><a class="mark" href="#all_errors_err_crypto_fips_forced" id="all_errors_err_crypto_fips_forced">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_fips_forced"></a></h4>
<p>The <a href="#all_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>node:crypto</code> module.</p>
<p><a id="ERR_CRYPTO_FIPS_UNAVAILABLE"></a></p>
<h4><code>ERR_CRYPTO_FIPS_UNAVAILABLE</code><span><a class="mark" href="#all_errors_err_crypto_fips_unavailable" id="all_errors_err_crypto_fips_unavailable">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_fips_unavailable"></a></h4>
<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>
<h4><code>ERR_CRYPTO_HASH_FINALIZED</code><span><a class="mark" href="#all_errors_err_crypto_hash_finalized" id="all_errors_err_crypto_hash_finalized">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_hash_finalized"></a></h4>
<p><a href="#all_crypto_hashdigestencoding"><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>
<h4><code>ERR_CRYPTO_HASH_UPDATE_FAILED</code><span><a class="mark" href="#all_errors_err_crypto_hash_update_failed" id="all_errors_err_crypto_hash_update_failed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_hash_update_failed"></a></h4>
<p><a href="#all_crypto_hashupdatedata-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>
<h4><code>ERR_CRYPTO_INCOMPATIBLE_KEY</code><span><a class="mark" href="#all_errors_err_crypto_incompatible_key" id="all_errors_err_crypto_incompatible_key">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_incompatible_key"></a></h4>
<p>The given crypto keys are incompatible with the attempted operation.</p>
<p><a id="ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS"></a></p>
<h4><code>ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS</code><span><a class="mark" href="#all_errors_err_crypto_incompatible_key_options" id="all_errors_err_crypto_incompatible_key_options">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_incompatible_key_options"></a></h4>
<p>The selected public or private key encoding is incompatible with other options.</p>
<p><a id="ERR_CRYPTO_INITIALIZATION_FAILED"></a></p>
<h4><code>ERR_CRYPTO_INITIALIZATION_FAILED</code><span><a class="mark" href="#all_errors_err_crypto_initialization_failed" id="all_errors_err_crypto_initialization_failed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_initialization_failed"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>Initialization of the crypto subsystem failed.</p>
<p><a id="ERR_CRYPTO_INVALID_AUTH_TAG"></a></p>
<h4><code>ERR_CRYPTO_INVALID_AUTH_TAG</code><span><a class="mark" href="#all_errors_err_crypto_invalid_auth_tag" id="all_errors_err_crypto_invalid_auth_tag">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_invalid_auth_tag"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>An invalid authentication tag was provided.</p>
<p><a id="ERR_CRYPTO_INVALID_COUNTER"></a></p>
<h4><code>ERR_CRYPTO_INVALID_COUNTER</code><span><a class="mark" href="#all_errors_err_crypto_invalid_counter" id="all_errors_err_crypto_invalid_counter">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_invalid_counter"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>An invalid counter was provided for a counter-mode cipher.</p>
<p><a id="ERR_CRYPTO_INVALID_CURVE"></a></p>
<h4><code>ERR_CRYPTO_INVALID_CURVE</code><span><a class="mark" href="#all_errors_err_crypto_invalid_curve" id="all_errors_err_crypto_invalid_curve">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_invalid_curve"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>An invalid elliptic-curve was provided.</p>
<p><a id="ERR_CRYPTO_INVALID_DIGEST"></a></p>
<h4><code>ERR_CRYPTO_INVALID_DIGEST</code><span><a class="mark" href="#all_errors_err_crypto_invalid_digest" id="all_errors_err_crypto_invalid_digest">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_invalid_digest"></a></h4>
<p>An invalid <a href="#all_crypto_cryptogethashes">crypto digest algorithm</a> was specified.</p>
<p><a id="ERR_CRYPTO_INVALID_IV"></a></p>
<h4><code>ERR_CRYPTO_INVALID_IV</code><span><a class="mark" href="#all_errors_err_crypto_invalid_iv" id="all_errors_err_crypto_invalid_iv">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_invalid_iv"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>An invalid initialization vector was provided.</p>
<p><a id="ERR_CRYPTO_INVALID_JWK"></a></p>
<h4><code>ERR_CRYPTO_INVALID_JWK</code><span><a class="mark" href="#all_errors_err_crypto_invalid_jwk" id="all_errors_err_crypto_invalid_jwk">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_invalid_jwk"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>An invalid JSON Web Key was provided.</p>
<p><a id="ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE"></a></p>
<h4><code>ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE</code><span><a class="mark" href="#all_errors_err_crypto_invalid_key_object_type" id="all_errors_err_crypto_invalid_key_object_type">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_invalid_key_object_type"></a></h4>
<p>The given crypto key object's type is invalid for the attempted operation.</p>
<p><a id="ERR_CRYPTO_INVALID_KEYLEN"></a></p>
<h4><code>ERR_CRYPTO_INVALID_KEYLEN</code><span><a class="mark" href="#all_errors_err_crypto_invalid_keylen" id="all_errors_err_crypto_invalid_keylen">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_invalid_keylen"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>An invalid key length was provided.</p>
<p><a id="ERR_CRYPTO_INVALID_KEYPAIR"></a></p>
<h4><code>ERR_CRYPTO_INVALID_KEYPAIR</code><span><a class="mark" href="#all_errors_err_crypto_invalid_keypair" id="all_errors_err_crypto_invalid_keypair">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_invalid_keypair"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>An invalid key pair was provided.</p>
<p><a id="ERR_CRYPTO_INVALID_KEYTYPE"></a></p>
<h4><code>ERR_CRYPTO_INVALID_KEYTYPE</code><span><a class="mark" href="#all_errors_err_crypto_invalid_keytype" id="all_errors_err_crypto_invalid_keytype">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_invalid_keytype"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>An invalid key type was provided.</p>
<p><a id="ERR_CRYPTO_INVALID_MESSAGELEN"></a></p>
<h4><code>ERR_CRYPTO_INVALID_MESSAGELEN</code><span><a class="mark" href="#all_errors_err_crypto_invalid_messagelen" id="all_errors_err_crypto_invalid_messagelen">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_invalid_messagelen"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>An invalid message length was provided.</p>
<p><a id="ERR_CRYPTO_INVALID_SCRYPT_PARAMS"></a></p>
<h4><code>ERR_CRYPTO_INVALID_SCRYPT_PARAMS</code><span><a class="mark" href="#all_errors_err_crypto_invalid_scrypt_params" id="all_errors_err_crypto_invalid_scrypt_params">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_invalid_scrypt_params"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>Invalid scrypt algorithm parameters were provided.</p>
<p><a id="ERR_CRYPTO_INVALID_STATE"></a></p>
<h4><code>ERR_CRYPTO_INVALID_STATE</code><span><a class="mark" href="#all_errors_err_crypto_invalid_state" id="all_errors_err_crypto_invalid_state">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_invalid_state"></a></h4>
<p>A crypto method was used on an object that was in an invalid state. For
instance, calling <a href="#all_crypto_ciphergetauthtag"><code>cipher.getAuthTag()</code></a> before calling <code>cipher.final()</code>.</p>
<p><a id="ERR_CRYPTO_INVALID_TAG_LENGTH"></a></p>
<h4><code>ERR_CRYPTO_INVALID_TAG_LENGTH</code><span><a class="mark" href="#all_errors_err_crypto_invalid_tag_length" id="all_errors_err_crypto_invalid_tag_length">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_invalid_tag_length"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>An invalid authentication tag length was provided.</p>
<p><a id="ERR_CRYPTO_JOB_INIT_FAILED"></a></p>
<h4><code>ERR_CRYPTO_JOB_INIT_FAILED</code><span><a class="mark" href="#all_errors_err_crypto_job_init_failed" id="all_errors_err_crypto_job_init_failed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_job_init_failed"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>Initialization of an asynchronous crypto operation failed.</p>
<p><a id="ERR_CRYPTO_JWK_UNSUPPORTED_CURVE"></a></p>
<h4><code>ERR_CRYPTO_JWK_UNSUPPORTED_CURVE</code><span><a class="mark" href="#all_errors_err_crypto_jwk_unsupported_curve" id="all_errors_err_crypto_jwk_unsupported_curve">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_jwk_unsupported_curve"></a></h4>
<p>Key's Elliptic Curve is not registered for use in the
<a href="https://www.iana.org/assignments/jose/jose.xhtml#web-key-elliptic-curve">JSON Web Key Elliptic Curve Registry</a>.</p>
<p><a id="ERR_CRYPTO_JWK_UNSUPPORTED_KEY_TYPE"></a></p>
<h4><code>ERR_CRYPTO_JWK_UNSUPPORTED_KEY_TYPE</code><span><a class="mark" href="#all_errors_err_crypto_jwk_unsupported_key_type" id="all_errors_err_crypto_jwk_unsupported_key_type">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_jwk_unsupported_key_type"></a></h4>
<p>Key's Asymmetric Key Type is not registered for use in the
<a href="https://www.iana.org/assignments/jose/jose.xhtml#web-key-types">JSON Web Key Types Registry</a>.</p>
<p><a id="ERR_CRYPTO_OPERATION_FAILED"></a></p>
<h4><code>ERR_CRYPTO_OPERATION_FAILED</code><span><a class="mark" href="#all_errors_err_crypto_operation_failed" id="all_errors_err_crypto_operation_failed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_operation_failed"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>A crypto operation failed for an otherwise unspecified reason.</p>
<p><a id="ERR_CRYPTO_PBKDF2_ERROR"></a></p>
<h4><code>ERR_CRYPTO_PBKDF2_ERROR</code><span><a class="mark" href="#all_errors_err_crypto_pbkdf2_error" id="all_errors_err_crypto_pbkdf2_error">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_pbkdf2_error"></a></h4>
<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>
<h4><code>ERR_CRYPTO_SCRYPT_INVALID_PARAMETER</code><span><a class="mark" href="#all_errors_err_crypto_scrypt_invalid_parameter" id="all_errors_err_crypto_scrypt_invalid_parameter">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_scrypt_invalid_parameter"></a></h4>
<p>One or more <a href="#all_crypto_cryptoscryptpassword-salt-keylen-options-callback"><code>crypto.scrypt()</code></a> or <a href="#all_crypto_cryptoscryptsyncpassword-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>
<h4><code>ERR_CRYPTO_SCRYPT_NOT_SUPPORTED</code><span><a class="mark" href="#all_errors_err_crypto_scrypt_not_supported" id="all_errors_err_crypto_scrypt_not_supported">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_scrypt_not_supported"></a></h4>
<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>
<h4><code>ERR_CRYPTO_SIGN_KEY_REQUIRED</code><span><a class="mark" href="#all_errors_err_crypto_sign_key_required" id="all_errors_err_crypto_sign_key_required">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_sign_key_required"></a></h4>
<p>A signing <code>key</code> was not provided to the <a href="#all_crypto_signsignprivatekey-outputencoding"><code>sign.sign()</code></a> method.</p>
<p><a id="ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH"></a></p>
<h4><code>ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH</code><span><a class="mark" href="#all_errors_err_crypto_timing_safe_equal_length" id="all_errors_err_crypto_timing_safe_equal_length">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_timing_safe_equal_length"></a></h4>
<p><a href="#all_crypto_cryptotimingsafeequala-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>
<h4><code>ERR_CRYPTO_UNKNOWN_CIPHER</code><span><a class="mark" href="#all_errors_err_crypto_unknown_cipher" id="all_errors_err_crypto_unknown_cipher">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_unknown_cipher"></a></h4>
<p>An unknown cipher was specified.</p>
<p><a id="ERR_CRYPTO_UNKNOWN_DH_GROUP"></a></p>
<h4><code>ERR_CRYPTO_UNKNOWN_DH_GROUP</code><span><a class="mark" href="#all_errors_err_crypto_unknown_dh_group" id="all_errors_err_crypto_unknown_dh_group">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_unknown_dh_group"></a></h4>
<p>An unknown Diffie-Hellman group name was given. See
<a href="#all_crypto_cryptogetdiffiehellmangroupname"><code>crypto.getDiffieHellman()</code></a> for a list of valid group names.</p>
<p><a id="ERR_CRYPTO_UNSUPPORTED_OPERATION"></a></p>
<h4><code>ERR_CRYPTO_UNSUPPORTED_OPERATION</code><span><a class="mark" href="#all_errors_err_crypto_unsupported_operation" id="all_errors_err_crypto_unsupported_operation">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_unsupported_operation"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0, v14.18.0</span>
</div>
<p>An attempt to invoke an unsupported crypto operation was made.</p>
<p><a id="ERR_DEBUGGER_ERROR"></a></p>
<h4><code>ERR_DEBUGGER_ERROR</code><span><a class="mark" href="#all_errors_err_debugger_error" id="all_errors_err_debugger_error">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_debugger_error"></a></h4>
<div class="api_metadata">
<span>Added in: v16.4.0, v14.17.4</span>
</div>
<p>An error occurred with the <a href="debugger.html">debugger</a>.</p>
<p><a id="ERR_DEBUGGER_STARTUP_ERROR"></a></p>
<h4><code>ERR_DEBUGGER_STARTUP_ERROR</code><span><a class="mark" href="#all_errors_err_debugger_startup_error" id="all_errors_err_debugger_startup_error">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_debugger_startup_error"></a></h4>
<div class="api_metadata">
<span>Added in: v16.4.0, v14.17.4</span>
</div>
<p>The <a href="debugger.html">debugger</a> timed out waiting for the required host/port to be free.</p>
<p><a id="ERR_DLOPEN_DISABLED"></a></p>
<h4><code>ERR_DLOPEN_DISABLED</code><span><a class="mark" href="#all_errors_err_dlopen_disabled" id="all_errors_err_dlopen_disabled">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_dlopen_disabled"></a></h4>
<div class="api_metadata">
<span>Added in: v16.10.0, v14.19.0</span>
</div>
<p>Loading native addons has been disabled using <a href="#all_cli_--no-addons"><code>--no-addons</code></a>.</p>
<p><a id="ERR_DLOPEN_FAILED"></a></p>
<h4><code>ERR_DLOPEN_FAILED</code><span><a class="mark" href="#all_errors_err_dlopen_failed" id="all_errors_err_dlopen_failed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_dlopen_failed"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>A call to <code>process.dlopen()</code> failed.</p>
<p><a id="ERR_DIR_CLOSED"></a></p>
<h4><code>ERR_DIR_CLOSED</code><span><a class="mark" href="#all_errors_err_dir_closed" id="all_errors_err_dir_closed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_dir_closed"></a></h4>
<p>The <a href="#all_fs_class-fsdir"><code>fs.Dir</code></a> was previously closed.</p>
<p><a id="ERR_DIR_CONCURRENT_OPERATION"></a></p>
<h4><code>ERR_DIR_CONCURRENT_OPERATION</code><span><a class="mark" href="#all_errors_err_dir_concurrent_operation" id="all_errors_err_dir_concurrent_operation">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_dir_concurrent_operation"></a></h4>
<div class="api_metadata">
<span>Added in: v14.3.0</span>
</div>
<p>A synchronous read or close call was attempted on an <a href="#all_fs_class-fsdir"><code>fs.Dir</code></a> which has
ongoing asynchronous operations.</p>
<p><a id="ERR_DNS_SET_SERVERS_FAILED"></a></p>
<h4><code>ERR_DNS_SET_SERVERS_FAILED</code><span><a class="mark" href="#all_errors_err_dns_set_servers_failed" id="all_errors_err_dns_set_servers_failed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_dns_set_servers_failed"></a></h4>
<p><code>c-ares</code> failed to set the DNS server.</p>
<p><a id="ERR_DOMAIN_CALLBACK_NOT_AVAILABLE"></a></p>
<h4><code>ERR_DOMAIN_CALLBACK_NOT_AVAILABLE</code><span><a class="mark" href="#all_errors_err_domain_callback_not_available" id="all_errors_err_domain_callback_not_available">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_domain_callback_not_available"></a></h4>
<p>The <code>node:domain</code> module was not usable since it could not establish the
required error handling hooks, because
<a href="#all_process_processsetuncaughtexceptioncapturecallbackfn"><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>
<h4><code>ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE</code><span><a class="mark" href="#all_errors_err_domain_cannot_set_uncaught_exception_capture" id="all_errors_err_domain_cannot_set_uncaught_exception_capture">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_domain_cannot_set_uncaught_exception_capture"></a></h4>
<p><a href="#all_process_processsetuncaughtexceptioncapturecallbackfn"><code>process.setUncaughtExceptionCaptureCallback()</code></a> could not be called
because the <code>node: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>node:domain</code> module had been loaded.</p>
<p><a id="ERR_DUPLICATE_STARTUP_SNAPSHOT_MAIN_FUNCTION"></a></p>
<h4><code>ERR_DUPLICATE_STARTUP_SNAPSHOT_MAIN_FUNCTION</code><span><a class="mark" href="#all_errors_err_duplicate_startup_snapshot_main_function" id="all_errors_err_duplicate_startup_snapshot_main_function">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_duplicate_startup_snapshot_main_function"></a></h4>
<p><a href="#all_v8_v8startupsnapshotsetdeserializemainfunctioncallback-data"><code>v8.startupSnapshot.setDeserializeMainFunction()</code></a> could not be called
because it had already been called before.</p>
<p><a id="ERR_ENCODING_INVALID_ENCODED_DATA"></a></p>
<h4><code>ERR_ENCODING_INVALID_ENCODED_DATA</code><span><a class="mark" href="#all_errors_err_encoding_invalid_encoded_data" id="all_errors_err_encoding_invalid_encoded_data">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_encoding_invalid_encoded_data"></a></h4>
<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>
<h4><code>ERR_ENCODING_NOT_SUPPORTED</code><span><a class="mark" href="#all_errors_err_encoding_not_supported" id="all_errors_err_encoding_not_supported">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_encoding_not_supported"></a></h4>
<p>Encoding provided to <code>TextDecoder()</code> API was not one of the
<a href="#all_util_whatwg-supported-encodings">WHATWG Supported Encodings</a>.</p>
<p><a id="ERR_EVAL_ESM_CANNOT_PRINT"></a></p>
<h4><code>ERR_EVAL_ESM_CANNOT_PRINT</code><span><a class="mark" href="#all_errors_err_eval_esm_cannot_print" id="all_errors_err_eval_esm_cannot_print">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_eval_esm_cannot_print"></a></h4>
<p><code>--print</code> cannot be used with ESM input.</p>
<p><a id="ERR_EVENT_RECURSION"></a></p>
<h4><code>ERR_EVENT_RECURSION</code><span><a class="mark" href="#all_errors_err_event_recursion" id="all_errors_err_event_recursion">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_event_recursion"></a></h4>
<p>Thrown when an attempt is made to recursively dispatch an event on <code>EventTarget</code>.</p>
<p><a id="ERR_EXECUTION_ENVIRONMENT_NOT_AVAILABLE"></a></p>
<h4><code>ERR_EXECUTION_ENVIRONMENT_NOT_AVAILABLE</code><span><a class="mark" href="#all_errors_err_execution_environment_not_available" id="all_errors_err_execution_environment_not_available">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_execution_environment_not_available"></a></h4>
<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>
<h4><code>ERR_FALSY_VALUE_REJECTION</code><span><a class="mark" href="#all_errors_err_falsy_value_rejection" id="all_errors_err_falsy_value_rejection">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_falsy_value_rejection"></a></h4>
<p>A <code>Promise</code> that was callbackified via <code>util.callbackify()</code> was rejected with a
falsy value.</p>
<p><a id="ERR_FEATURE_UNAVAILABLE_ON_PLATFORM"></a></p>
<h4><code>ERR_FEATURE_UNAVAILABLE_ON_PLATFORM</code><span><a class="mark" href="#all_errors_err_feature_unavailable_on_platform" id="all_errors_err_feature_unavailable_on_platform">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_feature_unavailable_on_platform"></a></h4>
<div class="api_metadata">
<span>Added in: v14.0.0</span>
</div>
<p>Used when a feature that is not available
to the current platform which is running Node.js is used.</p>
<p><a id="ERR_FS_CP_DIR_TO_NON_DIR"></a></p>
<h4><code>ERR_FS_CP_DIR_TO_NON_DIR</code><span><a class="mark" href="#all_errors_err_fs_cp_dir_to_non_dir" id="all_errors_err_fs_cp_dir_to_non_dir">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_fs_cp_dir_to_non_dir"></a></h4>
<div class="api_metadata">
<span>Added in: v16.7.0</span>
</div>
<p>An attempt was made to copy a directory to a non-directory (file, symlink,
etc.) using <a href="#all_fs_fscpsrc-dest-options-callback"><code>fs.cp()</code></a>.</p>
<p><a id="ERR_FS_CP_EEXIST"></a></p>
<h4><code>ERR_FS_CP_EEXIST</code><span><a class="mark" href="#all_errors_err_fs_cp_eexist" id="all_errors_err_fs_cp_eexist">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_fs_cp_eexist"></a></h4>
<div class="api_metadata">
<span>Added in: v16.7.0</span>
</div>
<p>An attempt was made to copy over a file that already existed with
<a href="#all_fs_fscpsrc-dest-options-callback"><code>fs.cp()</code></a>, with the <code>force</code> and <code>errorOnExist</code> set to <code>true</code>.</p>
<p><a id="ERR_FS_CP_EINVAL"></a></p>
<h4><code>ERR_FS_CP_EINVAL</code><span><a class="mark" href="#all_errors_err_fs_cp_einval" id="all_errors_err_fs_cp_einval">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_fs_cp_einval"></a></h4>
<div class="api_metadata">
<span>Added in: v16.7.0</span>
</div>
<p>When using <a href="#all_fs_fscpsrc-dest-options-callback"><code>fs.cp()</code></a>, <code>src</code> or <code>dest</code> pointed to an invalid path.</p>
<p><a id="ERR_FS_CP_FIFO_PIPE"></a></p>
<h4><code>ERR_HTTP_BODY_NOT_ALLOWED</code><span><a class="mark" href="#all_errors_err_http_body_not_allowed" id="all_errors_err_http_body_not_allowed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http_body_not_allowed"></a></h4>
<p>An error is thrown when writing to an HTTP response which does not allow
contents. <a id="ERR_HTTP_BODY_NOT_ALLOWED"></a></p>
<h4><code>ERR_HTTP_CONTENT_LENGTH_MISMATCH</code><span><a class="mark" href="#all_errors_err_http_content_length_mismatch" id="all_errors_err_http_content_length_mismatch">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http_content_length_mismatch"></a></h4>
<p>Response body size doesn't match with the specified content-length header value.</p>
<p><a id="ERR_HTTP_CONTENT_LENGTH_MISMATCH"></a></p>
<h4><code>ERR_FS_CP_FIFO_PIPE</code><span><a class="mark" href="#all_errors_err_fs_cp_fifo_pipe" id="all_errors_err_fs_cp_fifo_pipe">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_fs_cp_fifo_pipe"></a></h4>
<div class="api_metadata">
<span>Added in: v16.7.0</span>
</div>
<p>An attempt was made to copy a named pipe with <a href="#all_fs_fscpsrc-dest-options-callback"><code>fs.cp()</code></a>.</p>
<p><a id="ERR_FS_CP_NON_DIR_TO_DIR"></a></p>
<h4><code>ERR_FS_CP_NON_DIR_TO_DIR</code><span><a class="mark" href="#all_errors_err_fs_cp_non_dir_to_dir" id="all_errors_err_fs_cp_non_dir_to_dir">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_fs_cp_non_dir_to_dir"></a></h4>
<div class="api_metadata">
<span>Added in: v16.7.0</span>
</div>
<p>An attempt was made to copy a non-directory (file, symlink, etc.) to a directory
using <a href="#all_fs_fscpsrc-dest-options-callback"><code>fs.cp()</code></a>.</p>
<p><a id="ERR_FS_CP_SOCKET"></a></p>
<h4><code>ERR_FS_CP_SOCKET</code><span><a class="mark" href="#all_errors_err_fs_cp_socket" id="all_errors_err_fs_cp_socket">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_fs_cp_socket"></a></h4>
<div class="api_metadata">
<span>Added in: v16.7.0</span>
</div>
<p>An attempt was made to copy to a socket with <a href="#all_fs_fscpsrc-dest-options-callback"><code>fs.cp()</code></a>.</p>
<p><a id="ERR_FS_CP_SYMLINK_TO_SUBDIRECTORY"></a></p>
<h4><code>ERR_FS_CP_SYMLINK_TO_SUBDIRECTORY</code><span><a class="mark" href="#all_errors_err_fs_cp_symlink_to_subdirectory" id="all_errors_err_fs_cp_symlink_to_subdirectory">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_fs_cp_symlink_to_subdirectory"></a></h4>
<div class="api_metadata">
<span>Added in: v16.7.0</span>
</div>
<p>When using <a href="#all_fs_fscpsrc-dest-options-callback"><code>fs.cp()</code></a>, a symlink in <code>dest</code> pointed to a subdirectory
of <code>src</code>.</p>
<p><a id="ERR_FS_CP_UNKNOWN"></a></p>
<h4><code>ERR_FS_CP_UNKNOWN</code><span><a class="mark" href="#all_errors_err_fs_cp_unknown" id="all_errors_err_fs_cp_unknown">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_fs_cp_unknown"></a></h4>
<div class="api_metadata">
<span>Added in: v16.7.0</span>
</div>
<p>An attempt was made to copy to an unknown file type with <a href="#all_fs_fscpsrc-dest-options-callback"><code>fs.cp()</code></a>.</p>
<p><a id="ERR_FS_EISDIR"></a></p>
<h4><code>ERR_FS_EISDIR</code><span><a class="mark" href="#all_errors_err_fs_eisdir" id="all_errors_err_fs_eisdir">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_fs_eisdir"></a></h4>
<p>Path is a directory.</p>
<p><a id="ERR_FS_FILE_TOO_LARGE"></a></p>
<h4><code>ERR_FS_FILE_TOO_LARGE</code><span><a class="mark" href="#all_errors_err_fs_file_too_large" id="all_errors_err_fs_file_too_large">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_fs_file_too_large"></a></h4>
<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>
<h4><code>ERR_FS_INVALID_SYMLINK_TYPE</code><span><a class="mark" href="#all_errors_err_fs_invalid_symlink_type" id="all_errors_err_fs_invalid_symlink_type">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_fs_invalid_symlink_type"></a></h4>
<p>An invalid symlink type was passed to the <a href="#all_fs_fssymlinktarget-path-type-callback"><code>fs.symlink()</code></a> or
<a href="#all_fs_fssymlinksynctarget-path-type"><code>fs.symlinkSync()</code></a> methods.</p>
<p><a id="ERR_HTTP_HEADERS_SENT"></a></p>
<h4><code>ERR_HTTP_HEADERS_SENT</code><span><a class="mark" href="#all_errors_err_http_headers_sent" id="all_errors_err_http_headers_sent">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http_headers_sent"></a></h4>
<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>
<h4><code>ERR_HTTP_INVALID_HEADER_VALUE</code><span><a class="mark" href="#all_errors_err_http_invalid_header_value" id="all_errors_err_http_invalid_header_value">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http_invalid_header_value"></a></h4>
<p>An invalid HTTP header value was specified.</p>
<p><a id="ERR_HTTP_INVALID_STATUS_CODE"></a></p>
<h4><code>ERR_HTTP_INVALID_STATUS_CODE</code><span><a class="mark" href="#all_errors_err_http_invalid_status_code" id="all_errors_err_http_invalid_status_code">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http_invalid_status_code"></a></h4>
<p>Status code was outside the regular status code range (100-999).</p>
<p><a id="ERR_HTTP_REQUEST_TIMEOUT"></a></p>
<h4><code>ERR_HTTP_REQUEST_TIMEOUT</code><span><a class="mark" href="#all_errors_err_http_request_timeout" id="all_errors_err_http_request_timeout">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http_request_timeout"></a></h4>
<p>The client has not sent the entire request within the allowed time.</p>
<p><a id="ERR_HTTP_SOCKET_ASSIGNED"></a></p>
<h4><code>ERR_HTTP_SOCKET_ASSIGNED</code><span><a class="mark" href="#all_errors_err_http_socket_assigned" id="all_errors_err_http_socket_assigned">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http_socket_assigned"></a></h4>
<p>The given <a href="#all_http_class-httpserverresponse"><code>ServerResponse</code></a> was already assigned a socket.</p>
<p><a id="ERR_HTTP_SOCKET_ENCODING"></a></p>
<h4><code>ERR_HTTP_SOCKET_ENCODING</code><span><a class="mark" href="#all_errors_err_http_socket_encoding" id="all_errors_err_http_socket_encoding">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http_socket_encoding"></a></h4>
<p>Changing the socket encoding is not allowed per <a href="https://tools.ietf.org/html/rfc7230#section-3">RFC 7230 Section 3</a>.</p>
<p><a id="ERR_HTTP_TRAILER_INVALID"></a></p>
<h4><code>ERR_HTTP_TRAILER_INVALID</code><span><a class="mark" href="#all_errors_err_http_trailer_invalid" id="all_errors_err_http_trailer_invalid">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http_trailer_invalid"></a></h4>
<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>
<h4><code>ERR_HTTP2_ALTSVC_INVALID_ORIGIN</code><span><a class="mark" href="#all_errors_err_http2_altsvc_invalid_origin" id="all_errors_err_http2_altsvc_invalid_origin">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_altsvc_invalid_origin"></a></h4>
<p>HTTP/2 ALTSVC frames require a valid origin.</p>
<p><a id="ERR_HTTP2_ALTSVC_LENGTH"></a></p>
<h4><code>ERR_HTTP2_ALTSVC_LENGTH</code><span><a class="mark" href="#all_errors_err_http2_altsvc_length" id="all_errors_err_http2_altsvc_length">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_altsvc_length"></a></h4>
<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>
<h4><code>ERR_HTTP2_CONNECT_AUTHORITY</code><span><a class="mark" href="#all_errors_err_http2_connect_authority" id="all_errors_err_http2_connect_authority">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_connect_authority"></a></h4>
<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>
<h4><code>ERR_HTTP2_CONNECT_PATH</code><span><a class="mark" href="#all_errors_err_http2_connect_path" id="all_errors_err_http2_connect_path">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_connect_path"></a></h4>
<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>
<h4><code>ERR_HTTP2_CONNECT_SCHEME</code><span><a class="mark" href="#all_errors_err_http2_connect_scheme" id="all_errors_err_http2_connect_scheme">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_connect_scheme"></a></h4>
<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>
<h4><code>ERR_HTTP2_ERROR</code><span><a class="mark" href="#all_errors_err_http2_error" id="all_errors_err_http2_error">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_error"></a></h4>
<p>A non-specific HTTP/2 error has occurred.</p>
<p><a id="ERR_HTTP2_GOAWAY_SESSION"></a></p>
<h4><code>ERR_HTTP2_GOAWAY_SESSION</code><span><a class="mark" href="#all_errors_err_http2_goaway_session" id="all_errors_err_http2_goaway_session">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_goaway_session"></a></h4>
<p>New HTTP/2 Streams may not be opened after the <code>Http2Session</code> has received a
<code>GOAWAY</code> frame from the connected peer.</p>
<p><a id="ERR_HTTP2_HEADER_SINGLE_VALUE"></a></p>
<h4><code>ERR_HTTP2_HEADER_SINGLE_VALUE</code><span><a class="mark" href="#all_errors_err_http2_header_single_value" id="all_errors_err_http2_header_single_value">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_header_single_value"></a></h4>
<p>Multiple values were provided for an HTTP/2 header field that was required to
have only a single value.</p>
<p><a id="ERR_HTTP2_HEADERS_AFTER_RESPOND"></a></p>
<h4><code>ERR_HTTP2_HEADERS_AFTER_RESPOND</code><span><a class="mark" href="#all_errors_err_http2_headers_after_respond" id="all_errors_err_http2_headers_after_respond">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_headers_after_respond"></a></h4>
<p>An additional headers was specified after an HTTP/2 response was initiated.</p>
<p><a id="ERR_HTTP2_HEADERS_SENT"></a></p>
<h4><code>ERR_HTTP2_HEADERS_SENT</code><span><a class="mark" href="#all_errors_err_http2_headers_sent" id="all_errors_err_http2_headers_sent">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_headers_sent"></a></h4>
<p>An attempt was made to send multiple response headers.</p>
<p><a id="ERR_HTTP2_INFO_STATUS_NOT_ALLOWED"></a></p>
<h4><code>ERR_HTTP2_INFO_STATUS_NOT_ALLOWED</code><span><a class="mark" href="#all_errors_err_http2_info_status_not_allowed" id="all_errors_err_http2_info_status_not_allowed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_info_status_not_allowed"></a></h4>
<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>
<h4><code>ERR_HTTP2_INVALID_CONNECTION_HEADERS</code><span><a class="mark" href="#all_errors_err_http2_invalid_connection_headers" id="all_errors_err_http2_invalid_connection_headers">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_invalid_connection_headers"></a></h4>
<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>
<h4><code>ERR_HTTP2_INVALID_HEADER_VALUE</code><span><a class="mark" href="#all_errors_err_http2_invalid_header_value" id="all_errors_err_http2_invalid_header_value">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_invalid_header_value"></a></h4>
<p>An invalid HTTP/2 header value was specified.</p>
<p><a id="ERR_HTTP2_INVALID_INFO_STATUS"></a></p>
<h4><code>ERR_HTTP2_INVALID_INFO_STATUS</code><span><a class="mark" href="#all_errors_err_http2_invalid_info_status" id="all_errors_err_http2_invalid_info_status">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_invalid_info_status"></a></h4>
<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>
<h4><code>ERR_HTTP2_INVALID_ORIGIN</code><span><a class="mark" href="#all_errors_err_http2_invalid_origin" id="all_errors_err_http2_invalid_origin">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_invalid_origin"></a></h4>
<p>HTTP/2 <code>ORIGIN</code> frames require a valid origin.</p>
<p><a id="ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH"></a></p>
<h4><code>ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH</code><span><a class="mark" href="#all_errors_err_http2_invalid_packed_settings_length" id="all_errors_err_http2_invalid_packed_settings_length">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_invalid_packed_settings_length"></a></h4>
<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>
<h4><code>ERR_HTTP2_INVALID_PSEUDOHEADER</code><span><a class="mark" href="#all_errors_err_http2_invalid_pseudoheader" id="all_errors_err_http2_invalid_pseudoheader">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_invalid_pseudoheader"></a></h4>
<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>
<h4><code>ERR_HTTP2_INVALID_SESSION</code><span><a class="mark" href="#all_errors_err_http2_invalid_session" id="all_errors_err_http2_invalid_session">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_invalid_session"></a></h4>
<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>
<h4><code>ERR_HTTP2_INVALID_SETTING_VALUE</code><span><a class="mark" href="#all_errors_err_http2_invalid_setting_value" id="all_errors_err_http2_invalid_setting_value">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_invalid_setting_value"></a></h4>
<p>An invalid value has been specified for an HTTP/2 setting.</p>
<p><a id="ERR_HTTP2_INVALID_STREAM"></a></p>
<h4><code>ERR_HTTP2_INVALID_STREAM</code><span><a class="mark" href="#all_errors_err_http2_invalid_stream" id="all_errors_err_http2_invalid_stream">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_invalid_stream"></a></h4>
<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>
<h4><code>ERR_HTTP2_MAX_PENDING_SETTINGS_ACK</code><span><a class="mark" href="#all_errors_err_http2_max_pending_settings_ack" id="all_errors_err_http2_max_pending_settings_ack">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_max_pending_settings_ack"></a></h4>
<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>
<h4><code>ERR_HTTP2_NESTED_PUSH</code><span><a class="mark" href="#all_errors_err_http2_nested_push" id="all_errors_err_http2_nested_push">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_nested_push"></a></h4>
<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_MEM"></a></p>
<h4><code>ERR_HTTP2_NO_MEM</code><span><a class="mark" href="#all_errors_err_http2_no_mem" id="all_errors_err_http2_no_mem">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_no_mem"></a></h4>
<p>Out of memory when using the <code>http2session.setLocalWindowSize(windowSize)</code> API.</p>
<p><a id="ERR_HTTP2_NO_SOCKET_MANIPULATION"></a></p>
<h4><code>ERR_HTTP2_NO_SOCKET_MANIPULATION</code><span><a class="mark" href="#all_errors_err_http2_no_socket_manipulation" id="all_errors_err_http2_no_socket_manipulation">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_no_socket_manipulation"></a></h4>
<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>
<h4><code>ERR_HTTP2_ORIGIN_LENGTH</code><span><a class="mark" href="#all_errors_err_http2_origin_length" id="all_errors_err_http2_origin_length">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_origin_length"></a></h4>
<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>
<h4><code>ERR_HTTP2_OUT_OF_STREAMS</code><span><a class="mark" href="#all_errors_err_http2_out_of_streams" id="all_errors_err_http2_out_of_streams">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_out_of_streams"></a></h4>
<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>
<h4><code>ERR_HTTP2_PAYLOAD_FORBIDDEN</code><span><a class="mark" href="#all_errors_err_http2_payload_forbidden" id="all_errors_err_http2_payload_forbidden">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_payload_forbidden"></a></h4>
<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>
<h4><code>ERR_HTTP2_PING_CANCEL</code><span><a class="mark" href="#all_errors_err_http2_ping_cancel" id="all_errors_err_http2_ping_cancel">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_ping_cancel"></a></h4>
<p>An HTTP/2 ping was canceled.</p>
<p><a id="ERR_HTTP2_PING_LENGTH"></a></p>
<h4><code>ERR_HTTP2_PING_LENGTH</code><span><a class="mark" href="#all_errors_err_http2_ping_length" id="all_errors_err_http2_ping_length">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_ping_length"></a></h4>
<p>HTTP/2 ping payloads must be exactly 8 bytes in length.</p>
<p><a id="ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED"></a></p>
<h4><code>ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED</code><span><a class="mark" href="#all_errors_err_http2_pseudoheader_not_allowed" id="all_errors_err_http2_pseudoheader_not_allowed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_pseudoheader_not_allowed"></a></h4>
<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>
<h4><code>ERR_HTTP2_PUSH_DISABLED</code><span><a class="mark" href="#all_errors_err_http2_push_disabled" id="all_errors_err_http2_push_disabled">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_push_disabled"></a></h4>
<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>
<h4><code>ERR_HTTP2_SEND_FILE</code><span><a class="mark" href="#all_errors_err_http2_send_file" id="all_errors_err_http2_send_file">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_send_file"></a></h4>
<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>
<h4><code>ERR_HTTP2_SEND_FILE_NOSEEK</code><span><a class="mark" href="#all_errors_err_http2_send_file_noseek" id="all_errors_err_http2_send_file_noseek">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_send_file_noseek"></a></h4>
<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>
<h4><code>ERR_HTTP2_SESSION_ERROR</code><span><a class="mark" href="#all_errors_err_http2_session_error" id="all_errors_err_http2_session_error">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_session_error"></a></h4>
<p>The <code>Http2Session</code> closed with a non-zero error code.</p>
<p><a id="ERR_HTTP2_SETTINGS_CANCEL"></a></p>
<h4><code>ERR_HTTP2_SETTINGS_CANCEL</code><span><a class="mark" href="#all_errors_err_http2_settings_cancel" id="all_errors_err_http2_settings_cancel">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_settings_cancel"></a></h4>
<p>The <code>Http2Session</code> settings canceled.</p>
<p><a id="ERR_HTTP2_SOCKET_BOUND"></a></p>
<h4><code>ERR_HTTP2_SOCKET_BOUND</code><span><a class="mark" href="#all_errors_err_http2_socket_bound" id="all_errors_err_http2_socket_bound">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_socket_bound"></a></h4>
<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>
<h4><code>ERR_HTTP2_SOCKET_UNBOUND</code><span><a class="mark" href="#all_errors_err_http2_socket_unbound" id="all_errors_err_http2_socket_unbound">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_socket_unbound"></a></h4>
<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>
<h4><code>ERR_HTTP2_STATUS_101</code><span><a class="mark" href="#all_errors_err_http2_status_101" id="all_errors_err_http2_status_101">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_status_101"></a></h4>
<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>
<h4><code>ERR_HTTP2_STATUS_INVALID</code><span><a class="mark" href="#all_errors_err_http2_status_invalid" id="all_errors_err_http2_status_invalid">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_status_invalid"></a></h4>
<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>
<h4><code>ERR_HTTP2_STREAM_CANCEL</code><span><a class="mark" href="#all_errors_err_http2_stream_cancel" id="all_errors_err_http2_stream_cancel">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_stream_cancel"></a></h4>
<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>
<h4><code>ERR_HTTP2_STREAM_ERROR</code><span><a class="mark" href="#all_errors_err_http2_stream_error" id="all_errors_err_http2_stream_error">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_stream_error"></a></h4>
<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>
<h4><code>ERR_HTTP2_STREAM_SELF_DEPENDENCY</code><span><a class="mark" href="#all_errors_err_http2_stream_self_dependency" id="all_errors_err_http2_stream_self_dependency">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_stream_self_dependency"></a></h4>
<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_TOO_MANY_CUSTOM_SETTINGS"></a></p>
<h4><code>ERR_HTTP2_TOO_MANY_CUSTOM_SETTINGS</code><span><a class="mark" href="#all_errors_err_http2_too_many_custom_settings" id="all_errors_err_http2_too_many_custom_settings">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_too_many_custom_settings"></a></h4>
<p>The number of supported custom settings (10) has been exceeded.</p>
<p><a id="ERR_HTTP2_TOO_MANY_INVALID_FRAMES"></a></p>
<h4><code>ERR_HTTP2_TOO_MANY_INVALID_FRAMES</code><span><a class="mark" href="#all_errors_err_http2_too_many_invalid_frames" id="all_errors_err_http2_too_many_invalid_frames">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_too_many_invalid_frames"></a></h4>
<div class="api_metadata">
<span>Added in: v15.14.0</span>
</div>
<p>The limit of acceptable invalid HTTP/2 protocol frames sent by the peer,
as specified through the <code>maxSessionInvalidFrames</code> option, has been exceeded.</p>
<p><a id="ERR_HTTP2_TRAILERS_ALREADY_SENT"></a></p>
<h4><code>ERR_HTTP2_TRAILERS_ALREADY_SENT</code><span><a class="mark" href="#all_errors_err_http2_trailers_already_sent" id="all_errors_err_http2_trailers_already_sent">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_trailers_already_sent"></a></h4>
<p>Trailing headers have already been sent on the <code>Http2Stream</code>.</p>
<p><a id="ERR_HTTP2_TRAILERS_NOT_READY"></a></p>
<h4><code>ERR_HTTP2_TRAILERS_NOT_READY</code><span><a class="mark" href="#all_errors_err_http2_trailers_not_ready" id="all_errors_err_http2_trailers_not_ready">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_trailers_not_ready"></a></h4>
<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>
<h4><code>ERR_HTTP2_UNSUPPORTED_PROTOCOL</code><span><a class="mark" href="#all_errors_err_http2_unsupported_protocol" id="all_errors_err_http2_unsupported_protocol">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_unsupported_protocol"></a></h4>
<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_ILLEGAL_CONSTRUCTOR"></a></p>
<h4><code>ERR_ILLEGAL_CONSTRUCTOR</code><span><a class="mark" href="#all_errors_err_illegal_constructor" id="all_errors_err_illegal_constructor">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_illegal_constructor"></a></h4>
<p>An attempt was made to construct an object using a non-public constructor.</p>
<p><a id="ERR_IMPORT_ASSERTION_TYPE_FAILED"></a></p>
<h4><code>ERR_IMPORT_ASSERTION_TYPE_FAILED</code><span><a class="mark" href="#all_errors_err_import_assertion_type_failed" id="all_errors_err_import_assertion_type_failed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_import_assertion_type_failed"></a></h4>
<div class="api_metadata">
<span>Added in: v17.1.0, v16.14.0</span>
</div>
<p>An import <code>type</code> attribute was provided, but the specified module is of a
different type.</p>
<p><a id="ERR_IMPORT_ASSERTION_TYPE_MISSING"></a></p>
<h4><code>ERR_IMPORT_ASSERTION_TYPE_MISSING</code><span><a class="mark" href="#all_errors_err_import_assertion_type_missing" id="all_errors_err_import_assertion_type_missing">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_import_assertion_type_missing"></a></h4>
<div class="api_metadata">
<span>Added in: v17.1.0, v16.14.0</span>
</div>
<p>An import attribute is missing, preventing the specified module to be imported.</p>
<p><a id="ERR_IMPORT_ASSERTION_TYPE_UNSUPPORTED"></a></p>
<h4><code>ERR_IMPORT_ASSERTION_TYPE_UNSUPPORTED</code><span><a class="mark" href="#all_errors_err_import_assertion_type_unsupported" id="all_errors_err_import_assertion_type_unsupported">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_import_assertion_type_unsupported"></a></h4>
<div class="api_metadata">
<span>Added in: v17.1.0, v16.14.0</span>
</div>
<p>An import attribute is not supported by this version of Node.js.</p>
<p><a id="ERR_IMPORT_ATTRIBUTE_UNSUPPORTED"></a></p>
<h4><code>ERR_IMPORT_ATTRIBUTE_UNSUPPORTED</code><span><a class="mark" href="#all_errors_err_import_attribute_unsupported" id="all_errors_err_import_attribute_unsupported">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_import_attribute_unsupported"></a></h4>
<div class="api_metadata">
<span>Added in: v20.10.0</span>
</div>
<p>An import attribute is not supported by this version of Node.js.</p>
<p><a id="ERR_INCOMPATIBLE_OPTION_PAIR"></a></p>
<h4><code>ERR_INCOMPATIBLE_OPTION_PAIR</code><span><a class="mark" href="#all_errors_err_incompatible_option_pair" id="all_errors_err_incompatible_option_pair">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_incompatible_option_pair"></a></h4>
<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>
<h4><code>ERR_INPUT_TYPE_NOT_ALLOWED</code><span><a class="mark" href="#all_errors_err_input_type_not_allowed" id="all_errors_err_input_type_not_allowed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_input_type_not_allowed"></a></h4>
<p></p><div class="api_stability api_stability_1"><a href="#all_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>
<h4><code>ERR_INSPECTOR_ALREADY_ACTIVATED</code><span><a class="mark" href="#all_errors_err_inspector_already_activated" id="all_errors_err_inspector_already_activated">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_inspector_already_activated"></a></h4>
<p>While using the <code>node: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>
<h4><code>ERR_INSPECTOR_ALREADY_CONNECTED</code><span><a class="mark" href="#all_errors_err_inspector_already_connected" id="all_errors_err_inspector_already_connected">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_inspector_already_connected"></a></h4>
<p>While using the <code>node:inspector</code> module, an attempt was made to connect when the
inspector was already connected.</p>
<p><a id="ERR_INSPECTOR_CLOSED"></a></p>
<h4><code>ERR_INSPECTOR_CLOSED</code><span><a class="mark" href="#all_errors_err_inspector_closed" id="all_errors_err_inspector_closed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_inspector_closed"></a></h4>
<p>While using the <code>node: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>
<h4><code>ERR_INSPECTOR_COMMAND</code><span><a class="mark" href="#all_errors_err_inspector_command" id="all_errors_err_inspector_command">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_inspector_command"></a></h4>
<p>An error occurred while issuing a command via the <code>node:inspector</code> module.</p>
<p><a id="ERR_INSPECTOR_NOT_ACTIVE"></a></p>
<h4><code>ERR_INSPECTOR_NOT_ACTIVE</code><span><a class="mark" href="#all_errors_err_inspector_not_active" id="all_errors_err_inspector_not_active">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_inspector_not_active"></a></h4>
<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>
<h4><code>ERR_INSPECTOR_NOT_AVAILABLE</code><span><a class="mark" href="#all_errors_err_inspector_not_available" id="all_errors_err_inspector_not_available">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_inspector_not_available"></a></h4>
<p>The <code>node:inspector</code> module is not available for use.</p>
<p><a id="ERR_INSPECTOR_NOT_CONNECTED"></a></p>
<h4><code>ERR_INSPECTOR_NOT_CONNECTED</code><span><a class="mark" href="#all_errors_err_inspector_not_connected" id="all_errors_err_inspector_not_connected">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_inspector_not_connected"></a></h4>
<p>While using the <code>node: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>
<h4><code>ERR_INSPECTOR_NOT_WORKER</code><span><a class="mark" href="#all_errors_err_inspector_not_worker" id="all_errors_err_inspector_not_worker">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_inspector_not_worker"></a></h4>
<p>An API was called on the main thread that can only be used from
the worker thread.</p>
<p><a id="ERR_INTERNAL_ASSERTION"></a></p>
<h4><code>ERR_INTERNAL_ASSERTION</code><span><a class="mark" href="#all_errors_err_internal_assertion" id="all_errors_err_internal_assertion">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_internal_assertion"></a></h4>
<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_INVALID_ADDRESS"></a></p>
<h4><code>ERR_INVALID_ADDRESS</code><span><a class="mark" href="#all_errors_err_invalid_address" id="all_errors_err_invalid_address">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_address"></a></h4>
<p>The provided address is not understood by the Node.js API.</p>
<p><a id="ERR_INVALID_ADDRESS_FAMILY"></a></p>
<h4><code>ERR_INVALID_ADDRESS_FAMILY</code><span><a class="mark" href="#all_errors_err_invalid_address_family" id="all_errors_err_invalid_address_family">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_address_family"></a></h4>
<p>The provided address family is not understood by the Node.js API.</p>
<p><a id="ERR_INVALID_ARG_TYPE"></a></p>
<h4><code>ERR_INVALID_ARG_TYPE</code><span><a class="mark" href="#all_errors_err_invalid_arg_type" id="all_errors_err_invalid_arg_type">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_arg_type"></a></h4>
<p>An argument of the wrong type was passed to a Node.js API.</p>
<p><a id="ERR_INVALID_ARG_VALUE"></a></p>
<h4><code>ERR_INVALID_ARG_VALUE</code><span><a class="mark" href="#all_errors_err_invalid_arg_value" id="all_errors_err_invalid_arg_value">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_arg_value"></a></h4>
<p>An invalid or unsupported value was passed for a given argument.</p>
<p><a id="ERR_INVALID_ASYNC_ID"></a></p>
<h4><code>ERR_INVALID_ASYNC_ID</code><span><a class="mark" href="#all_errors_err_invalid_async_id" id="all_errors_err_invalid_async_id">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_async_id"></a></h4>
<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>
<h4><code>ERR_INVALID_BUFFER_SIZE</code><span><a class="mark" href="#all_errors_err_invalid_buffer_size" id="all_errors_err_invalid_buffer_size">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_buffer_size"></a></h4>
<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_CHAR"></a></p>
<h4><code>ERR_INVALID_CHAR</code><span><a class="mark" href="#all_errors_err_invalid_char" id="all_errors_err_invalid_char">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_char"></a></h4>
<p>Invalid characters were detected in headers.</p>
<p><a id="ERR_INVALID_CURSOR_POS"></a></p>
<h4><code>ERR_INVALID_CURSOR_POS</code><span><a class="mark" href="#all_errors_err_invalid_cursor_pos" id="all_errors_err_invalid_cursor_pos">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_cursor_pos"></a></h4>
<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>
<h4><code>ERR_INVALID_FD</code><span><a class="mark" href="#all_errors_err_invalid_fd" id="all_errors_err_invalid_fd">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_fd"></a></h4>
<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>
<h4><code>ERR_INVALID_FD_TYPE</code><span><a class="mark" href="#all_errors_err_invalid_fd_type" id="all_errors_err_invalid_fd_type">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_fd_type"></a></h4>
<p>A file descriptor ('fd') type was not valid.</p>
<p><a id="ERR_INVALID_FILE_URL_HOST"></a></p>
<h4><code>ERR_INVALID_FILE_URL_HOST</code><span><a class="mark" href="#all_errors_err_invalid_file_url_host" id="all_errors_err_invalid_file_url_host">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_file_url_host"></a></h4>
<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>
<h4><code>ERR_INVALID_FILE_URL_PATH</code><span><a class="mark" href="#all_errors_err_invalid_file_url_path" id="all_errors_err_invalid_file_url_path">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_file_url_path"></a></h4>
<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>
<h4><code>ERR_INVALID_HANDLE_TYPE</code><span><a class="mark" href="#all_errors_err_invalid_handle_type" id="all_errors_err_invalid_handle_type">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_handle_type"></a></h4>
<p>An attempt was made to send an unsupported "handle" over an IPC communication
channel to a child process. See <a href="#all_child_process_subprocesssendmessage-sendhandle-options-callback"><code>subprocess.send()</code></a> and <a href="#all_process_processsendmessage-sendhandle-options-callback"><code>process.send()</code></a>
for more information.</p>
<p><a id="ERR_INVALID_HTTP_TOKEN"></a></p>
<h4><code>ERR_INVALID_HTTP_TOKEN</code><span><a class="mark" href="#all_errors_err_invalid_http_token" id="all_errors_err_invalid_http_token">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_http_token"></a></h4>
<p>An invalid HTTP token was supplied.</p>
<p><a id="ERR_INVALID_IP_ADDRESS"></a></p>
<h4><code>ERR_INVALID_IP_ADDRESS</code><span><a class="mark" href="#all_errors_err_invalid_ip_address" id="all_errors_err_invalid_ip_address">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_ip_address"></a></h4>
<p>An IP address is not valid.</p>
<p><a id="ERR_INVALID_MIME_SYNTAX"></a></p>
<h4><code>ERR_INVALID_MIME_SYNTAX</code><span><a class="mark" href="#all_errors_err_invalid_mime_syntax" id="all_errors_err_invalid_mime_syntax">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_mime_syntax"></a></h4>
<p>The syntax of a MIME is not valid.</p>
<p><a id="ERR_INVALID_MODULE"></a></p>
<h4><code>ERR_INVALID_MODULE</code><span><a class="mark" href="#all_errors_err_invalid_module" id="all_errors_err_invalid_module">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_module"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0, v14.18.0</span>
</div>
<p>An attempt was made to load a module that does not exist or was otherwise not
valid.</p>
<p><a id="ERR_INVALID_MODULE_SPECIFIER"></a></p>
<h4><code>ERR_INVALID_MODULE_SPECIFIER</code><span><a class="mark" href="#all_errors_err_invalid_module_specifier" id="all_errors_err_invalid_module_specifier">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_module_specifier"></a></h4>
<p>The imported module string is an invalid URL, package name, or package subpath
specifier.</p>
<p><a id="ERR_INVALID_OBJECT_DEFINE_PROPERTY"></a></p>
<h4><code>ERR_INVALID_OBJECT_DEFINE_PROPERTY</code><span><a class="mark" href="#all_errors_err_invalid_object_define_property" id="all_errors_err_invalid_object_define_property">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_object_define_property"></a></h4>
<p>An error occurred while setting an invalid attribute on the property of
an object.</p>
<p><a id="ERR_INVALID_PACKAGE_CONFIG"></a></p>
<h4><code>ERR_INVALID_PACKAGE_CONFIG</code><span><a class="mark" href="#all_errors_err_invalid_package_config" id="all_errors_err_invalid_package_config">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_package_config"></a></h4>
<p>An invalid <a href="#all_packages_nodejs-packagejson-field-definitions"><code>package.json</code></a> file failed parsing.</p>
<p><a id="ERR_INVALID_PACKAGE_TARGET"></a></p>
<h4><code>ERR_INVALID_PACKAGE_TARGET</code><span><a class="mark" href="#all_errors_err_invalid_package_target" id="all_errors_err_invalid_package_target">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_package_target"></a></h4>
<p>The <code>package.json</code> <a href="#all_packages_exports"><code>"exports"</code></a> field contains an invalid target mapping
value for the attempted module resolution.</p>
<p><a id="ERR_INVALID_PERFORMANCE_MARK"></a></p>
<h4><code>ERR_INVALID_PERFORMANCE_MARK</code><span><a class="mark" href="#all_errors_err_invalid_performance_mark" id="all_errors_err_invalid_performance_mark">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_performance_mark"></a></h4>
<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>
<h4><code>ERR_INVALID_PROTOCOL</code><span><a class="mark" href="#all_errors_err_invalid_protocol" id="all_errors_err_invalid_protocol">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_protocol"></a></h4>
<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>
<h4><code>ERR_INVALID_REPL_EVAL_CONFIG</code><span><a class="mark" href="#all_errors_err_invalid_repl_eval_config" id="all_errors_err_invalid_repl_eval_config">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_repl_eval_config"></a></h4>
<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>
<h4><code>ERR_INVALID_REPL_INPUT</code><span><a class="mark" href="#all_errors_err_invalid_repl_input" id="all_errors_err_invalid_repl_input">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_repl_input"></a></h4>
<p>The input may not be used in the <a href="repl.html"><code>REPL</code></a>. The conditions under which this
error is used are described in the <a href="repl.html"><code>REPL</code></a> documentation.</p>
<p><a id="ERR_INVALID_RETURN_PROPERTY"></a></p>
<h4><code>ERR_INVALID_RETURN_PROPERTY</code><span><a class="mark" href="#all_errors_err_invalid_return_property" id="all_errors_err_invalid_return_property">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_return_property"></a></h4>
<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>
<h4><code>ERR_INVALID_RETURN_PROPERTY_VALUE</code><span><a class="mark" href="#all_errors_err_invalid_return_property_value" id="all_errors_err_invalid_return_property_value">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_return_property_value"></a></h4>
<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>
<h4><code>ERR_INVALID_RETURN_VALUE</code><span><a class="mark" href="#all_errors_err_invalid_return_value" id="all_errors_err_invalid_return_value">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_return_value"></a></h4>
<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_STATE"></a></p>
<h4><code>ERR_INVALID_STATE</code><span><a class="mark" href="#all_errors_err_invalid_state" id="all_errors_err_invalid_state">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_state"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>Indicates that an operation cannot be completed due to an invalid state.
For instance, an object may have already been destroyed, or may be
performing another operation.</p>
<p><a id="ERR_INVALID_SYNC_FORK_INPUT"></a></p>
<h4><code>ERR_INVALID_SYNC_FORK_INPUT</code><span><a class="mark" href="#all_errors_err_invalid_sync_fork_input" id="all_errors_err_invalid_sync_fork_input">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_sync_fork_input"></a></h4>
<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>
<h4><code>ERR_INVALID_THIS</code><span><a class="mark" href="#all_errors_err_invalid_this" id="all_errors_err_invalid_this">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_this"></a></h4>
<p>A Node.js API function was called with an incompatible <code>this</code> value.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> urlSearchParams = <span class="hljs-keyword">new</span> <span class="hljs-title class_">URLSearchParams</span>(<span class="hljs-string">'foo=bar&#x26;baz=new'</span>);

<span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">1</span>);
urlSearchParams.<span class="hljs-property">has</span>.<span class="hljs-title function_">call</span>(buf, <span class="hljs-string">'foo'</span>);
<span class="hljs-comment">// Throws a TypeError with code 'ERR_INVALID_THIS'</span></code> <button class="copy-button">copy</button></pre>
<p><a id="ERR_INVALID_TRANSFER_OBJECT"></a></p>
<h4><code>ERR_INVALID_TRANSFER_OBJECT</code><span><a class="mark" href="#all_errors_err_invalid_transfer_object" id="all_errors_err_invalid_transfer_object">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_transfer_object"></a></h4>
<p>An invalid transfer object was passed to <code>postMessage()</code>.</p>
<p><a id="ERR_INVALID_TUPLE"></a></p>
<h4><code>ERR_INVALID_TUPLE</code><span><a class="mark" href="#all_errors_err_invalid_tuple" id="all_errors_err_invalid_tuple">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_tuple"></a></h4>
<p>An element in the <code>iterable</code> provided to the <a href="#all_url_the-whatwg-url-api">WHATWG</a>
<a href="#all_url_new-urlsearchparamsiterable"><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>
<h4><code>ERR_INVALID_URI</code><span><a class="mark" href="#all_errors_err_invalid_uri" id="all_errors_err_invalid_uri">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_uri"></a></h4>
<p>An invalid URI was passed.</p>
<p><a id="ERR_INVALID_URL"></a></p>
<h4><code>ERR_INVALID_URL</code><span><a class="mark" href="#all_errors_err_invalid_url" id="all_errors_err_invalid_url">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_url"></a></h4>
<p>An invalid URL was passed to the <a href="#all_url_the-whatwg-url-api">WHATWG</a> <a href="#all_url_new-urlinput-base"><code>URL</code>
constructor</a> or the legacy <a href="#all_url_urlparseurlstring-parsequerystring-slashesdenotehost"><code>url.parse()</code></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>
<h4><code>ERR_INVALID_URL_SCHEME</code><span><a class="mark" href="#all_errors_err_invalid_url_scheme" id="all_errors_err_invalid_url_scheme">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_url_scheme"></a></h4>
<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="#all_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>
<h4><code>ERR_IPC_CHANNEL_CLOSED</code><span><a class="mark" href="#all_errors_err_ipc_channel_closed" id="all_errors_err_ipc_channel_closed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_ipc_channel_closed"></a></h4>
<p>An attempt was made to use an IPC communication channel that was already closed.</p>
<p><a id="ERR_IPC_DISCONNECTED"></a></p>
<h4><code>ERR_IPC_DISCONNECTED</code><span><a class="mark" href="#all_errors_err_ipc_disconnected" id="all_errors_err_ipc_disconnected">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_ipc_disconnected"></a></h4>
<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>
<h4><code>ERR_IPC_ONE_PIPE</code><span><a class="mark" href="#all_errors_err_ipc_one_pipe" id="all_errors_err_ipc_one_pipe">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_ipc_one_pipe"></a></h4>
<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>
<h4><code>ERR_IPC_SYNC_FORK</code><span><a class="mark" href="#all_errors_err_ipc_sync_fork" id="all_errors_err_ipc_sync_fork">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_ipc_sync_fork"></a></h4>
<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_LOADER_CHAIN_INCOMPLETE"></a></p>
<h4><code>ERR_LOADER_CHAIN_INCOMPLETE</code><span><a class="mark" href="#all_errors_err_loader_chain_incomplete" id="all_errors_err_loader_chain_incomplete">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_loader_chain_incomplete"></a></h4>
<div class="api_metadata">
<span>Added in: v18.6.0, v16.17.0</span>
</div>
<p>An ESM loader hook returned without calling <code>next()</code> and without explicitly
signaling a short circuit.</p>
<p><a id="ERR_MANIFEST_ASSERT_INTEGRITY"></a></p>
<h4><code>ERR_MANIFEST_ASSERT_INTEGRITY</code><span><a class="mark" href="#all_errors_err_manifest_assert_integrity" id="all_errors_err_manifest_assert_integrity">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_manifest_assert_integrity"></a></h4>
<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="#all_permissions_policies">policy</a>
manifests for more information.</p>
<p><a id="ERR_MANIFEST_DEPENDENCY_MISSING"></a></p>
<h4><code>ERR_MANIFEST_DEPENDENCY_MISSING</code><span><a class="mark" href="#all_errors_err_manifest_dependency_missing" id="all_errors_err_manifest_dependency_missing">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_manifest_dependency_missing"></a></h4>
<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="#all_permissions_policies">policy</a> manifests for more information.</p>
<p><a id="ERR_MANIFEST_INTEGRITY_MISMATCH"></a></p>
<h4><code>ERR_MANIFEST_INTEGRITY_MISMATCH</code><span><a class="mark" href="#all_errors_err_manifest_integrity_mismatch" id="all_errors_err_manifest_integrity_mismatch">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_manifest_integrity_mismatch"></a></h4>
<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="#all_permissions_policies">policy</a> manifests for more information.</p>
<p><a id="ERR_MANIFEST_INVALID_RESOURCE_FIELD"></a></p>
<h4><code>ERR_MANIFEST_INVALID_RESOURCE_FIELD</code><span><a class="mark" href="#all_errors_err_manifest_invalid_resource_field" id="all_errors_err_manifest_invalid_resource_field">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_manifest_invalid_resource_field"></a></h4>
<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="#all_permissions_policies">policy</a> manifests for more information.</p>
<p><a id="ERR_MANIFEST_INVALID_SPECIFIER"></a></p>
<h4><code>ERR_MANIFEST_INVALID_SPECIFIER</code><span><a class="mark" href="#all_errors_err_manifest_invalid_specifier" id="all_errors_err_manifest_invalid_specifier">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_manifest_invalid_specifier"></a></h4>
<p>A policy manifest resource had an invalid value for one of its dependency
mappings. Update the manifest entry to match to resolve this error. See the
documentation for <a href="#all_permissions_policies">policy</a> manifests for more information.</p>
<p><a id="ERR_MANIFEST_PARSE_POLICY"></a></p>
<h4><code>ERR_MANIFEST_PARSE_POLICY</code><span><a class="mark" href="#all_errors_err_manifest_parse_policy" id="all_errors_err_manifest_parse_policy">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_manifest_parse_policy"></a></h4>
<p>An attempt was made to load a policy manifest, but the manifest was unable to
be parsed. See the documentation for <a href="#all_permissions_policies">policy</a> manifests for more information.</p>
<p><a id="ERR_MANIFEST_TDZ"></a></p>
<h4><code>ERR_MANIFEST_TDZ</code><span><a class="mark" href="#all_errors_err_manifest_tdz" id="all_errors_err_manifest_tdz">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_manifest_tdz"></a></h4>
<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>
<h4><code>ERR_MANIFEST_UNKNOWN_ONERROR</code><span><a class="mark" href="#all_errors_err_manifest_unknown_onerror" id="all_errors_err_manifest_unknown_onerror">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_manifest_unknown_onerror"></a></h4>
<p>A policy manifest was loaded, but had an unknown value for its "onerror"
behavior. See the documentation for <a href="#all_permissions_policies">policy</a> manifests for more information.</p>
<p><a id="ERR_MEMORY_ALLOCATION_FAILED"></a></p>
<h4><code>ERR_MEMORY_ALLOCATION_FAILED</code><span><a class="mark" href="#all_errors_err_memory_allocation_failed" id="all_errors_err_memory_allocation_failed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_memory_allocation_failed"></a></h4>
<p>An attempt was made to allocate memory (usually in the C++ layer) but it
failed.</p>
<p><a id="ERR_MESSAGE_TARGET_CONTEXT_UNAVAILABLE"></a></p>
<h4><code>ERR_MESSAGE_TARGET_CONTEXT_UNAVAILABLE</code><span><a class="mark" href="#all_errors_err_message_target_context_unavailable" id="all_errors_err_message_target_context_unavailable">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_message_target_context_unavailable"></a></h4>
<div class="api_metadata">
<span>Added in: v14.5.0, v12.19.0</span>
</div>
<p>A message posted to a <a href="#all_worker_threads_class-messageport"><code>MessagePort</code></a> could not be deserialized in the target
<a href="vm.html">vm</a> <code>Context</code>. Not all Node.js objects can be successfully instantiated in
any context at this time, and attempting to transfer them using <code>postMessage()</code>
can fail on the receiving side in that case.</p>
<p><a id="ERR_METHOD_NOT_IMPLEMENTED"></a></p>
<h4><code>ERR_METHOD_NOT_IMPLEMENTED</code><span><a class="mark" href="#all_errors_err_method_not_implemented" id="all_errors_err_method_not_implemented">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_method_not_implemented"></a></h4>
<p>A method is required but not implemented.</p>
<p><a id="ERR_MISSING_ARGS"></a></p>
<h4><code>ERR_MISSING_ARGS</code><span><a class="mark" href="#all_errors_err_missing_args" id="all_errors_err_missing_args">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_missing_args"></a></h4>
<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="#all_errors_err_invalid_arg_type"><code>ERR_INVALID_ARG_TYPE</code></a> error code may be used instead.</p>
<p><a id="ERR_MISSING_OPTION"></a></p>
<h4><code>ERR_MISSING_OPTION</code><span><a class="mark" href="#all_errors_err_missing_option" id="all_errors_err_missing_option">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_missing_option"></a></h4>
<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_PASSPHRASE"></a></p>
<h4><code>ERR_MISSING_PASSPHRASE</code><span><a class="mark" href="#all_errors_err_missing_passphrase" id="all_errors_err_missing_passphrase">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_missing_passphrase"></a></h4>
<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>
<h4><code>ERR_MISSING_PLATFORM_FOR_WORKER</code><span><a class="mark" href="#all_errors_err_missing_platform_for_worker" id="all_errors_err_missing_platform_for_worker">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_missing_platform_for_worker"></a></h4>
<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_MISSING_TRANSFERABLE_IN_TRANSFER_LIST"></a></p>
<h4><code>ERR_MISSING_TRANSFERABLE_IN_TRANSFER_LIST</code><span><a class="mark" href="#all_errors_err_missing_transferable_in_transfer_list" id="all_errors_err_missing_transferable_in_transfer_list">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_missing_transferable_in_transfer_list"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>An object that needs to be explicitly listed in the <code>transferList</code> argument
is in the object passed to a <a href="#all_worker_threads_portpostmessagevalue-transferlist"><code>postMessage()</code></a> call, but is not provided
in the <code>transferList</code> for that call. Usually, this is a <code>MessagePort</code>.</p>
<p>In Node.js versions prior to v15.0.0, the error code being used here was
<a href="#all_errors_err_missing_message_port_in_transfer_list"><code>ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST</code></a>. However, the set of
transferable object types has been expanded to cover more types than
<code>MessagePort</code>.</p>
<p><a id="ERR_MODULE_NOT_FOUND"></a></p>
<h4><code>ERR_MODULE_NOT_FOUND</code><span><a class="mark" href="#all_errors_err_module_not_found" id="all_errors_err_module_not_found">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_module_not_found"></a></h4>
<p>A module file could not be resolved by the ECMAScript modules loader while
attempting an <code>import</code> operation or when loading the program entry point.</p>
<p><a id="ERR_MULTIPLE_CALLBACK"></a></p>
<h4><code>ERR_MULTIPLE_CALLBACK</code><span><a class="mark" href="#all_errors_err_multiple_callback" id="all_errors_err_multiple_callback">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_multiple_callback"></a></h4>
<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>
<h4><code>ERR_NAPI_CONS_FUNCTION</code><span><a class="mark" href="#all_errors_err_napi_cons_function" id="all_errors_err_napi_cons_function">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_napi_cons_function"></a></h4>
<p>While using <code>Node-API</code>, a constructor passed was not a function.</p>
<p><a id="ERR_NAPI_INVALID_DATAVIEW_ARGS"></a></p>
<h4><code>ERR_NAPI_INVALID_DATAVIEW_ARGS</code><span><a class="mark" href="#all_errors_err_napi_invalid_dataview_args" id="all_errors_err_napi_invalid_dataview_args">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_napi_invalid_dataview_args"></a></h4>
<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>
<h4><code>ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT</code><span><a class="mark" href="#all_errors_err_napi_invalid_typedarray_alignment" id="all_errors_err_napi_invalid_typedarray_alignment">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_napi_invalid_typedarray_alignment"></a></h4>
<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>
<h4><code>ERR_NAPI_INVALID_TYPEDARRAY_LENGTH</code><span><a class="mark" href="#all_errors_err_napi_invalid_typedarray_length" id="all_errors_err_napi_invalid_typedarray_length">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_napi_invalid_typedarray_length"></a></h4>
<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>
<h4><code>ERR_NAPI_TSFN_CALL_JS</code><span><a class="mark" href="#all_errors_err_napi_tsfn_call_js" id="all_errors_err_napi_tsfn_call_js">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_napi_tsfn_call_js"></a></h4>
<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>
<h4><code>ERR_NAPI_TSFN_GET_UNDEFINED</code><span><a class="mark" href="#all_errors_err_napi_tsfn_get_undefined" id="all_errors_err_napi_tsfn_get_undefined">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_napi_tsfn_get_undefined"></a></h4>
<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>
<h4><code>ERR_NAPI_TSFN_START_IDLE_LOOP</code><span><a class="mark" href="#all_errors_err_napi_tsfn_start_idle_loop" id="all_errors_err_napi_tsfn_start_idle_loop">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_napi_tsfn_start_idle_loop"></a></h4>
<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>
<h4><code>ERR_NAPI_TSFN_STOP_IDLE_LOOP</code><span><a class="mark" href="#all_errors_err_napi_tsfn_stop_idle_loop" id="all_errors_err_napi_tsfn_stop_idle_loop">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_napi_tsfn_stop_idle_loop"></a></h4>
<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_NOT_BUILDING_SNAPSHOT"></a></p>
<h4><code>ERR_NOT_BUILDING_SNAPSHOT</code><span><a class="mark" href="#all_errors_err_not_building_snapshot" id="all_errors_err_not_building_snapshot">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_not_building_snapshot"></a></h4>
<p>An attempt was made to use operations that can only be used when building
V8 startup snapshot even though Node.js isn't building one.</p>
<p><a id="ERR_NOT_IN_SINGLE_EXECUTABLE_APPLICATION"></a></p>
<h4><code>ERR_NOT_IN_SINGLE_EXECUTABLE_APPLICATION</code><span><a class="mark" href="#all_errors_err_not_in_single_executable_application" id="all_errors_err_not_in_single_executable_application">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_not_in_single_executable_application"></a></h4>
<div class="api_metadata">
<span>Added in: v20.12.0</span>
</div>
<p>The operation cannot be performed when it's not in a single-executable
application.</p>
<p><a id="ERR_NOT_SUPPORTED_IN_SNAPSHOT"></a></p>
<h4><code>ERR_NOT_SUPPORTED_IN_SNAPSHOT</code><span><a class="mark" href="#all_errors_err_not_supported_in_snapshot" id="all_errors_err_not_supported_in_snapshot">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_not_supported_in_snapshot"></a></h4>
<p>An attempt was made to perform operations that are not supported when
building a startup snapshot.</p>
<p><a id="ERR_NO_CRYPTO"></a></p>
<h4><code>ERR_NO_CRYPTO</code><span><a class="mark" href="#all_errors_err_no_crypto" id="all_errors_err_no_crypto">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_no_crypto"></a></h4>
<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>
<h4><code>ERR_NO_ICU</code><span><a class="mark" href="#all_errors_err_no_icu" id="all_errors_err_no_icu">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_no_icu"></a></h4>
<p>An attempt was made to use features that require <a href="#all_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>
<h4><code>ERR_NON_CONTEXT_AWARE_DISABLED</code><span><a class="mark" href="#all_errors_err_non_context_aware_disabled" id="all_errors_err_non_context_aware_disabled">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_non_context_aware_disabled"></a></h4>
<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>
<h4><code>ERR_OUT_OF_RANGE</code><span><a class="mark" href="#all_errors_err_out_of_range" id="all_errors_err_out_of_range">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_out_of_range"></a></h4>
<p>A given value is out of the accepted range.</p>
<p><a id="ERR_PACKAGE_IMPORT_NOT_DEFINED"></a></p>
<h4><code>ERR_PACKAGE_IMPORT_NOT_DEFINED</code><span><a class="mark" href="#all_errors_err_package_import_not_defined" id="all_errors_err_package_import_not_defined">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_package_import_not_defined"></a></h4>
<p>The <code>package.json</code> <a href="#all_packages_imports"><code>"imports"</code></a> field does not define the given internal
package specifier mapping.</p>
<p><a id="ERR_PACKAGE_PATH_NOT_EXPORTED"></a></p>
<h4><code>ERR_PACKAGE_PATH_NOT_EXPORTED</code><span><a class="mark" href="#all_errors_err_package_path_not_exported" id="all_errors_err_package_path_not_exported">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_package_path_not_exported"></a></h4>
<p>The <code>package.json</code> <a href="#all_packages_exports"><code>"exports"</code></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_PARSE_ARGS_INVALID_OPTION_VALUE"></a></p>
<h4><code>ERR_PARSE_ARGS_INVALID_OPTION_VALUE</code><span><a class="mark" href="#all_errors_err_parse_args_invalid_option_value" id="all_errors_err_parse_args_invalid_option_value">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_parse_args_invalid_option_value"></a></h4>
<div class="api_metadata">
<span>Added in: v18.3.0, v16.17.0</span>
</div>
<p>When <code>strict</code> set to <code>true</code>, thrown by <a href="#all_util_utilparseargsconfig"><code>util.parseArgs()</code></a> if a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a>
value is provided for an option of type <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a>, or if a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a>
value is provided for an option of type <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a>.</p>
<p><a id="ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL"></a></p>
<h4><code>ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL</code><span><a class="mark" href="#all_errors_err_parse_args_unexpected_positional" id="all_errors_err_parse_args_unexpected_positional">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_parse_args_unexpected_positional"></a></h4>
<div class="api_metadata">
<span>Added in: v18.3.0, v16.17.0</span>
</div>
<p>Thrown by <a href="#all_util_utilparseargsconfig"><code>util.parseArgs()</code></a>, when a positional argument is provided and
<code>allowPositionals</code> is set to <code>false</code>.</p>
<p><a id="ERR_PARSE_ARGS_UNKNOWN_OPTION"></a></p>
<h4><code>ERR_PARSE_ARGS_UNKNOWN_OPTION</code><span><a class="mark" href="#all_errors_err_parse_args_unknown_option" id="all_errors_err_parse_args_unknown_option">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_parse_args_unknown_option"></a></h4>
<div class="api_metadata">
<span>Added in: v18.3.0, v16.17.0</span>
</div>
<p>When <code>strict</code> set to <code>true</code>, thrown by <a href="#all_util_utilparseargsconfig"><code>util.parseArgs()</code></a> if an argument
is not configured in <code>options</code>.</p>
<p><a id="ERR_PERFORMANCE_INVALID_TIMESTAMP"></a></p>
<h4><code>ERR_PERFORMANCE_INVALID_TIMESTAMP</code><span><a class="mark" href="#all_errors_err_performance_invalid_timestamp" id="all_errors_err_performance_invalid_timestamp">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_performance_invalid_timestamp"></a></h4>
<p>An invalid timestamp value was provided for a performance mark or measure.</p>
<p><a id="ERR_PERFORMANCE_MEASURE_INVALID_OPTIONS"></a></p>
<h4><code>ERR_PERFORMANCE_MEASURE_INVALID_OPTIONS</code><span><a class="mark" href="#all_errors_err_performance_measure_invalid_options" id="all_errors_err_performance_measure_invalid_options">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_performance_measure_invalid_options"></a></h4>
<p>Invalid options were provided for a performance measure.</p>
<p><a id="ERR_PROTO_ACCESS"></a></p>
<h4><code>ERR_PROTO_ACCESS</code><span><a class="mark" href="#all_errors_err_proto_access" id="all_errors_err_proto_access">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_proto_access"></a></h4>
<p>Accessing <code>Object.prototype.__proto__</code> has been forbidden using
<a href="#all_cli_--disable-protomode"><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_CYCLE_MODULE"></a></p>
<h4><code>ERR_REQUIRE_CYCLE_MODULE</code><span><a class="mark" href="#all_errors_err_require_cycle_module" id="all_errors_err_require_cycle_module">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_require_cycle_module"></a></h4>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>When trying to <code>require()</code> a <a href="esm.html">ES Module</a> under <code>--experimental-require-module</code>,
a CommonJS to ESM or ESM to CommonJS edge participates in an immediate cycle.
This is not allowed because ES Modules cannot be evaluated while they are
already being evaluated.</p>
<p>To avoid the cycle, the <code>require()</code> call involved in a cycle should not happen
at the top-level of either an ES Module (via <code>createRequire()</code>) or a CommonJS
module, and should be done lazily in an inner function.</p>
<p><a id="ERR_REQUIRE_ASYNC_MODULE"></a></p>
<h4><code>ERR_REQUIRE_ASYNC_MODULE</code><span><a class="mark" href="#all_errors_err_require_async_module" id="all_errors_err_require_async_module">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_require_async_module"></a></h4>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>When trying to <code>require()</code> a <a href="esm.html">ES Module</a> under <code>--experimental-require-module</code>,
the module turns out to be asynchronous. That is, it contains top-level await.</p>
<p>To see where the top-level await is, use
<code>--experimental-print-required-tla</code> (this would execute the modules
before looking for the top-level awaits).</p>
<p><a id="ERR_REQUIRE_ESM"></a></p>
<h4><code>ERR_REQUIRE_ESM</code><span><a class="mark" href="#all_errors_err_require_esm" id="all_errors_err_require_esm">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_require_esm"></a></h4>
<p></p><div class="api_stability api_stability_1"><a href="#all_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>To enable <code>require()</code> for synchronous module graphs (without
top-level <code>await</code>), use <code>--experimental-require-module</code>.</p>
<p><a id="ERR_SCRIPT_EXECUTION_INTERRUPTED"></a></p>
<h4><code>ERR_SCRIPT_EXECUTION_INTERRUPTED</code><span><a class="mark" href="#all_errors_err_script_execution_interrupted" id="all_errors_err_script_execution_interrupted">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_script_execution_interrupted"></a></h4>
<p>Script execution was interrupted by <code>SIGINT</code> (For
example, <kbd>Ctrl</kbd>+<kbd>C</kbd> was pressed.)</p>
<p><a id="ERR_SCRIPT_EXECUTION_TIMEOUT"></a></p>
<h4><code>ERR_SCRIPT_EXECUTION_TIMEOUT</code><span><a class="mark" href="#all_errors_err_script_execution_timeout" id="all_errors_err_script_execution_timeout">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_script_execution_timeout"></a></h4>
<p>Script execution timed out, possibly due to bugs in the script being executed.</p>
<p><a id="ERR_SERVER_ALREADY_LISTEN"></a></p>
<h4><code>ERR_SERVER_ALREADY_LISTEN</code><span><a class="mark" href="#all_errors_err_server_already_listen" id="all_errors_err_server_already_listen">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_server_already_listen"></a></h4>
<p>The <a href="#all_net_serverlisten"><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>
<h4><code>ERR_SERVER_NOT_RUNNING</code><span><a class="mark" href="#all_errors_err_server_not_running" id="all_errors_err_server_not_running">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_server_not_running"></a></h4>
<p>The <a href="#all_net_serverclosecallback"><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_SINGLE_EXECUTABLE_APPLICATION_ASSET_NOT_FOUND"></a></p>
<h4><code>ERR_SINGLE_EXECUTABLE_APPLICATION_ASSET_NOT_FOUND</code><span><a class="mark" href="#all_errors_err_single_executable_application_asset_not_found" id="all_errors_err_single_executable_application_asset_not_found">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_single_executable_application_asset_not_found"></a></h4>
<div class="api_metadata">
<span>Added in: v20.12.0</span>
</div>
<p>A key was passed to single executable application APIs to identify an asset,
but no match could be found.</p>
<p><a id="ERR_SOCKET_ALREADY_BOUND"></a></p>
<h4><code>ERR_SOCKET_ALREADY_BOUND</code><span><a class="mark" href="#all_errors_err_socket_already_bound" id="all_errors_err_socket_already_bound">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_socket_already_bound"></a></h4>
<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>
<h4><code>ERR_SOCKET_BAD_BUFFER_SIZE</code><span><a class="mark" href="#all_errors_err_socket_bad_buffer_size" id="all_errors_err_socket_bad_buffer_size">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_socket_bad_buffer_size"></a></h4>
<p>An invalid (negative) size was passed for either the <code>recvBufferSize</code> or
<code>sendBufferSize</code> options in <a href="#all_dgram_dgramcreatesocketoptions-callback"><code>dgram.createSocket()</code></a>.</p>
<p><a id="ERR_SOCKET_BAD_PORT"></a></p>
<h4><code>ERR_SOCKET_BAD_PORT</code><span><a class="mark" href="#all_errors_err_socket_bad_port" id="all_errors_err_socket_bad_port">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_socket_bad_port"></a></h4>
<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>
<h4><code>ERR_SOCKET_BAD_TYPE</code><span><a class="mark" href="#all_errors_err_socket_bad_type" id="all_errors_err_socket_bad_type">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_socket_bad_type"></a></h4>
<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>
<h4><code>ERR_SOCKET_BUFFER_SIZE</code><span><a class="mark" href="#all_errors_err_socket_buffer_size" id="all_errors_err_socket_buffer_size">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_socket_buffer_size"></a></h4>
<p>While using <a href="#all_dgram_dgramcreatesocketoptions-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_CLOSED"></a></p>
<h4><code>ERR_SOCKET_CLOSED</code><span><a class="mark" href="#all_errors_err_socket_closed" id="all_errors_err_socket_closed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_socket_closed"></a></h4>
<p>An attempt was made to operate on an already closed socket.</p>
<p><a id="ERR_SOCKET_CLOSED_BEFORE_CONNECTION"></a></p>
<h4><code>ERR_SOCKET_CLOSED_BEFORE_CONNECTION</code><span><a class="mark" href="#all_errors_err_socket_closed_before_connection" id="all_errors_err_socket_closed_before_connection">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_socket_closed_before_connection"></a></h4>
<p>When calling <a href="#all_net_socketwritedata-encoding-callback"><code>net.Socket.write()</code></a> on a connecting socket and the socket was
closed before the connection was established.</p>
<p><a id="ERR_SOCKET_CONNECTION_TIMEOUT"></a></p>
<h4><code>ERR_SOCKET_CONNECTION_TIMEOUT</code><span><a class="mark" href="#all_errors_err_socket_connection_timeout" id="all_errors_err_socket_connection_timeout">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_socket_connection_timeout"></a></h4>
<p>The socket was unable to connect to any address returned by the DNS within the
allowed timeout when using the family autoselection algorithm.</p>
<p><a id="ERR_SOCKET_DGRAM_IS_CONNECTED"></a></p>
<h4><code>ERR_SOCKET_DGRAM_IS_CONNECTED</code><span><a class="mark" href="#all_errors_err_socket_dgram_is_connected" id="all_errors_err_socket_dgram_is_connected">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_socket_dgram_is_connected"></a></h4>
<p>A <a href="#all_dgram_socketconnectport-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>
<h4><code>ERR_SOCKET_DGRAM_NOT_CONNECTED</code><span><a class="mark" href="#all_errors_err_socket_dgram_not_connected" id="all_errors_err_socket_dgram_not_connected">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_socket_dgram_not_connected"></a></h4>
<p>A <a href="#all_dgram_socketdisconnect"><code>dgram.disconnect()</code></a> or <a href="#all_dgram_socketremoteaddress"><code>dgram.remoteAddress()</code></a> call was made on a
disconnected socket.</p>
<p><a id="ERR_SOCKET_DGRAM_NOT_RUNNING"></a></p>
<h4><code>ERR_SOCKET_DGRAM_NOT_RUNNING</code><span><a class="mark" href="#all_errors_err_socket_dgram_not_running" id="all_errors_err_socket_dgram_not_running">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_socket_dgram_not_running"></a></h4>
<p>A call was made and the UDP subsystem was not running.</p>
<p><a id="ERR_SRI_PARSE"></a></p>
<h4><code>ERR_SRI_PARSE</code><span><a class="mark" href="#all_errors_err_sri_parse" id="all_errors_err_sri_parse">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_sri_parse"></a></h4>
<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_ALREADY_FINISHED"></a></p>
<h4><code>ERR_STREAM_ALREADY_FINISHED</code><span><a class="mark" href="#all_errors_err_stream_already_finished" id="all_errors_err_stream_already_finished">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_stream_already_finished"></a></h4>
<p>A stream method was called that cannot complete because the stream was
finished.</p>
<p><a id="ERR_STREAM_CANNOT_PIPE"></a></p>
<h4><code>ERR_STREAM_CANNOT_PIPE</code><span><a class="mark" href="#all_errors_err_stream_cannot_pipe" id="all_errors_err_stream_cannot_pipe">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_stream_cannot_pipe"></a></h4>
<p>An attempt was made to call <a href="#all_stream_readablepipedestination-options"><code>stream.pipe()</code></a> on a <a href="#all_stream_class-streamwritable"><code>Writable</code></a> stream.</p>
<p><a id="ERR_STREAM_DESTROYED"></a></p>
<h4><code>ERR_STREAM_DESTROYED</code><span><a class="mark" href="#all_errors_err_stream_destroyed" id="all_errors_err_stream_destroyed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_stream_destroyed"></a></h4>
<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>
<h4><code>ERR_STREAM_NULL_VALUES</code><span><a class="mark" href="#all_errors_err_stream_null_values" id="all_errors_err_stream_null_values">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_stream_null_values"></a></h4>
<p>An attempt was made to call <a href="#all_stream_writablewritechunk-encoding-callback"><code>stream.write()</code></a> with a <code>null</code> chunk.</p>
<p><a id="ERR_STREAM_PREMATURE_CLOSE"></a></p>
<h4><code>ERR_STREAM_PREMATURE_CLOSE</code><span><a class="mark" href="#all_errors_err_stream_premature_close" id="all_errors_err_stream_premature_close">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_stream_premature_close"></a></h4>
<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>
<h4><code>ERR_STREAM_PUSH_AFTER_EOF</code><span><a class="mark" href="#all_errors_err_stream_push_after_eof" id="all_errors_err_stream_push_after_eof">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_stream_push_after_eof"></a></h4>
<p>An attempt was made to call <a href="#all_stream_readablepushchunk-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>
<h4><code>ERR_STREAM_UNSHIFT_AFTER_END_EVENT</code><span><a class="mark" href="#all_errors_err_stream_unshift_after_end_event" id="all_errors_err_stream_unshift_after_end_event">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_stream_unshift_after_end_event"></a></h4>
<p>An attempt was made to call <a href="#all_stream_readableunshiftchunk-encoding"><code>stream.unshift()</code></a> after the <code>'end'</code> event was
emitted.</p>
<p><a id="ERR_STREAM_WRAP"></a></p>
<h4><code>ERR_STREAM_WRAP</code><span><a class="mark" href="#all_errors_err_stream_wrap" id="all_errors_err_stream_wrap">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_stream_wrap"></a></h4>
<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"><span class="hljs-keyword">const</span> <span class="hljs-title class_">Socket</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:net'</span>).<span class="hljs-property">Socket</span>;
<span class="hljs-keyword">const</span> instance = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Socket</span>();

instance.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>);</code> <button class="copy-button">copy</button></pre>
<p><a id="ERR_STREAM_WRITE_AFTER_END"></a></p>
<h4><code>ERR_STREAM_WRITE_AFTER_END</code><span><a class="mark" href="#all_errors_err_stream_write_after_end" id="all_errors_err_stream_write_after_end">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_stream_write_after_end"></a></h4>
<p>An attempt was made to call <a href="#all_stream_writablewritechunk-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>
<h4><code>ERR_STRING_TOO_LONG</code><span><a class="mark" href="#all_errors_err_string_too_long" id="all_errors_err_string_too_long">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_string_too_long"></a></h4>
<p>An attempt has been made to create a string longer than the maximum allowed
length.</p>
<p><a id="ERR_SYNTHETIC"></a></p>
<h4><code>ERR_SYNTHETIC</code><span><a class="mark" href="#all_errors_err_synthetic" id="all_errors_err_synthetic">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_synthetic"></a></h4>
<p>An artificial error object used to capture the call stack for diagnostic
reports.</p>
<p><a id="ERR_SYSTEM_ERROR"></a></p>
<h4><code>ERR_SYSTEM_ERROR</code><span><a class="mark" href="#all_errors_err_system_error" id="all_errors_err_system_error">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_system_error"></a></h4>
<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_TAP_LEXER_ERROR"></a></p>
<h4><code>ERR_TAP_LEXER_ERROR</code><span><a class="mark" href="#all_errors_err_tap_lexer_error" id="all_errors_err_tap_lexer_error">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tap_lexer_error"></a></h4>
<p>An error representing a failing lexer state.</p>
<p><a id="ERR_TAP_PARSER_ERROR"></a></p>
<h4><code>ERR_TAP_PARSER_ERROR</code><span><a class="mark" href="#all_errors_err_tap_parser_error" id="all_errors_err_tap_parser_error">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tap_parser_error"></a></h4>
<p>An error representing a failing parser state. Additional information about
the token causing the error is available via the <code>cause</code> property.</p>
<p><a id="ERR_TAP_VALIDATION_ERROR"></a></p>
<h4><code>ERR_TAP_VALIDATION_ERROR</code><span><a class="mark" href="#all_errors_err_tap_validation_error" id="all_errors_err_tap_validation_error">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tap_validation_error"></a></h4>
<p>This error represents a failed TAP validation.</p>
<p><a id="ERR_TEST_FAILURE"></a></p>
<h4><code>ERR_TEST_FAILURE</code><span><a class="mark" href="#all_errors_err_test_failure" id="all_errors_err_test_failure">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_test_failure"></a></h4>
<p>This error represents a failed test. Additional information about the failure
is available via the <code>cause</code> property. The <code>failureType</code> property specifies
what the test was doing when the failure occurred.</p>
<p><a id="ERR_TLS_ALPN_CALLBACK_INVALID_RESULT"></a></p>
<h4><code>ERR_TLS_ALPN_CALLBACK_INVALID_RESULT</code><span><a class="mark" href="#all_errors_err_tls_alpn_callback_invalid_result" id="all_errors_err_tls_alpn_callback_invalid_result">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tls_alpn_callback_invalid_result"></a></h4>
<p>This error is thrown when an <code>ALPNCallback</code> returns a value that is not in the
list of ALPN protocols offered by the client.</p>
<p><a id="ERR_TLS_ALPN_CALLBACK_WITH_PROTOCOLS"></a></p>
<h4><code>ERR_TLS_ALPN_CALLBACK_WITH_PROTOCOLS</code><span><a class="mark" href="#all_errors_err_tls_alpn_callback_with_protocols" id="all_errors_err_tls_alpn_callback_with_protocols">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tls_alpn_callback_with_protocols"></a></h4>
<p>This error is thrown when creating a <code>TLSServer</code> if the TLS options include
both <code>ALPNProtocols</code> and <code>ALPNCallback</code>. These options are mutually exclusive.</p>
<p><a id="ERR_TLS_CERT_ALTNAME_FORMAT"></a></p>
<h4><code>ERR_TLS_CERT_ALTNAME_FORMAT</code><span><a class="mark" href="#all_errors_err_tls_cert_altname_format" id="all_errors_err_tls_cert_altname_format">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tls_cert_altname_format"></a></h4>
<p>This error is thrown by <code>checkServerIdentity</code> if a user-supplied
<code>subjectaltname</code> property violates encoding rules. Certificate objects produced
by Node.js itself always comply with encoding rules and will never cause
this error.</p>
<p><a id="ERR_TLS_CERT_ALTNAME_INVALID"></a></p>
<h4><code>ERR_TLS_CERT_ALTNAME_INVALID</code><span><a class="mark" href="#all_errors_err_tls_cert_altname_invalid" id="all_errors_err_tls_cert_altname_invalid">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tls_cert_altname_invalid"></a></h4>
<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>
<h4><code>ERR_TLS_DH_PARAM_SIZE</code><span><a class="mark" href="#all_errors_err_tls_dh_param_size" id="all_errors_err_tls_dh_param_size">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tls_dh_param_size"></a></h4>
<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>
<h4><code>ERR_TLS_HANDSHAKE_TIMEOUT</code><span><a class="mark" href="#all_errors_err_tls_handshake_timeout" id="all_errors_err_tls_handshake_timeout">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tls_handshake_timeout"></a></h4>
<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>
<h4><code>ERR_TLS_INVALID_CONTEXT</code><span><a class="mark" href="#all_errors_err_tls_invalid_context" id="all_errors_err_tls_invalid_context">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tls_invalid_context"></a></h4>
<div class="api_metadata">
<span>Added in: v13.3.0</span>
</div>
<p>The context must be a <code>SecureContext</code>.</p>
<p><a id="ERR_TLS_INVALID_PROTOCOL_METHOD"></a></p>
<h4><code>ERR_TLS_INVALID_PROTOCOL_METHOD</code><span><a class="mark" href="#all_errors_err_tls_invalid_protocol_method" id="all_errors_err_tls_invalid_protocol_method">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tls_invalid_protocol_method"></a></h4>
<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>
<h4><code>ERR_TLS_INVALID_PROTOCOL_VERSION</code><span><a class="mark" href="#all_errors_err_tls_invalid_protocol_version" id="all_errors_err_tls_invalid_protocol_version">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tls_invalid_protocol_version"></a></h4>
<p>Valid TLS protocol versions are <code>'TLSv1'</code>, <code>'TLSv1.1'</code>, or <code>'TLSv1.2'</code>.</p>
<p><a id="ERR_TLS_INVALID_STATE"></a></p>
<h4><code>ERR_TLS_INVALID_STATE</code><span><a class="mark" href="#all_errors_err_tls_invalid_state" id="all_errors_err_tls_invalid_state">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tls_invalid_state"></a></h4>
<div class="api_metadata">
<span>Added in: v13.10.0, v12.17.0</span>
</div>
<p>The TLS socket must be connected and securely established. Ensure the 'secure'
event is emitted before continuing.</p>
<p><a id="ERR_TLS_PROTOCOL_VERSION_CONFLICT"></a></p>
<h4><code>ERR_TLS_PROTOCOL_VERSION_CONFLICT</code><span><a class="mark" href="#all_errors_err_tls_protocol_version_conflict" id="all_errors_err_tls_protocol_version_conflict">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tls_protocol_version_conflict"></a></h4>
<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_PSK_SET_IDENTIY_HINT_FAILED"></a></p>
<h4><code>ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED</code><span><a class="mark" href="#all_errors_err_tls_psk_set_identiy_hint_failed" id="all_errors_err_tls_psk_set_identiy_hint_failed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tls_psk_set_identiy_hint_failed"></a></h4>
<p>Failed to set PSK identity hint. Hint may be too long.</p>
<p><a id="ERR_TLS_RENEGOTIATION_DISABLED"></a></p>
<h4><code>ERR_TLS_RENEGOTIATION_DISABLED</code><span><a class="mark" href="#all_errors_err_tls_renegotiation_disabled" id="all_errors_err_tls_renegotiation_disabled">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tls_renegotiation_disabled"></a></h4>
<p>An attempt was made to renegotiate TLS on a socket instance with renegotiation
disabled.</p>
<p><a id="ERR_TLS_REQUIRED_SERVER_NAME"></a></p>
<h4><code>ERR_TLS_REQUIRED_SERVER_NAME</code><span><a class="mark" href="#all_errors_err_tls_required_server_name" id="all_errors_err_tls_required_server_name">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tls_required_server_name"></a></h4>
<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>
<h4><code>ERR_TLS_SESSION_ATTACK</code><span><a class="mark" href="#all_errors_err_tls_session_attack" id="all_errors_err_tls_session_attack">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tls_session_attack"></a></h4>
<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>
<h4><code>ERR_TLS_SNI_FROM_SERVER</code><span><a class="mark" href="#all_errors_err_tls_sni_from_server" id="all_errors_err_tls_sni_from_server">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tls_sni_from_server"></a></h4>
<p>An attempt was made to issue Server Name Indication from a TLS server-side
socket, which is only valid from a client.</p>
<p><a id="ERR_TRACE_EVENTS_CATEGORY_REQUIRED"></a></p>
<h4><code>ERR_TRACE_EVENTS_CATEGORY_REQUIRED</code><span><a class="mark" href="#all_errors_err_trace_events_category_required" id="all_errors_err_trace_events_category_required">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_trace_events_category_required"></a></h4>
<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>
<h4><code>ERR_TRACE_EVENTS_UNAVAILABLE</code><span><a class="mark" href="#all_errors_err_trace_events_unavailable" id="all_errors_err_trace_events_unavailable">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_trace_events_unavailable"></a></h4>
<p>The <code>node: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_TRANSFORM_ALREADY_TRANSFORMING"></a></p>
<h4><code>ERR_TRANSFORM_ALREADY_TRANSFORMING</code><span><a class="mark" href="#all_errors_err_transform_already_transforming" id="all_errors_err_transform_already_transforming">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_transform_already_transforming"></a></h4>
<p>A <code>Transform</code> stream finished while it was still transforming.</p>
<p><a id="ERR_TRANSFORM_WITH_LENGTH_0"></a></p>
<h4><code>ERR_TRANSFORM_WITH_LENGTH_0</code><span><a class="mark" href="#all_errors_err_transform_with_length_0" id="all_errors_err_transform_with_length_0">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_transform_with_length_0"></a></h4>
<p>A <code>Transform</code> stream finished with data still in the write buffer.</p>
<p><a id="ERR_TTY_INIT_FAILED"></a></p>
<h4><code>ERR_TTY_INIT_FAILED</code><span><a class="mark" href="#all_errors_err_tty_init_failed" id="all_errors_err_tty_init_failed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tty_init_failed"></a></h4>
<p>The initialization of a TTY failed due to a system error.</p>
<p><a id="ERR_UNAVAILABLE_DURING_EXIT"></a></p>
<h4><code>ERR_UNAVAILABLE_DURING_EXIT</code><span><a class="mark" href="#all_errors_err_unavailable_during_exit" id="all_errors_err_unavailable_during_exit">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_unavailable_during_exit"></a></h4>
<p>Function was called within a <a href="#all_process_event-exit"><code>process.on('exit')</code></a> handler that shouldn't be
called within <a href="#all_process_event-exit"><code>process.on('exit')</code></a> handler.</p>
<p><a id="ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET"></a></p>
<h4><code>ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET</code><span><a class="mark" href="#all_errors_err_uncaught_exception_capture_already_set" id="all_errors_err_uncaught_exception_capture_already_set">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_uncaught_exception_capture_already_set"></a></h4>
<p><a href="#all_process_processsetuncaughtexceptioncapturecallbackfn"><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>
<h4><code>ERR_UNESCAPED_CHARACTERS</code><span><a class="mark" href="#all_errors_err_unescaped_characters" id="all_errors_err_unescaped_characters">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_unescaped_characters"></a></h4>
<p>A string that contained unescaped characters was received.</p>
<p><a id="ERR_UNHANDLED_ERROR"></a></p>
<h4><code>ERR_UNHANDLED_ERROR</code><span><a class="mark" href="#all_errors_err_unhandled_error" id="all_errors_err_unhandled_error">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_unhandled_error"></a></h4>
<p>An unhandled error occurred (for instance, when an <code>'error'</code> event is emitted
by an <a href="#all_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>
<h4><code>ERR_UNKNOWN_BUILTIN_MODULE</code><span><a class="mark" href="#all_errors_err_unknown_builtin_module" id="all_errors_err_unknown_builtin_module">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_unknown_builtin_module"></a></h4>
<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>
<h4><code>ERR_UNKNOWN_CREDENTIAL</code><span><a class="mark" href="#all_errors_err_unknown_credential" id="all_errors_err_unknown_credential">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_unknown_credential"></a></h4>
<p>A Unix group or user identifier that does not exist was passed.</p>
<p><a id="ERR_UNKNOWN_ENCODING"></a></p>
<h4><code>ERR_UNKNOWN_ENCODING</code><span><a class="mark" href="#all_errors_err_unknown_encoding" id="all_errors_err_unknown_encoding">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_unknown_encoding"></a></h4>
<p>An invalid or unknown encoding option was passed to an API.</p>
<p><a id="ERR_UNKNOWN_FILE_EXTENSION"></a></p>
<h4><code>ERR_UNKNOWN_FILE_EXTENSION</code><span><a class="mark" href="#all_errors_err_unknown_file_extension" id="all_errors_err_unknown_file_extension">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_unknown_file_extension"></a></h4>
<p></p><div class="api_stability api_stability_1"><a href="#all_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>
<h4><code>ERR_UNKNOWN_MODULE_FORMAT</code><span><a class="mark" href="#all_errors_err_unknown_module_format" id="all_errors_err_unknown_module_format">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_unknown_module_format"></a></h4>
<p></p><div class="api_stability api_stability_1"><a href="#all_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>
<h4><code>ERR_UNKNOWN_SIGNAL</code><span><a class="mark" href="#all_errors_err_unknown_signal" id="all_errors_err_unknown_signal">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_unknown_signal"></a></h4>
<p>An invalid or unknown process signal was passed to an API expecting a valid
signal (such as <a href="#all_child_process_subprocesskillsignal"><code>subprocess.kill()</code></a>).</p>
<p><a id="ERR_UNSUPPORTED_DIR_IMPORT"></a></p>
<h4><code>ERR_UNSUPPORTED_DIR_IMPORT</code><span><a class="mark" href="#all_errors_err_unsupported_dir_import" id="all_errors_err_unsupported_dir_import">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_unsupported_dir_import"></a></h4>
<p><code>import</code> a directory URL is unsupported. Instead,
<a href="#all_packages_self-referencing-a-package-using-its-name">self-reference a package using its name</a> and <a href="#all_packages_subpath-exports">define a custom subpath</a> in
the <a href="#all_packages_exports"><code>"exports"</code></a> field of the <a href="#all_packages_nodejs-packagejson-field-definitions"><code>package.json</code></a> file.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> <span class="hljs-string">'./'</span>; <span class="hljs-comment">// unsupported</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'./index.js'</span>; <span class="hljs-comment">// supported</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'package-name'</span>; <span class="hljs-comment">// supported</span></code> <button class="copy-button">copy</button></pre>
<p><a id="ERR_UNSUPPORTED_ESM_URL_SCHEME"></a></p>
<h4><code>ERR_UNSUPPORTED_ESM_URL_SCHEME</code><span><a class="mark" href="#all_errors_err_unsupported_esm_url_scheme" id="all_errors_err_unsupported_esm_url_scheme">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_unsupported_esm_url_scheme"></a></h4>
<p><code>import</code> with URL schemes other than <code>file</code> and <code>data</code> is unsupported.</p>
<p><a id="ERR_UNSUPPORTED_RESOLVE_REQUEST"></a></p>
<h4><code>ERR_UNSUPPORTED_RESOLVE_REQUEST</code><span><a class="mark" href="#all_errors_err_unsupported_resolve_request" id="all_errors_err_unsupported_resolve_request">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_unsupported_resolve_request"></a></h4>
<p>An attempt was made to resolve an invalid module referrer. This can happen when
importing or calling <code>import.meta.resolve()</code> with either:</p>
<ul>
<li>a bare specifier that is not a builtin module from a module whose URL scheme
is not <code>file</code>.</li>
<li>a <a href="https://url.spec.whatwg.org/#relative-url-string">relative URL</a> from a module whose URL scheme is not a <a href="https://url.spec.whatwg.org/#special-scheme">special scheme</a>.</li>
</ul>
<pre><code class="language-js mjs"><span class="hljs-keyword">try</span> {
  <span class="hljs-comment">// Trying to import the package 'bare-specifier' from a `data:` URL module:</span>
  <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'data:text/javascript,import "bare-specifier"'</span>);
} <span class="hljs-keyword">catch</span> (e) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(e.<span class="hljs-property">code</span>); <span class="hljs-comment">// ERR_UNSUPPORTED_RESOLVE_REQUEST</span>
}</code> <button class="copy-button">copy</button></pre>
<p><a id="ERR_USE_AFTER_CLOSE"></a></p>
<h4><code>ERR_USE_AFTER_CLOSE</code><span><a class="mark" href="#all_errors_err_use_after_close" id="all_errors_err_use_after_close">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_use_after_close"></a></h4>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>An attempt was made to use something that was already closed.</p>
<p><a id="ERR_VALID_PERFORMANCE_ENTRY_TYPE"></a></p>
<h4><code>ERR_VALID_PERFORMANCE_ENTRY_TYPE</code><span><a class="mark" href="#all_errors_err_valid_performance_entry_type" id="all_errors_err_valid_performance_entry_type">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_valid_performance_entry_type"></a></h4>
<p>While using the Performance Timing API (<code>perf_hooks</code>), no valid performance
entry types are found.</p>
<p><a id="ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG"></a></p>
<h4><code>ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG</code><span><a class="mark" href="#all_errors_err_vm_dynamic_import_callback_missing_flag" id="all_errors_err_vm_dynamic_import_callback_missing_flag">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_vm_dynamic_import_callback_missing_flag"></a></h4>
<p>A dynamic import callback was invoked without <code>--experimental-vm-modules</code>.</p>
<p><a id="ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING"></a></p>
<h4><code>ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING</code><span><a class="mark" href="#all_errors_err_vm_dynamic_import_callback_missing" id="all_errors_err_vm_dynamic_import_callback_missing">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_vm_dynamic_import_callback_missing"></a></h4>
<p>A dynamic import callback was not specified.</p>
<p><a id="ERR_VM_MODULE_ALREADY_LINKED"></a></p>
<h4><code>ERR_VM_MODULE_ALREADY_LINKED</code><span><a class="mark" href="#all_errors_err_vm_module_already_linked" id="all_errors_err_vm_module_already_linked">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_vm_module_already_linked"></a></h4>
<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>
<h4><code>ERR_VM_MODULE_CACHED_DATA_REJECTED</code><span><a class="mark" href="#all_errors_err_vm_module_cached_data_rejected" id="all_errors_err_vm_module_cached_data_rejected">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_vm_module_cached_data_rejected"></a></h4>
<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>
<h4><code>ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA</code><span><a class="mark" href="#all_errors_err_vm_module_cannot_create_cached_data" id="all_errors_err_vm_module_cannot_create_cached_data">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_vm_module_cannot_create_cached_data"></a></h4>
<p>Cached data cannot be created for modules which have already been evaluated.</p>
<p><a id="ERR_VM_MODULE_DIFFERENT_CONTEXT"></a></p>
<h4><code>ERR_VM_MODULE_DIFFERENT_CONTEXT</code><span><a class="mark" href="#all_errors_err_vm_module_different_context" id="all_errors_err_vm_module_different_context">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_vm_module_different_context"></a></h4>
<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_LINK_FAILURE"></a></p>
<h4><code>ERR_VM_MODULE_LINK_FAILURE</code><span><a class="mark" href="#all_errors_err_vm_module_link_failure" id="all_errors_err_vm_module_link_failure">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_vm_module_link_failure"></a></h4>
<p>The module was unable to be linked due to a failure.</p>
<p><a id="ERR_VM_MODULE_NOT_MODULE"></a></p>
<h4><code>ERR_VM_MODULE_NOT_MODULE</code><span><a class="mark" href="#all_errors_err_vm_module_not_module" id="all_errors_err_vm_module_not_module">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_vm_module_not_module"></a></h4>
<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>
<h4><code>ERR_VM_MODULE_STATUS</code><span><a class="mark" href="#all_errors_err_vm_module_status" id="all_errors_err_vm_module_status">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_vm_module_status"></a></h4>
<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>
<h4><code>ERR_WASI_ALREADY_STARTED</code><span><a class="mark" href="#all_errors_err_wasi_already_started" id="all_errors_err_wasi_already_started">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_wasi_already_started"></a></h4>
<p>The WASI instance has already started.</p>
<p><a id="ERR_WASI_NOT_STARTED"></a></p>
<h4><code>ERR_WASI_NOT_STARTED</code><span><a class="mark" href="#all_errors_err_wasi_not_started" id="all_errors_err_wasi_not_started">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_wasi_not_started"></a></h4>
<p>The WASI instance has not been started.</p>
<p><a id="ERR_WEBASSEMBLY_RESPONSE"></a></p>
<h4><code>ERR_WEBASSEMBLY_RESPONSE</code><span><a class="mark" href="#all_errors_err_webassembly_response" id="all_errors_err_webassembly_response">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_webassembly_response"></a></h4>
<div class="api_metadata">
<span>Added in: v18.1.0</span>
</div>
<p>The <code>Response</code> that has been passed to <code>WebAssembly.compileStreaming</code> or to
<code>WebAssembly.instantiateStreaming</code> is not a valid WebAssembly response.</p>
<p><a id="ERR_WORKER_INIT_FAILED"></a></p>
<h4><code>ERR_WORKER_INIT_FAILED</code><span><a class="mark" href="#all_errors_err_worker_init_failed" id="all_errors_err_worker_init_failed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_worker_init_failed"></a></h4>
<p>The <code>Worker</code> initialization failed.</p>
<p><a id="ERR_WORKER_INVALID_EXEC_ARGV"></a></p>
<h4><code>ERR_WORKER_INVALID_EXEC_ARGV</code><span><a class="mark" href="#all_errors_err_worker_invalid_exec_argv" id="all_errors_err_worker_invalid_exec_argv">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_worker_invalid_exec_argv"></a></h4>
<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>
<h4><code>ERR_WORKER_NOT_RUNNING</code><span><a class="mark" href="#all_errors_err_worker_not_running" id="all_errors_err_worker_not_running">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_worker_not_running"></a></h4>
<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>
<h4><code>ERR_WORKER_OUT_OF_MEMORY</code><span><a class="mark" href="#all_errors_err_worker_out_of_memory" id="all_errors_err_worker_out_of_memory">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_worker_out_of_memory"></a></h4>
<p>The <code>Worker</code> instance terminated because it reached its memory limit.</p>
<p><a id="ERR_WORKER_PATH"></a></p>
<h4><code>ERR_WORKER_PATH</code><span><a class="mark" href="#all_errors_err_worker_path" id="all_errors_err_worker_path">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_worker_path"></a></h4>
<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>
<h4><code>ERR_WORKER_UNSERIALIZABLE_ERROR</code><span><a class="mark" href="#all_errors_err_worker_unserializable_error" id="all_errors_err_worker_unserializable_error">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_worker_unserializable_error"></a></h4>
<p>All attempts at serializing an uncaught exception from a worker thread failed.</p>
<p><a id="ERR_WORKER_UNSUPPORTED_OPERATION"></a></p>
<h4><code>ERR_WORKER_UNSUPPORTED_OPERATION</code><span><a class="mark" href="#all_errors_err_worker_unsupported_operation" id="all_errors_err_worker_unsupported_operation">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_worker_unsupported_operation"></a></h4>
<p>The requested functionality is not supported in worker threads.</p>
<p><a id="ERR_ZLIB_INITIALIZATION_FAILED"></a></p>
<h4><code>ERR_ZLIB_INITIALIZATION_FAILED</code><span><a class="mark" href="#all_errors_err_zlib_initialization_failed" id="all_errors_err_zlib_initialization_failed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_zlib_initialization_failed"></a></h4>
<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>
<h4><code>HPE_HEADER_OVERFLOW</code><span><a class="mark" href="#all_errors_hpe_header_overflow" id="all_errors_hpe_header_overflow">#</a></span><a aria-hidden="true" class="legacy" id="errors_hpe_header_overflow"></a></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, v10.15.0</td>
<td><p>Max header size in <code>http_parser</code> was set to 8 KiB.</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 <code>maxHeaderSize</code> 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="HPE_CHUNK_EXTENSIONS_OVERFLOW"></a></p>
<h4><code>HPE_CHUNK_EXTENSIONS_OVERFLOW</code><span><a class="mark" href="#all_errors_hpe_chunk_extensions_overflow" id="all_errors_hpe_chunk_extensions_overflow">#</a></span><a aria-hidden="true" class="legacy" id="errors_hpe_chunk_extensions_overflow"></a></h4>
<div class="api_metadata">
<span>Added in: v20.11.1</span>
</div>
<p>Too much data was received for a chunk extensions. In order to protect against
malicious or malconfigured clients, if more than 16 KiB of data is received
then an <code>Error</code> with this code will be emitted.</p>
<p><a id="HPE_UNEXPECTED_CONTENT_LENGTH"></a></p>
<h4><code>HPE_UNEXPECTED_CONTENT_LENGTH</code><span><a class="mark" href="#all_errors_hpe_unexpected_content_length" id="all_errors_hpe_unexpected_content_length">#</a></span><a aria-hidden="true" class="legacy" id="errors_hpe_unexpected_content_length"></a></h4>
<p>Server is sending both a <code>Content-Length</code> header and <code>Transfer-Encoding: chunked</code>.</p>
<p><code>Transfer-Encoding: chunked</code> allows the server to maintain an HTTP persistent
connection for dynamically generated content.
In this case, the <code>Content-Length</code> HTTP header cannot be used.</p>
<p>Use <code>Content-Length</code> or <code>Transfer-Encoding: chunked</code>.</p>
<p><a id="MODULE_NOT_FOUND"></a></p>
<h4><code>MODULE_NOT_FOUND</code><span><a class="mark" href="#all_errors_module_not_found" id="all_errors_module_not_found">#</a></span><a aria-hidden="true" class="legacy" id="errors_module_not_found"></a></h4>
<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 by the CommonJS modules loader while
attempting a <a href="#all_modules_requireid"><code>require()</code></a> operation or when loading the program entry point.</p>
</section><section><h3>Legacy Node.js error codes<span><a class="mark" href="#all_errors_legacy-nodejs-error-codes" id="all_errors_legacy-nodejs-error-codes">#</a></span><a aria-hidden="true" class="legacy" id="errors_legacy_node_js_error_codes"></a></h3>
<p></p><div class="api_stability api_stability_0"><a href="#all_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>
<h4><code>ERR_CANNOT_TRANSFER_OBJECT</code><span><a class="mark" href="#all_errors_err_cannot_transfer_object" id="all_errors_err_cannot_transfer_object">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_cannot_transfer_object"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.0</span><span>Removed in: v12.5.0</span>
</div>
<p>The value passed to <code>postMessage()</code> contained an object that is not supported
for transferring.</p>
<p><a id="ERR_CRYPTO_HASH_DIGEST_NO_UTF16"></a></p>
<h4><code>ERR_CRYPTO_HASH_DIGEST_NO_UTF16</code><span><a class="mark" href="#all_errors_err_crypto_hash_digest_no_utf16" id="all_errors_err_crypto_hash_digest_no_utf16">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_crypto_hash_digest_no_utf16"></a></h4>
<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="#all_crypto_hashdigestencoding"><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>
<h4><code>ERR_HTTP2_FRAME_ERROR</code><span><a class="mark" href="#all_errors_err_http2_frame_error" id="all_errors_err_http2_frame_error">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_frame_error"></a></h4>
<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>
<h4><code>ERR_HTTP2_HEADERS_OBJECT</code><span><a class="mark" href="#all_errors_err_http2_headers_object" id="all_errors_err_http2_headers_object">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_headers_object"></a></h4>
<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>
<h4><code>ERR_HTTP2_HEADER_REQUIRED</code><span><a class="mark" href="#all_errors_err_http2_header_required" id="all_errors_err_http2_header_required">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_header_required"></a></h4>
<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>
<h4><code>ERR_HTTP2_INFO_HEADERS_AFTER_RESPOND</code><span><a class="mark" href="#all_errors_err_http2_info_headers_after_respond" id="all_errors_err_http2_info_headers_after_respond">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_info_headers_after_respond"></a></h4>
<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>
<h4><code>ERR_HTTP2_STREAM_CLOSED</code><span><a class="mark" href="#all_errors_err_http2_stream_closed" id="all_errors_err_http2_stream_closed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http2_stream_closed"></a></h4>
<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>
<h4><code>ERR_HTTP_INVALID_CHAR</code><span><a class="mark" href="#all_errors_err_http_invalid_char" id="all_errors_err_http_invalid_char">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_http_invalid_char"></a></h4>
<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>
<h4><code>ERR_INDEX_OUT_OF_RANGE</code><span><a class="mark" href="#all_errors_err_index_out_of_range" id="all_errors_err_index_out_of_range">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_index_out_of_range"></a></h4>
<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_INVALID_OPT_VALUE"></a></p>
<h4><code>ERR_INVALID_OPT_VALUE</code><span><a class="mark" href="#all_errors_err_invalid_opt_value" id="all_errors_err_invalid_opt_value">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_opt_value"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span><span>Removed in: v15.0.0</span>
</div>
<p>An invalid or unexpected value was passed in an options object.</p>
<p><a id="ERR_INVALID_OPT_VALUE_ENCODING"></a></p>
<h4><code>ERR_INVALID_OPT_VALUE_ENCODING</code><span><a class="mark" href="#all_errors_err_invalid_opt_value_encoding" id="all_errors_err_invalid_opt_value_encoding">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_invalid_opt_value_encoding"></a></h4>
<div class="api_metadata">
<span>Added in: v9.0.0</span><span>Removed in: v15.0.0</span>
</div>
<p>An invalid or unknown file encoding was passed.</p>
<p><a id="ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST"></a></p>
<h4><code>ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST</code><span><a class="mark" href="#all_errors_err_missing_message_port_in_transfer_list" id="all_errors_err_missing_message_port_in_transfer_list">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_missing_message_port_in_transfer_list"></a></h4>
<div class="api_metadata">
<span>Removed in: v15.0.0</span>
</div>
<p>This error code was replaced by <a href="#all_errors_err_missing_transferable_in_transfer_list"><code>ERR_MISSING_TRANSFERABLE_IN_TRANSFER_LIST</code></a>
in Node.js v15.0.0, because it is no longer accurate as other types of
transferable objects also exist now.</p>
<p><a id="ERR_NAPI_CONS_PROTOTYPE_OBJECT"></a></p>
<h4><code>ERR_NAPI_CONS_PROTOTYPE_OBJECT</code><span><a class="mark" href="#all_errors_err_napi_cons_prototype_object" id="all_errors_err_napi_cons_prototype_object">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_napi_cons_prototype_object"></a></h4>
<div class="api_metadata">
<span>Added in: v9.0.0</span><span>Removed in: v10.0.0</span>
</div>
<p>Used by the <code>Node-API</code> when <code>Constructor.prototype</code> is not an object.</p>
<p><a id="ERR_NETWORK_IMPORT_BAD_RESPONSE"></a></p>
<h4><code>ERR_NETWORK_IMPORT_BAD_RESPONSE</code><span><a class="mark" href="#all_errors_err_network_import_bad_response" id="all_errors_err_network_import_bad_response">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_network_import_bad_response"></a></h4>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Response was received but was invalid when importing a module over the network.</p>
<p><a id="ERR_NETWORK_IMPORT_DISALLOWED"></a></p>
<h4><code>ERR_NETWORK_IMPORT_DISALLOWED</code><span><a class="mark" href="#all_errors_err_network_import_disallowed" id="all_errors_err_network_import_disallowed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_network_import_disallowed"></a></h4>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>A network module attempted to load another module that it is not allowed to
load. Likely this restriction is for security reasons.</p>
<p><a id="ERR_NO_LONGER_SUPPORTED"></a></p>
<h4><code>ERR_NO_LONGER_SUPPORTED</code><span><a class="mark" href="#all_errors_err_no_longer_supported" id="all_errors_err_no_longer_supported">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_no_longer_supported"></a></h4>
<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_OPERATION_FAILED"></a></p>
<h4><code>ERR_OPERATION_FAILED</code><span><a class="mark" href="#all_errors_err_operation_failed" id="all_errors_err_operation_failed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_operation_failed"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>An operation failed. This is typically used to signal the general failure
of an asynchronous operation.</p>
<p><a id="ERR_OUTOFMEMORY"></a></p>
<h4><code>ERR_OUTOFMEMORY</code><span><a class="mark" href="#all_errors_err_outofmemory" id="all_errors_err_outofmemory">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_outofmemory"></a></h4>
<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>
<h4><code>ERR_PARSE_HISTORY_DATA</code><span><a class="mark" href="#all_errors_err_parse_history_data" id="all_errors_err_parse_history_data">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_parse_history_data"></a></h4>
<div class="api_metadata">
<span>Added in: v9.0.0</span><span>Removed in: v10.0.0</span>
</div>
<p>The <code>node:repl</code> module was unable to parse data from the REPL history file.</p>
<p><a id="ERR_SOCKET_CANNOT_SEND"></a></p>
<h4><code>ERR_SOCKET_CANNOT_SEND</code><span><a class="mark" href="#all_errors_err_socket_cannot_send" id="all_errors_err_socket_cannot_send">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_socket_cannot_send"></a></h4>
<div class="api_metadata">
<span>Added in: v9.0.0</span><span>Removed in: v14.0.0</span>
</div>
<p>Data could not be sent on a socket.</p>
<p><a id="ERR_STDERR_CLOSE"></a></p>
<h4><code>ERR_STDERR_CLOSE</code><span><a class="mark" href="#all_errors_err_stderr_close" id="all_errors_err_stderr_close">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_stderr_close"></a></h4>
<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>
<h4><code>ERR_STDOUT_CLOSE</code><span><a class="mark" href="#all_errors_err_stdout_close" id="all_errors_err_stdout_close">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_stdout_close"></a></h4>
<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>
<h4><code>ERR_STREAM_READ_NOT_IMPLEMENTED</code><span><a class="mark" href="#all_errors_err_stream_read_not_implemented" id="all_errors_err_stream_read_not_implemented">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_stream_read_not_implemented"></a></h4>
<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="#all_stream_readable_readsize"><code>readable._read()</code></a>.</p>
<p><a id="ERR_TLS_RENEGOTIATION_FAILED"></a></p>
<h4><code>ERR_TLS_RENEGOTIATION_FAILED</code><span><a class="mark" href="#all_errors_err_tls_renegotiation_failed" id="all_errors_err_tls_renegotiation_failed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_tls_renegotiation_failed"></a></h4>
<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_TRANSFERRING_EXTERNALIZED_SHAREDARRAYBUFFER"></a></p>
<h4><code>ERR_TRANSFERRING_EXTERNALIZED_SHAREDARRAYBUFFER</code><span><a class="mark" href="#all_errors_err_transferring_externalized_sharedarraybuffer" id="all_errors_err_transferring_externalized_sharedarraybuffer">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_transferring_externalized_sharedarraybuffer"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.0</span><span>Removed in: v14.0.0</span>
</div>
<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_UNKNOWN_STDIN_TYPE"></a></p>
<h4><code>ERR_UNKNOWN_STDIN_TYPE</code><span><a class="mark" href="#all_errors_err_unknown_stdin_type" id="all_errors_err_unknown_stdin_type">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_unknown_stdin_type"></a></h4>
<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>
<h4><code>ERR_UNKNOWN_STREAM_TYPE</code><span><a class="mark" href="#all_errors_err_unknown_stream_type" id="all_errors_err_unknown_stream_type">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_unknown_stream_type"></a></h4>
<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_V8BREAKITERATOR"></a></p>
<h4><code>ERR_V8BREAKITERATOR</code><span><a class="mark" href="#all_errors_err_v8breakiterator" id="all_errors_err_v8breakiterator">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_v8breakiterator"></a></h4>
<p>The V8 <code>BreakIterator</code> API was used but the full ICU data set is not installed.</p>
<p><a id="ERR_VALUE_OUT_OF_RANGE"></a></p>
<h4><code>ERR_VALUE_OUT_OF_RANGE</code><span><a class="mark" href="#all_errors_err_value_out_of_range" id="all_errors_err_value_out_of_range">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_value_out_of_range"></a></h4>
<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>
<h4><code>ERR_VM_MODULE_NOT_LINKED</code><span><a class="mark" href="#all_errors_err_vm_module_not_linked" id="all_errors_err_vm_module_not_linked">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_vm_module_not_linked"></a></h4>
<p>The module must be successfully linked before instantiation.</p>
<p><a id="ERR_VM_MODULE_LINKING_ERRORED"></a></p>
<h4><code>ERR_VM_MODULE_LINKING_ERRORED</code><span><a class="mark" href="#all_errors_err_vm_module_linking_errored" id="all_errors_err_vm_module_linking_errored">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_vm_module_linking_errored"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span><span>Removed in: v18.1.0, v16.17.0</span>
</div>
<p>The linker function returned a module for which linking has failed.</p>
<p><a id="ERR_WORKER_UNSUPPORTED_EXTENSION"></a></p>
<h4><code>ERR_WORKER_UNSUPPORTED_EXTENSION</code><span><a class="mark" href="#all_errors_err_worker_unsupported_extension" id="all_errors_err_worker_unsupported_extension">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_worker_unsupported_extension"></a></h4>
<div class="api_metadata">
<span>Added in: v11.0.0</span><span>Removed in: v16.9.0</span>
</div>
<p>The pathname used for the main script of a worker has an
unknown file extension.</p>
<p><a id="ERR_ZLIB_BINDING_CLOSED"></a></p>
<h4><code>ERR_ZLIB_BINDING_CLOSED</code><span><a class="mark" href="#all_errors_err_zlib_binding_closed" id="all_errors_err_zlib_binding_closed">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_zlib_binding_closed"></a></h4>
<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>
<p><a id="ERR_CPU_USAGE"></a></p>
<h4><code>ERR_CPU_USAGE</code><span><a class="mark" href="#all_errors_err_cpu_usage" id="all_errors_err_cpu_usage">#</a></span><a aria-hidden="true" class="legacy" id="errors_err_cpu_usage"></a></h4>
<div class="api_metadata">
<span>Removed in: v15.0.0</span>
</div>
<p>The native call from <code>process.cpuUsage</code> could not be processed.</p>
<p><a id="openssl-error-codes"></a></p>
</section><section><h3>OpenSSL Error Codes<span><a class="mark" href="#all_errors_openssl-error-codes" id="all_errors_openssl-error-codes">#</a></span><a aria-hidden="true" class="legacy" id="errors_openssl_error_codes"></a></h3>
<p><a id="Time Validity Errors"></a></p>
<h4>Time Validity Errors<span><a class="mark" href="#all_errors_time-validity-errors" id="all_errors_time-validity-errors">#</a></span><a aria-hidden="true" class="legacy" id="errors_time_validity_errors"></a></h4>
<p><a id="CERT_NOT_YET_VALID"></a></p>
<h5><code>CERT_NOT_YET_VALID</code><span><a class="mark" href="#all_errors_cert_not_yet_valid" id="all_errors_cert_not_yet_valid">#</a></span><a aria-hidden="true" class="legacy" id="errors_cert_not_yet_valid"></a></h5>
<p>The certificate is not yet valid: the notBefore date is after the current time.</p>
<p><a id="CERT_HAS_EXPIRED"></a></p>
<h5><code>CERT_HAS_EXPIRED</code><span><a class="mark" href="#all_errors_cert_has_expired" id="all_errors_cert_has_expired">#</a></span><a aria-hidden="true" class="legacy" id="errors_cert_has_expired"></a></h5>
<p>The certificate has expired: the notAfter date is before the current time.</p>
<p><a id="CRL_NOT_YET_VALID"></a></p>
<h5><code>CRL_NOT_YET_VALID</code><span><a class="mark" href="#all_errors_crl_not_yet_valid" id="all_errors_crl_not_yet_valid">#</a></span><a aria-hidden="true" class="legacy" id="errors_crl_not_yet_valid"></a></h5>
<p>The certificate revocation list (CRL) has a future issue date.</p>
<p><a id="CRL_HAS_EXPIRED"></a></p>
<h5><code>CRL_HAS_EXPIRED</code><span><a class="mark" href="#all_errors_crl_has_expired" id="all_errors_crl_has_expired">#</a></span><a aria-hidden="true" class="legacy" id="errors_crl_has_expired"></a></h5>
<p>The certificate revocation list (CRL) has expired.</p>
<p><a id="CERT_REVOKED"></a></p>
<h5><code>CERT_REVOKED</code><span><a class="mark" href="#all_errors_cert_revoked" id="all_errors_cert_revoked">#</a></span><a aria-hidden="true" class="legacy" id="errors_cert_revoked"></a></h5>
<p>The certificate has been revoked; it is on a certificate revocation list (CRL).</p>
<p><a id="Trust or Chain Related Errors"></a></p>
<h4>Trust or Chain Related Errors<span><a class="mark" href="#all_errors_trust-or-chain-related-errors" id="all_errors_trust-or-chain-related-errors">#</a></span><a aria-hidden="true" class="legacy" id="errors_trust_or_chain_related_errors"></a></h4>
<p><a id="UNABLE_TO_GET_ISSUER_CERT"></a></p>
<h5><code>UNABLE_TO_GET_ISSUER_CERT</code><span><a class="mark" href="#all_errors_unable_to_get_issuer_cert" id="all_errors_unable_to_get_issuer_cert">#</a></span><a aria-hidden="true" class="legacy" id="errors_unable_to_get_issuer_cert"></a></h5>
<p>The issuer certificate of a looked up certificate could not be found. This
normally means the list of trusted certificates is not complete.</p>
<p><a id="UNABLE_TO_GET_ISSUER_CERT_LOCALLY"></a></p>
<h5><code>UNABLE_TO_GET_ISSUER_CERT_LOCALLY</code><span><a class="mark" href="#all_errors_unable_to_get_issuer_cert_locally" id="all_errors_unable_to_get_issuer_cert_locally">#</a></span><a aria-hidden="true" class="legacy" id="errors_unable_to_get_issuer_cert_locally"></a></h5>
<p>The certificate’s issuer is not known. This is the case if the issuer is not
included in the trusted certificate list.</p>
<p><a id="DEPTH_ZERO_SELF_SIGNED_CERT"></a></p>
<h5><code>DEPTH_ZERO_SELF_SIGNED_CERT</code><span><a class="mark" href="#all_errors_depth_zero_self_signed_cert" id="all_errors_depth_zero_self_signed_cert">#</a></span><a aria-hidden="true" class="legacy" id="errors_depth_zero_self_signed_cert"></a></h5>
<p>The passed certificate is self-signed and the same certificate cannot be found
in the list of trusted certificates.</p>
<p><a id="SELF_SIGNED_CERT_IN_CHAIN"></a></p>
<h5><code>SELF_SIGNED_CERT_IN_CHAIN</code><span><a class="mark" href="#all_errors_self_signed_cert_in_chain" id="all_errors_self_signed_cert_in_chain">#</a></span><a aria-hidden="true" class="legacy" id="errors_self_signed_cert_in_chain"></a></h5>
<p>The certificate’s issuer is not known. This is the case if the issuer is not
included in the trusted certificate list.</p>
<p><a id="CERT_CHAIN_TOO_LONG"></a></p>
<h5><code>CERT_CHAIN_TOO_LONG</code><span><a class="mark" href="#all_errors_cert_chain_too_long" id="all_errors_cert_chain_too_long">#</a></span><a aria-hidden="true" class="legacy" id="errors_cert_chain_too_long"></a></h5>
<p>The certificate chain length is greater than the maximum depth.</p>
<p><a id="UNABLE_TO_GET_CRL"></a></p>
<h5><code>UNABLE_TO_GET_CRL</code><span><a class="mark" href="#all_errors_unable_to_get_crl" id="all_errors_unable_to_get_crl">#</a></span><a aria-hidden="true" class="legacy" id="errors_unable_to_get_crl"></a></h5>
<p>The CRL reference by the certificate could not be found.</p>
<p><a id="UNABLE_TO_VERIFY_LEAF_SIGNATURE"></a></p>
<h5><code>UNABLE_TO_VERIFY_LEAF_SIGNATURE</code><span><a class="mark" href="#all_errors_unable_to_verify_leaf_signature" id="all_errors_unable_to_verify_leaf_signature">#</a></span><a aria-hidden="true" class="legacy" id="errors_unable_to_verify_leaf_signature"></a></h5>
<p>No signatures could be verified because the chain contains only one certificate
and it is not self signed.</p>
<p><a id="CERT_UNTRUSTED"></a></p>
<h5><code>CERT_UNTRUSTED</code><span><a class="mark" href="#all_errors_cert_untrusted" id="all_errors_cert_untrusted">#</a></span><a aria-hidden="true" class="legacy" id="errors_cert_untrusted"></a></h5>
<p>The root certificate authority (CA) is not marked as trusted for the specified
purpose.</p>
<p><a id="Basic Extension Errors"></a></p>
<h4>Basic Extension Errors<span><a class="mark" href="#all_errors_basic-extension-errors" id="all_errors_basic-extension-errors">#</a></span><a aria-hidden="true" class="legacy" id="errors_basic_extension_errors"></a></h4>
<p><a id="INVALID_CA"></a></p>
<h5><code>INVALID_CA</code><span><a class="mark" href="#all_errors_invalid_ca" id="all_errors_invalid_ca">#</a></span><a aria-hidden="true" class="legacy" id="errors_invalid_ca"></a></h5>
<p>A CA certificate is invalid. Either it is not a CA or its extensions are not
consistent with the supplied purpose.</p>
<p><a id="PATH_LENGTH_EXCEEDED"></a></p>
<h5><code>PATH_LENGTH_EXCEEDED</code><span><a class="mark" href="#all_errors_path_length_exceeded" id="all_errors_path_length_exceeded">#</a></span><a aria-hidden="true" class="legacy" id="errors_path_length_exceeded"></a></h5>
<p>The basicConstraints pathlength parameter has been exceeded.</p>
<p><a id="Name Related Errors"></a></p>
<h4>Name Related Errors<span><a class="mark" href="#all_errors_name-related-errors" id="all_errors_name-related-errors">#</a></span><a aria-hidden="true" class="legacy" id="errors_name_related_errors"></a></h4>
<p><a id="HOSTNAME_MISMATCH"></a></p>
<h5><code>HOSTNAME_MISMATCH</code><span><a class="mark" href="#all_errors_hostname_mismatch" id="all_errors_hostname_mismatch">#</a></span><a aria-hidden="true" class="legacy" id="errors_hostname_mismatch"></a></h5>
<p>Certificate does not match provided name.</p>
<p><a id="Usage and Policy Errors"></a></p>
<h4>Usage and Policy Errors<span><a class="mark" href="#all_errors_usage-and-policy-errors" id="all_errors_usage-and-policy-errors">#</a></span><a aria-hidden="true" class="legacy" id="errors_usage_and_policy_errors"></a></h4>
<p><a id="INVALID_PURPOSE"></a></p>
<h5><code>INVALID_PURPOSE</code><span><a class="mark" href="#all_errors_invalid_purpose" id="all_errors_invalid_purpose">#</a></span><a aria-hidden="true" class="legacy" id="errors_invalid_purpose"></a></h5>
<p>The supplied certificate cannot be used for the specified purpose.</p>
<p><a id="CERT_REJECTED"></a></p>
<h5><code>CERT_REJECTED</code><span><a class="mark" href="#all_errors_cert_rejected" id="all_errors_cert_rejected">#</a></span><a aria-hidden="true" class="legacy" id="errors_cert_rejected"></a></h5>
<p>The root CA is marked to reject the specified purpose.</p>
<p><a id="Formatting Errors"></a></p>
<h4>Formatting Errors<span><a class="mark" href="#all_errors_formatting-errors" id="all_errors_formatting-errors">#</a></span><a aria-hidden="true" class="legacy" id="errors_formatting_errors"></a></h4>
<p><a id="CERT_SIGNATURE_FAILURE"></a></p>
<h5><code>CERT_SIGNATURE_FAILURE</code><span><a class="mark" href="#all_errors_cert_signature_failure" id="all_errors_cert_signature_failure">#</a></span><a aria-hidden="true" class="legacy" id="errors_cert_signature_failure"></a></h5>
<p>The signature of the certificate is invalid.</p>
<p><a id="CRL_SIGNATURE_FAILURE"></a></p>
<h5><code>CRL_SIGNATURE_FAILURE</code><span><a class="mark" href="#all_errors_crl_signature_failure" id="all_errors_crl_signature_failure">#</a></span><a aria-hidden="true" class="legacy" id="errors_crl_signature_failure"></a></h5>
<p>The signature of the certificate revocation list (CRL) is invalid.</p>
<p><a id="ERROR_IN_CERT_NOT_BEFORE_FIELD"></a></p>
<h5><code>ERROR_IN_CERT_NOT_BEFORE_FIELD</code><span><a class="mark" href="#all_errors_error_in_cert_not_before_field" id="all_errors_error_in_cert_not_before_field">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_in_cert_not_before_field"></a></h5>
<p>The certificate notBefore field contains an invalid time.</p>
<p><a id="ERROR_IN_CERT_NOT_AFTER_FIELD"></a></p>
<h5><code>ERROR_IN_CERT_NOT_AFTER_FIELD</code><span><a class="mark" href="#all_errors_error_in_cert_not_after_field" id="all_errors_error_in_cert_not_after_field">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_in_cert_not_after_field"></a></h5>
<p>The certificate notAfter field contains an invalid time.</p>
<p><a id="ERROR_IN_CRL_LAST_UPDATE_FIELD"></a></p>
<h5><code>ERROR_IN_CRL_LAST_UPDATE_FIELD</code><span><a class="mark" href="#all_errors_error_in_crl_last_update_field" id="all_errors_error_in_crl_last_update_field">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_in_crl_last_update_field"></a></h5>
<p>The CRL lastUpdate field contains an invalid time.</p>
<p><a id="ERROR_IN_CRL_NEXT_UPDATE_FIELD"></a></p>
<h5><code>ERROR_IN_CRL_NEXT_UPDATE_FIELD</code><span><a class="mark" href="#all_errors_error_in_crl_next_update_field" id="all_errors_error_in_crl_next_update_field">#</a></span><a aria-hidden="true" class="legacy" id="errors_error_in_crl_next_update_field"></a></h5>
<p>The CRL nextUpdate field contains an invalid time.</p>
<p><a id="UNABLE_TO_DECRYPT_CERT_SIGNATURE"></a></p>
<h5><code>UNABLE_TO_DECRYPT_CERT_SIGNATURE</code><span><a class="mark" href="#all_errors_unable_to_decrypt_cert_signature" id="all_errors_unable_to_decrypt_cert_signature">#</a></span><a aria-hidden="true" class="legacy" id="errors_unable_to_decrypt_cert_signature"></a></h5>
<p>The certificate signature could not be decrypted. This means that the actual
signature value could not be determined rather than it not matching the expected
value, this is only meaningful for RSA keys.</p>
<p><a id="UNABLE_TO_DECRYPT_CRL_SIGNATURE"></a></p>
<h5><code>UNABLE_TO_DECRYPT_CRL_SIGNATURE</code><span><a class="mark" href="#all_errors_unable_to_decrypt_crl_signature" id="all_errors_unable_to_decrypt_crl_signature">#</a></span><a aria-hidden="true" class="legacy" id="errors_unable_to_decrypt_crl_signature"></a></h5>
<p>The certificate revocation list (CRL) signature could not be decrypted: this
means that the actual signature value could not be determined rather than it not
matching the expected value.</p>
<p><a id="UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY"></a></p>
<h5><code>UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY</code><span><a class="mark" href="#all_errors_unable_to_decode_issuer_public_key" id="all_errors_unable_to_decode_issuer_public_key">#</a></span><a aria-hidden="true" class="legacy" id="errors_unable_to_decode_issuer_public_key"></a></h5>
<p>The public key in the certificate SubjectPublicKeyInfo could not be read.</p>
<p><a id="Other OpenSSL Errors"></a></p>
<h4>Other OpenSSL Errors<span><a class="mark" href="#all_errors_other-openssl-errors" id="all_errors_other-openssl-errors">#</a></span><a aria-hidden="true" class="legacy" id="errors_other_openssl_errors"></a></h4>
<p><a id="OUT_OF_MEM"></a></p>
<h5><code>OUT_OF_MEM</code><span><a class="mark" href="#all_errors_out_of_mem" id="all_errors_out_of_mem">#</a></span><a aria-hidden="true" class="legacy" id="errors_out_of_mem"></a></h5>
<p>An error occurred trying to allocate memory. This should never happen.</p></section>
        </section>
<section><h2>Events<span><a class="mark" href="#all_events_events" id="all_events_events">#</a></span><a aria-hidden="true" class="legacy" id="events_events"></a></h2>

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

<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/events.js">lib/events.js</a></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="#all_net_class-netserver"><code>net.Server</code></a> object emits an event each time a peer
connects to it; a <a href="#all_fs_class-fsreadstream"><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 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 class="with-44-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;

<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {}

<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>();
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'an event occurred!'</span>);
});
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);

<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {}

<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>();
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'an event occurred!'</span>);
});
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>);</code><button class="copy-button">copy</button></pre>
<section><h3>Passing arguments and <code>this</code> to listeners<span><a class="mark" href="#all_events_passing-arguments-and-this-to-listeners" id="all_events_passing-arguments-and-this-to-listeners">#</a></span><a aria-hidden="true" class="legacy" id="events_passing_arguments_and_this_to_listeners"></a></h3>
<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 class="with-44-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {}
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>();
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-keyword">function</span>(<span class="hljs-params">a, b</span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(a, b, <span class="hljs-variable language_">this</span>, <span class="hljs-variable language_">this</span> === myEmitter);
  <span class="hljs-comment">// Prints:</span>
  <span class="hljs-comment">//   a b MyEmitter {</span>
  <span class="hljs-comment">//     _events: [Object: null prototype] { event: [Function (anonymous)] },</span>
  <span class="hljs-comment">//     _eventsCount: 1,</span>
  <span class="hljs-comment">//     _maxListeners: undefined,</span>
  <span class="hljs-comment">//     [Symbol(shapeMode)]: false,</span>
  <span class="hljs-comment">//     [Symbol(kCapture)]: false</span>
  <span class="hljs-comment">//   } true</span>
});
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {}
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>();
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-keyword">function</span>(<span class="hljs-params">a, b</span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(a, b, <span class="hljs-variable language_">this</span>, <span class="hljs-variable language_">this</span> === myEmitter);
  <span class="hljs-comment">// Prints:</span>
  <span class="hljs-comment">//   a b MyEmitter {</span>
  <span class="hljs-comment">//     _events: [Object: null prototype] { event: [Function (anonymous)] },</span>
  <span class="hljs-comment">//     _eventsCount: 1,</span>
  <span class="hljs-comment">//     _maxListeners: undefined,</span>
  <span class="hljs-comment">//     [Symbol(shapeMode)]: false,</span>
  <span class="hljs-comment">//     [Symbol(kCapture)]: false</span>
  <span class="hljs-comment">//   } true</span>
});
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>);</code><button class="copy-button">copy</button></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 class="with-44-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {}
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>();
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">(<span class="hljs-params">a, b</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(a, b, <span class="hljs-variable language_">this</span>);
  <span class="hljs-comment">// Prints: a b undefined</span>
});
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {}
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>();
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">(<span class="hljs-params">a, b</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(a, b, <span class="hljs-variable language_">this</span>);
  <span class="hljs-comment">// Prints: a b {}</span>
});
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>);</code><button class="copy-button">copy</button></pre>
</section><section><h3>Asynchronous vs. synchronous<span><a class="mark" href="#all_events_asynchronous-vs-synchronous" id="all_events_asynchronous-vs-synchronous">#</a></span><a aria-hidden="true" class="legacy" id="events_asynchronous_vs_synchronous"></a></h3>
<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 class="with-44-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {}
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>();
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">(<span class="hljs-params">a, b</span>) =></span> {
  <span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'this happens asynchronously'</span>);
  });
});
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {}
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>();
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">(<span class="hljs-params">a, b</span>) =></span> {
  <span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'this happens asynchronously'</span>);
  });
});
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>);</code><button class="copy-button">copy</button></pre>
</section><section><h3>Handling events only once<span><a class="mark" href="#all_events_handling-events-only-once" id="all_events_handling-events-only-once">#</a></span><a aria-hidden="true" class="legacy" id="events_handling_events_only_once"></a></h3>
<p>When a listener is registered using the <code>eventEmitter.on()</code> method, that
listener is invoked <em>every time</em> the named event is emitted.</p>

<pre class="with-44-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {}
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>();
<span class="hljs-keyword">let</span> m = <span class="hljs-number">0</span>;
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(++m);
});
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>);
<span class="hljs-comment">// Prints: 1</span>
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>);
<span class="hljs-comment">// Prints: 2</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {}
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>();
<span class="hljs-keyword">let</span> m = <span class="hljs-number">0</span>;
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(++m);
});
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>);
<span class="hljs-comment">// Prints: 1</span>
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>);
<span class="hljs-comment">// Prints: 2</span></code><button class="copy-button">copy</button></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 class="with-44-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {}
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>();
<span class="hljs-keyword">let</span> m = <span class="hljs-number">0</span>;
myEmitter.<span class="hljs-title function_">once</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(++m);
});
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>);
<span class="hljs-comment">// Prints: 1</span>
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>);
<span class="hljs-comment">// Ignored</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {}
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>();
<span class="hljs-keyword">let</span> m = <span class="hljs-number">0</span>;
myEmitter.<span class="hljs-title function_">once</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(++m);
});
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>);
<span class="hljs-comment">// Prints: 1</span>
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>);
<span class="hljs-comment">// Ignored</span></code><button class="copy-button">copy</button></pre>
</section><section><h3>Error events<span><a class="mark" href="#all_events_error-events" id="all_events_error-events">#</a></span><a aria-hidden="true" class="legacy" id="events_error_events"></a></h3>
<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 class="with-44-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {}
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>();
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'error'</span>, <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'whoops!'</span>));
<span class="hljs-comment">// Throws and crashes Node.js</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {}
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>();
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'error'</span>, <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'whoops!'</span>));
<span class="hljs-comment">// Throws and crashes Node.js</span></code><button class="copy-button">copy</button></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>node:domain</code> module is deprecated.)</p>
<p>As a best practice, listeners should always be added for the <code>'error'</code> events.</p>

<pre class="with-44-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {}
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>();
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'whoops! there was an error'</span>);
});
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'error'</span>, <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'whoops!'</span>));
<span class="hljs-comment">// Prints: whoops! there was an error</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {}
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>();
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'whoops! there was an error'</span>);
});
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'error'</span>, <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'whoops!'</span>));
<span class="hljs-comment">// Prints: whoops! there was an error</span></code><button class="copy-button">copy</button></pre>
<p>It is possible to monitor <code>'error'</code> events without consuming the emitted error
by installing a listener using the symbol <code>events.errorMonitor</code>.</p>

<pre class="with-62-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">EventEmitter</span>, errorMonitor } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;

<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
myEmitter.<span class="hljs-title function_">on</span>(errorMonitor, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-title class_">MyMonitoringTool</span>.<span class="hljs-title function_">log</span>(err);
});
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'error'</span>, <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'whoops!'</span>));
<span class="hljs-comment">// Still throws and crashes Node.js</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">EventEmitter</span>, errorMonitor } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);

<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
myEmitter.<span class="hljs-title function_">on</span>(errorMonitor, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-title class_">MyMonitoringTool</span>.<span class="hljs-title function_">log</span>(err);
});
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'error'</span>, <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'whoops!'</span>));
<span class="hljs-comment">// Still throws and crashes Node.js</span></code><button class="copy-button">copy</button></pre>
</section><section><h3>Capture rejections of promises<span><a class="mark" href="#all_events_capture-rejections-of-promises" id="all_events_capture-rejections-of-promises">#</a></span><a aria-hidden="true" class="legacy" id="events_capture_rejections_of_promises"></a></h3>
<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 class="with-44-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
ee.<span class="hljs-title function_">on</span>(<span class="hljs-string">'something'</span>, <span class="hljs-keyword">async</span> (value) => {
  <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'kaboom'</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
ee.<span class="hljs-title function_">on</span>(<span class="hljs-string">'something'</span>, <span class="hljs-keyword">async</span> (value) => {
  <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'kaboom'</span>);
});</code><button class="copy-button">copy</button></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="#all_events_emittersymbolfornodejsrejectionerr-eventname-args"><code>Symbol.for('nodejs.rejection')</code></a> method
if there is one, or to <a href="#all_events_error-events"><code>'error'</code></a> event handler if there is none.</p>

<pre class="with-58-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">const</span> ee1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>({ <span class="hljs-attr">captureRejections</span>: <span class="hljs-literal">true</span> });
ee1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'something'</span>, <span class="hljs-keyword">async</span> (value) => {
  <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'kaboom'</span>);
});

ee1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>);

<span class="hljs-keyword">const</span> ee2 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>({ <span class="hljs-attr">captureRejections</span>: <span class="hljs-literal">true</span> });
ee2.<span class="hljs-title function_">on</span>(<span class="hljs-string">'something'</span>, <span class="hljs-keyword">async</span> (value) => {
  <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'kaboom'</span>);
});

ee2[<span class="hljs-title class_">Symbol</span>.<span class="hljs-title function_">for</span>(<span class="hljs-string">'nodejs.rejection'</span>)] = <span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">const</span> ee1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>({ <span class="hljs-attr">captureRejections</span>: <span class="hljs-literal">true</span> });
ee1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'something'</span>, <span class="hljs-keyword">async</span> (value) => {
  <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'kaboom'</span>);
});

ee1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>);

<span class="hljs-keyword">const</span> ee2 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>({ <span class="hljs-attr">captureRejections</span>: <span class="hljs-literal">true</span> });
ee2.<span class="hljs-title function_">on</span>(<span class="hljs-string">'something'</span>, <span class="hljs-keyword">async</span> (value) => {
  <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'kaboom'</span>);
});

ee2[<span class="hljs-title class_">Symbol</span>.<span class="hljs-title function_">for</span>(<span class="hljs-string">'nodejs.rejection'</span>)] = <span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>;</code><button class="copy-button">copy</button></pre>
<p>Setting <code>events.captureRejections = true</code> will change the default for all
new instances of <code>EventEmitter</code>.</p>

<pre class="with-43-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;

<span class="hljs-title class_">EventEmitter</span>.<span class="hljs-property">captureRejections</span> = <span class="hljs-literal">true</span>;
<span class="hljs-keyword">const</span> ee1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
ee1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'something'</span>, <span class="hljs-keyword">async</span> (value) => {
  <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'kaboom'</span>);
});

ee1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> events = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
events.<span class="hljs-property">captureRejections</span> = <span class="hljs-literal">true</span>;
<span class="hljs-keyword">const</span> ee1 = <span class="hljs-keyword">new</span> events.<span class="hljs-title class_">EventEmitter</span>();
ee1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'something'</span>, <span class="hljs-keyword">async</span> (value) => {
  <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'kaboom'</span>);
});

ee1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>);</code><button class="copy-button">copy</button></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>
</section><section><h3>Class: <code>EventEmitter</code><span><a class="mark" href="#all_events_class-eventemitter" id="all_events_class-eventemitter">#</a></span><a aria-hidden="true" class="legacy" id="events_class_eventemitter"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.4.0, 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>node:events</code> module:</p>

<pre class="with-44-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);</code><button class="copy-button">copy</button></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="#all_events_capture-rejections-of-promises">automatic capturing of promise rejection</a>.
<strong>Default:</strong> <code>false</code>.</li>
</ul>
<h4>Event: <code>'newListener'</code><span><a class="mark" href="#all_events_event-newlistener" id="all_events_event-newlistener">#</a></span><a aria-hidden="true" class="legacy" id="events_event_newlistener"></a></h4>
<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 are 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 are inserted <em>before</em> the
listener that is in the process of being added.</p>

<pre class="with-44-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {}

<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>();
<span class="hljs-comment">// Only do this once so we don't loop forever</span>
myEmitter.<span class="hljs-title function_">once</span>(<span class="hljs-string">'newListener'</span>, <span class="hljs-function">(<span class="hljs-params">event, listener</span>) =></span> {
  <span class="hljs-keyword">if</span> (event === <span class="hljs-string">'event'</span>) {
    <span class="hljs-comment">// Insert a new listener in front</span>
    myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> {
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'B'</span>);
    });
  }
});
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'A'</span>);
});
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>);
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   B</span>
<span class="hljs-comment">//   A</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {}

<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>();
<span class="hljs-comment">// Only do this once so we don't loop forever</span>
myEmitter.<span class="hljs-title function_">once</span>(<span class="hljs-string">'newListener'</span>, <span class="hljs-function">(<span class="hljs-params">event, listener</span>) =></span> {
  <span class="hljs-keyword">if</span> (event === <span class="hljs-string">'event'</span>) {
    <span class="hljs-comment">// Insert a new listener in front</span>
    myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> {
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'B'</span>);
    });
  }
});
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'A'</span>);
});
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>);
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   B</span>
<span class="hljs-comment">//   A</span></code><button class="copy-button">copy</button></pre>
<h4>Event: <code>'removeListener'</code><span><a class="mark" href="#all_events_event-removelistener" id="all_events_event-removelistener">#</a></span><a aria-hidden="true" class="legacy" id="events_event_removelistener"></a></h4>
<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>
<h4><code>emitter.addListener(eventName, listener)</code><span><a class="mark" href="#all_events_emitteraddlistenereventname-listener" id="all_events_emitteraddlistenereventname-listener">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_addlistener_eventname_listener"></a></h4>
<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>
<h4><code>emitter.emit(eventName[, ...args])</code><span><a class="mark" href="#all_events_emitteremiteventname-args" id="all_events_emitteremiteventname-args">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_emit_eventname_args"></a></h4>
<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 class="with-44-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();

<span class="hljs-comment">// First listener</span>
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-keyword">function</span> <span class="hljs-title function_">firstListener</span>(<span class="hljs-params"></span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Helloooo! first listener'</span>);
});
<span class="hljs-comment">// Second listener</span>
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-keyword">function</span> <span class="hljs-title function_">secondListener</span>(<span class="hljs-params">arg1, arg2</span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`event with parameters <span class="hljs-subst">${arg1}</span>, <span class="hljs-subst">${arg2}</span> in second listener`</span>);
});
<span class="hljs-comment">// Third listener</span>
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-keyword">function</span> <span class="hljs-title function_">thirdListener</span>(<span class="hljs-params">...args</span>) {
  <span class="hljs-keyword">const</span> parameters = args.<span class="hljs-title function_">join</span>(<span class="hljs-string">', '</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`event with parameters <span class="hljs-subst">${parameters}</span> in third listener`</span>);
});

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myEmitter.<span class="hljs-title function_">listeners</span>(<span class="hljs-string">'event'</span>));

myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>);

<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// [</span>
<span class="hljs-comment">//   [Function: firstListener],</span>
<span class="hljs-comment">//   [Function: secondListener],</span>
<span class="hljs-comment">//   [Function: thirdListener]</span>
<span class="hljs-comment">// ]</span>
<span class="hljs-comment">// Helloooo! first listener</span>
<span class="hljs-comment">// event with parameters 1, 2 in second listener</span>
<span class="hljs-comment">// event with parameters 1, 2, 3, 4, 5 in third listener</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();

<span class="hljs-comment">// First listener</span>
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-keyword">function</span> <span class="hljs-title function_">firstListener</span>(<span class="hljs-params"></span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Helloooo! first listener'</span>);
});
<span class="hljs-comment">// Second listener</span>
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-keyword">function</span> <span class="hljs-title function_">secondListener</span>(<span class="hljs-params">arg1, arg2</span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`event with parameters <span class="hljs-subst">${arg1}</span>, <span class="hljs-subst">${arg2}</span> in second listener`</span>);
});
<span class="hljs-comment">// Third listener</span>
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-keyword">function</span> <span class="hljs-title function_">thirdListener</span>(<span class="hljs-params">...args</span>) {
  <span class="hljs-keyword">const</span> parameters = args.<span class="hljs-title function_">join</span>(<span class="hljs-string">', '</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`event with parameters <span class="hljs-subst">${parameters}</span> in third listener`</span>);
});

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myEmitter.<span class="hljs-title function_">listeners</span>(<span class="hljs-string">'event'</span>));

myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>);

<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// [</span>
<span class="hljs-comment">//   [Function: firstListener],</span>
<span class="hljs-comment">//   [Function: secondListener],</span>
<span class="hljs-comment">//   [Function: thirdListener]</span>
<span class="hljs-comment">// ]</span>
<span class="hljs-comment">// Helloooo! first listener</span>
<span class="hljs-comment">// event with parameters 1, 2 in second listener</span>
<span class="hljs-comment">// event with parameters 1, 2, 3, 4, 5 in third listener</span></code><button class="copy-button">copy</button></pre>
<h4><code>emitter.eventNames()</code><span><a class="mark" href="#all_events_emittereventnames" id="all_events_emittereventnames">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_eventnames"></a></h4>
<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 are strings or <code>Symbol</code>s.</p>

<pre class="with-44-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;

<span class="hljs-keyword">const</span> myEE = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
myEE.<span class="hljs-title function_">on</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-function">() =></span> {});
myEE.<span class="hljs-title function_">on</span>(<span class="hljs-string">'bar'</span>, <span class="hljs-function">() =></span> {});

<span class="hljs-keyword">const</span> sym = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'symbol'</span>);
myEE.<span class="hljs-title function_">on</span>(sym, <span class="hljs-function">() =></span> {});

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myEE.<span class="hljs-title function_">eventNames</span>());
<span class="hljs-comment">// Prints: [ 'foo', 'bar', Symbol(symbol) ]</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);

<span class="hljs-keyword">const</span> myEE = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
myEE.<span class="hljs-title function_">on</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-function">() =></span> {});
myEE.<span class="hljs-title function_">on</span>(<span class="hljs-string">'bar'</span>, <span class="hljs-function">() =></span> {});

<span class="hljs-keyword">const</span> sym = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'symbol'</span>);
myEE.<span class="hljs-title function_">on</span>(sym, <span class="hljs-function">() =></span> {});

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myEE.<span class="hljs-title function_">eventNames</span>());
<span class="hljs-comment">// Prints: [ 'foo', 'bar', Symbol(symbol) ]</span></code><button class="copy-button">copy</button></pre>
<h4><code>emitter.getMaxListeners()</code><span><a class="mark" href="#all_events_emittergetmaxlisteners" id="all_events_emittergetmaxlisteners">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_getmaxlisteners"></a></h4>
<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="#all_events_emittersetmaxlistenersn"><code>emitter.setMaxListeners(n)</code></a> or defaults to
<a href="#all_events_eventsdefaultmaxlisteners"><code>events.defaultMaxListeners</code></a>.</p>
<h4><code>emitter.listenerCount(eventName[, listener])</code><span><a class="mark" href="#all_events_emitterlistenercounteventname-listener" id="all_events_emitterlistenercounteventname-listener">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_listenercount_eventname_listener"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.8.0</td>
<td><p>Added the <code>listener</code> argument.</p></td></tr>
<tr><td>v3.2.0</td>
<td><p><span>Added in: v3.2.0</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 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>
<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 for the event named <code>eventName</code>.
If <code>listener</code> is provided, it will return how many times the listener is found
in the list of the listeners of the event.</p>
<h4><code>emitter.listeners(eventName)</code><span><a class="mark" href="#all_events_emitterlistenerseventname" id="all_events_emitterlistenerseventname">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_listeners_eventname"></a></h4>
<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.<span class="hljs-title function_">on</span>(<span class="hljs-string">'connection'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'someone connected!'</span>);
});
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(util.<span class="hljs-title function_">inspect</span>(server.<span class="hljs-title function_">listeners</span>(<span class="hljs-string">'connection'</span>)));
<span class="hljs-comment">// Prints: [ [Function] ]</span></code> <button class="copy-button">copy</button></pre>
<h4><code>emitter.off(eventName, listener)</code><span><a class="mark" href="#all_events_emitteroffeventname-listener" id="all_events_emitteroffeventname-listener">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_off_eventname_listener"></a></h4>
<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="#all_events_class-eventemitter" class="type">&#x3C;EventEmitter></a></li>
</ul>
<p>Alias for <a href="#all_events_emitterremovelistenereventname-listener"><code>emitter.removeListener()</code></a>.</p>
<h4><code>emitter.on(eventName, listener)</code><span><a class="mark" href="#all_events_emitteroneventname-listener" id="all_events_emitteroneventname-listener">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_on_eventname_listener"></a></h4>
<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="#all_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.<span class="hljs-title function_">on</span>(<span class="hljs-string">'connection'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'someone connected!'</span>);
});</code> <button class="copy-button">copy</button></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 class="with-44-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">const</span> myEE = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
myEE.<span class="hljs-title function_">on</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'a'</span>));
myEE.<span class="hljs-title function_">prependListener</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'b'</span>));
myEE.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>);
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   b</span>
<span class="hljs-comment">//   a</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">const</span> myEE = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
myEE.<span class="hljs-title function_">on</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'a'</span>));
myEE.<span class="hljs-title function_">prependListener</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'b'</span>));
myEE.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>);
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   b</span>
<span class="hljs-comment">//   a</span></code><button class="copy-button">copy</button></pre>
<h4><code>emitter.once(eventName, listener)</code><span><a class="mark" href="#all_events_emitteronceeventname-listener" id="all_events_emitteronceeventname-listener">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_once_eventname_listener"></a></h4>
<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="#all_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.<span class="hljs-title function_">once</span>(<span class="hljs-string">'connection'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Ah, we have our first user!'</span>);
});</code> <button class="copy-button">copy</button></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 class="with-44-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">const</span> myEE = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
myEE.<span class="hljs-title function_">once</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'a'</span>));
myEE.<span class="hljs-title function_">prependOnceListener</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'b'</span>));
myEE.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>);
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   b</span>
<span class="hljs-comment">//   a</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">const</span> myEE = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
myEE.<span class="hljs-title function_">once</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'a'</span>));
myEE.<span class="hljs-title function_">prependOnceListener</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'b'</span>));
myEE.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>);
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   b</span>
<span class="hljs-comment">//   a</span></code><button class="copy-button">copy</button></pre>
<h4><code>emitter.prependListener(eventName, listener)</code><span><a class="mark" href="#all_events_emitterprependlistenereventname-listener" id="all_events_emitterprependlistenereventname-listener">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_prependlistener_eventname_listener"></a></h4>
<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="#all_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.<span class="hljs-title function_">prependListener</span>(<span class="hljs-string">'connection'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'someone connected!'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>Returns a reference to the <code>EventEmitter</code>, so that calls can be chained.</p>
<h4><code>emitter.prependOnceListener(eventName, listener)</code><span><a class="mark" href="#all_events_emitterprependoncelistenereventname-listener" id="all_events_emitterprependoncelistenereventname-listener">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_prependoncelistener_eventname_listener"></a></h4>
<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="#all_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.<span class="hljs-title function_">prependOnceListener</span>(<span class="hljs-string">'connection'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Ah, we have our first user!'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>Returns a reference to the <code>EventEmitter</code>, so that calls can be chained.</p>
<h4><code>emitter.removeAllListeners([eventName])</code><span><a class="mark" href="#all_events_emitterremovealllistenerseventname" id="all_events_emitterremovealllistenerseventname">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_removealllisteners_eventname"></a></h4>
<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="#all_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>
<h4><code>emitter.removeListener(eventName, listener)</code><span><a class="mark" href="#all_events_emitterremovelistenereventname-listener" id="all_events_emitterremovelistenereventname-listener">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_removelistener_eventname_listener"></a></h4>
<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="#all_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"><span class="hljs-keyword">const</span> <span class="hljs-title function_">callback</span> = (<span class="hljs-params">stream</span>) => {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'someone connected!'</span>);
};
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'connection'</span>, callback);
<span class="hljs-comment">// ...</span>
server.<span class="hljs-title function_">removeListener</span>(<span class="hljs-string">'connection'</span>, callback);</code> <button class="copy-button">copy</button></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 is emitted, all listeners attached to it at the
time of emitting are 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 behave as expected.</p>

<pre class="with-44-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {}
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>();

<span class="hljs-keyword">const</span> <span class="hljs-title function_">callbackA</span> = (<span class="hljs-params"></span>) => {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'A'</span>);
  myEmitter.<span class="hljs-title function_">removeListener</span>(<span class="hljs-string">'event'</span>, callbackB);
};

<span class="hljs-keyword">const</span> <span class="hljs-title function_">callbackB</span> = (<span class="hljs-params"></span>) => {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'B'</span>);
};

myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, callbackA);

myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, callbackB);

<span class="hljs-comment">// callbackA removes listener callbackB but it will still be called.</span>
<span class="hljs-comment">// Internal listener array at time of emit [callbackA, callbackB]</span>
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>);
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   A</span>
<span class="hljs-comment">//   B</span>

<span class="hljs-comment">// callbackB is now removed.</span>
<span class="hljs-comment">// Internal listener array [callbackA]</span>
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>);
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   A</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyEmitter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {}
<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyEmitter</span>();

<span class="hljs-keyword">const</span> <span class="hljs-title function_">callbackA</span> = (<span class="hljs-params"></span>) => {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'A'</span>);
  myEmitter.<span class="hljs-title function_">removeListener</span>(<span class="hljs-string">'event'</span>, callbackB);
};

<span class="hljs-keyword">const</span> <span class="hljs-title function_">callbackB</span> = (<span class="hljs-params"></span>) => {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'B'</span>);
};

myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, callbackA);

myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, callbackB);

<span class="hljs-comment">// callbackA removes listener callbackB but it will still be called.</span>
<span class="hljs-comment">// Internal listener array at time of emit [callbackA, callbackB]</span>
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>);
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   A</span>
<span class="hljs-comment">//   B</span>

<span class="hljs-comment">// callbackB is now removed.</span>
<span class="hljs-comment">// Internal listener array [callbackA]</span>
myEmitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'event'</span>);
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   A</span></code><button class="copy-button">copy</button></pre>
<p>Because listeners are managed using an internal array, calling this will
change the position indexes 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 class="with-44-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();

<span class="hljs-keyword">function</span> <span class="hljs-title function_">pong</span>(<span class="hljs-params"></span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'pong'</span>);
}

ee.<span class="hljs-title function_">on</span>(<span class="hljs-string">'ping'</span>, pong);
ee.<span class="hljs-title function_">once</span>(<span class="hljs-string">'ping'</span>, pong);
ee.<span class="hljs-title function_">removeListener</span>(<span class="hljs-string">'ping'</span>, pong);

ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'ping'</span>);
ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'ping'</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();

<span class="hljs-keyword">function</span> <span class="hljs-title function_">pong</span>(<span class="hljs-params"></span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'pong'</span>);
}

ee.<span class="hljs-title function_">on</span>(<span class="hljs-string">'ping'</span>, pong);
ee.<span class="hljs-title function_">once</span>(<span class="hljs-string">'ping'</span>, pong);
ee.<span class="hljs-title function_">removeListener</span>(<span class="hljs-string">'ping'</span>, pong);

ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'ping'</span>);
ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'ping'</span>);</code><button class="copy-button">copy</button></pre>
<p>Returns a reference to the <code>EventEmitter</code>, so that calls can be chained.</p>
<h4><code>emitter.setMaxListeners(n)</code><span><a class="mark" href="#all_events_emittersetmaxlistenersn" id="all_events_emittersetmaxlistenersn">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_setmaxlisteners_n"></a></h4>
<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="#all_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>
<h4><code>emitter.rawListeners(eventName)</code><span><a class="mark" href="#all_events_emitterrawlistenerseventname" id="all_events_emitterrawlistenerseventname">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_rawlisteners_eventname"></a></h4>
<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 class="with-44-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">const</span> emitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
emitter.<span class="hljs-title function_">once</span>(<span class="hljs-string">'log'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'log once'</span>));

<span class="hljs-comment">// Returns a new Array with a function `onceWrapper` which has a property</span>
<span class="hljs-comment">// `listener` which contains the original listener bound above</span>
<span class="hljs-keyword">const</span> listeners = emitter.<span class="hljs-title function_">rawListeners</span>(<span class="hljs-string">'log'</span>);
<span class="hljs-keyword">const</span> logFnWrapper = listeners[<span class="hljs-number">0</span>];

<span class="hljs-comment">// Logs "log once" to the console and does not unbind the `once` event</span>
logFnWrapper.<span class="hljs-title function_">listener</span>();

<span class="hljs-comment">// Logs "log once" to the console and removes the listener</span>
<span class="hljs-title function_">logFnWrapper</span>();

emitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'log'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'log persistently'</span>));
<span class="hljs-comment">// Will return a new Array with a single function bound by `.on()` above</span>
<span class="hljs-keyword">const</span> newListeners = emitter.<span class="hljs-title function_">rawListeners</span>(<span class="hljs-string">'log'</span>);

<span class="hljs-comment">// Logs "log persistently" twice</span>
newListeners[<span class="hljs-number">0</span>]();
emitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'log'</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">const</span> emitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
emitter.<span class="hljs-title function_">once</span>(<span class="hljs-string">'log'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'log once'</span>));

<span class="hljs-comment">// Returns a new Array with a function `onceWrapper` which has a property</span>
<span class="hljs-comment">// `listener` which contains the original listener bound above</span>
<span class="hljs-keyword">const</span> listeners = emitter.<span class="hljs-title function_">rawListeners</span>(<span class="hljs-string">'log'</span>);
<span class="hljs-keyword">const</span> logFnWrapper = listeners[<span class="hljs-number">0</span>];

<span class="hljs-comment">// Logs "log once" to the console and does not unbind the `once` event</span>
logFnWrapper.<span class="hljs-title function_">listener</span>();

<span class="hljs-comment">// Logs "log once" to the console and removes the listener</span>
<span class="hljs-title function_">logFnWrapper</span>();

emitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'log'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'log persistently'</span>));
<span class="hljs-comment">// Will return a new Array with a single function bound by `.on()` above</span>
<span class="hljs-keyword">const</span> newListeners = emitter.<span class="hljs-title function_">rawListeners</span>(<span class="hljs-string">'log'</span>);

<span class="hljs-comment">// Logs "log persistently" twice</span>
newListeners[<span class="hljs-number">0</span>]();
emitter.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'log'</span>);</code><button class="copy-button">copy</button></pre>
<h4><code>emitter[Symbol.for('nodejs.rejection')](err, eventName[, ...args])</code><span><a class="mark" href="#all_events_emittersymbolfornodejsrejectionerr-eventname-args" id="all_events_emittersymbolfornodejsrejectionerr-eventname-args">#</a></span><a aria-hidden="true" class="legacy" id="events_emitter_symbol_for_nodejs_rejection_err_eventname_args"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.4.0, v16.14.0</td>
<td><p>No longer experimental.</p></td></tr>
<tr><td>v13.4.0, v12.16.0</td>
<td><p><span>Added in: v13.4.0, v12.16.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<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="#all_events_capture-rejections-of-promises"><code>captureRejections</code></a> is enabled on the emitter.
It is possible to use <a href="#all_events_eventscapturerejectionsymbol"><code>events.captureRejectionSymbol</code></a> in
place of <code>Symbol.for('nodejs.rejection')</code>.</p>

<pre class="with-72-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">EventEmitter</span>, captureRejectionSymbol } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;

<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyClass</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {
  <span class="hljs-title function_">constructor</span>(<span class="hljs-params"></span>) {
    <span class="hljs-variable language_">super</span>({ <span class="hljs-attr">captureRejections</span>: <span class="hljs-literal">true</span> });
  }

  [captureRejectionSymbol](err, event, ...args) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'rejection happened for'</span>, event, <span class="hljs-string">'with'</span>, err, ...args);
    <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">destroy</span>(err);
  }

  <span class="hljs-title function_">destroy</span>(<span class="hljs-params">err</span>) {
    <span class="hljs-comment">// Tear the resource down here.</span>
  }
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">EventEmitter</span>, captureRejectionSymbol } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);

<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyClass</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {
  <span class="hljs-title function_">constructor</span>(<span class="hljs-params"></span>) {
    <span class="hljs-variable language_">super</span>({ <span class="hljs-attr">captureRejections</span>: <span class="hljs-literal">true</span> });
  }

  [captureRejectionSymbol](err, event, ...args) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'rejection happened for'</span>, event, <span class="hljs-string">'with'</span>, err, ...args);
    <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">destroy</span>(err);
  }

  <span class="hljs-title function_">destroy</span>(<span class="hljs-params">err</span>) {
    <span class="hljs-comment">// Tear the resource down here.</span>
  }
}</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>events.defaultMaxListeners</code><span><a class="mark" href="#all_events_eventsdefaultmaxlisteners" id="all_events_eventsdefaultmaxlisteners">#</a></span><a aria-hidden="true" class="legacy" id="events_events_defaultmaxlisteners"></a></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="#all_events_emittersetmaxlistenersn"><code>emitter.setMaxListeners(n)</code></a> method. To change the default
for <em>all</em> <code>EventEmitter</code> instances, the <code>events.defaultMaxListeners</code>
property can be used. If this value is not a positive number, a <code>RangeError</code>
is thrown.</p>
<p>Take caution when setting the <code>events.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="#all_events_emittersetmaxlistenersn"><code>emitter.setMaxListeners(n)</code></a> still has
precedence over <code>events.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 class="with-44-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">const</span> emitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
emitter.<span class="hljs-title function_">setMaxListeners</span>(emitter.<span class="hljs-title function_">getMaxListeners</span>() + <span class="hljs-number">1</span>);
emitter.<span class="hljs-title function_">once</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-comment">// do stuff</span>
  emitter.<span class="hljs-title function_">setMaxListeners</span>(<span class="hljs-title class_">Math</span>.<span class="hljs-title function_">max</span>(emitter.<span class="hljs-title function_">getMaxListeners</span>() - <span class="hljs-number">1</span>, <span class="hljs-number">0</span>));
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">const</span> emitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
emitter.<span class="hljs-title function_">setMaxListeners</span>(emitter.<span class="hljs-title function_">getMaxListeners</span>() + <span class="hljs-number">1</span>);
emitter.<span class="hljs-title function_">once</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-comment">// do stuff</span>
  emitter.<span class="hljs-title function_">setMaxListeners</span>(<span class="hljs-title class_">Math</span>.<span class="hljs-title function_">max</span>(emitter.<span class="hljs-title function_">getMaxListeners</span>() - <span class="hljs-number">1</span>, <span class="hljs-number">0</span>));
});</code><button class="copy-button">copy</button></pre>
<p>The <a href="#all_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="#all_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>
</section><section><h3><code>events.errorMonitor</code><span><a class="mark" href="#all_events_eventserrormonitor" id="all_events_eventserrormonitor">#</a></span><a aria-hidden="true" class="legacy" id="events_events_errormonitor"></a></h3>
<div class="api_metadata">
<span>Added in: v13.6.0, 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>
</section><section><h3><code>events.getEventListeners(emitterOrTarget, eventName)</code><span><a class="mark" href="#all_events_eventsgeteventlistenersemitterortarget-eventname" id="all_events_eventsgeteventlistenersemitterortarget-eventname">#</a></span><a aria-hidden="true" class="legacy" id="events_events_geteventlisteners_emitterortarget_eventname"></a></h3>
<div class="api_metadata">
<span>Added in: v15.2.0, v14.17.0</span>
</div>
<ul>
<li><code>emitterOrTarget</code> <a href="#all_events_class-eventemitter" class="type">&#x3C;EventEmitter></a> | <a href="#all_events_class-eventtarget" class="type">&#x3C;EventTarget></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></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>
<p>For <code>EventEmitter</code>s this behaves exactly the same as calling <code>.listeners</code> on
the emitter.</p>
<p>For <code>EventTarget</code>s this is the only way to get the event listeners for the
event target. This is useful for debugging and diagnostic purposes.</p>

<pre class="with-67-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { getEventListeners, <span class="hljs-title class_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;

{
  <span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
  <span class="hljs-keyword">const</span> <span class="hljs-title function_">listener</span> = (<span class="hljs-params"></span>) => <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Events are fun'</span>);
  ee.<span class="hljs-title function_">on</span>(<span class="hljs-string">'foo'</span>, listener);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getEventListeners</span>(ee, <span class="hljs-string">'foo'</span>)); <span class="hljs-comment">// [ [Function: listener] ]</span>
}
{
  <span class="hljs-keyword">const</span> et = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventTarget</span>();
  <span class="hljs-keyword">const</span> <span class="hljs-title function_">listener</span> = (<span class="hljs-params"></span>) => <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Events are fun'</span>);
  et.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">'foo'</span>, listener);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getEventListeners</span>(et, <span class="hljs-string">'foo'</span>)); <span class="hljs-comment">// [ [Function: listener] ]</span>
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { getEventListeners, <span class="hljs-title class_">EventEmitter</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);

{
  <span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
  <span class="hljs-keyword">const</span> <span class="hljs-title function_">listener</span> = (<span class="hljs-params"></span>) => <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Events are fun'</span>);
  ee.<span class="hljs-title function_">on</span>(<span class="hljs-string">'foo'</span>, listener);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getEventListeners</span>(ee, <span class="hljs-string">'foo'</span>)); <span class="hljs-comment">// [ [Function: listener] ]</span>
}
{
  <span class="hljs-keyword">const</span> et = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventTarget</span>();
  <span class="hljs-keyword">const</span> <span class="hljs-title function_">listener</span> = (<span class="hljs-params"></span>) => <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Events are fun'</span>);
  et.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">'foo'</span>, listener);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getEventListeners</span>(et, <span class="hljs-string">'foo'</span>)); <span class="hljs-comment">// [ [Function: listener] ]</span>
}</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>events.getMaxListeners(emitterOrTarget)</code><span><a class="mark" href="#all_events_eventsgetmaxlistenersemitterortarget" id="all_events_eventsgetmaxlistenersemitterortarget">#</a></span><a aria-hidden="true" class="legacy" id="events_events_getmaxlisteners_emitterortarget"></a></h3>
<div class="api_metadata">
<span>Added in: v19.9.0</span>
</div>
<ul>
<li><code>emitterOrTarget</code> <a href="#all_events_class-eventemitter" class="type">&#x3C;EventEmitter></a> | <a href="#all_events_class-eventtarget" class="type">&#x3C;EventTarget></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 currently set max amount of listeners.</p>
<p>For <code>EventEmitter</code>s this behaves exactly the same as calling <code>.getMaxListeners</code> on
the emitter.</p>
<p>For <code>EventTarget</code>s this is the only way to get the max event listeners for the
event target. If the number of event handlers on a single EventTarget exceeds
the max set, the EventTarget will print a warning.</p>

<pre class="with-82-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { getMaxListeners, setMaxListeners, <span class="hljs-title class_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;

{
  <span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getMaxListeners</span>(ee)); <span class="hljs-comment">// 10</span>
  <span class="hljs-title function_">setMaxListeners</span>(<span class="hljs-number">11</span>, ee);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getMaxListeners</span>(ee)); <span class="hljs-comment">// 11</span>
}
{
  <span class="hljs-keyword">const</span> et = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventTarget</span>();
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getMaxListeners</span>(et)); <span class="hljs-comment">// 10</span>
  <span class="hljs-title function_">setMaxListeners</span>(<span class="hljs-number">11</span>, et);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getMaxListeners</span>(et)); <span class="hljs-comment">// 11</span>
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { getMaxListeners, setMaxListeners, <span class="hljs-title class_">EventEmitter</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);

{
  <span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getMaxListeners</span>(ee)); <span class="hljs-comment">// 10</span>
  <span class="hljs-title function_">setMaxListeners</span>(<span class="hljs-number">11</span>, ee);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getMaxListeners</span>(ee)); <span class="hljs-comment">// 11</span>
}
{
  <span class="hljs-keyword">const</span> et = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventTarget</span>();
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getMaxListeners</span>(et)); <span class="hljs-comment">// 10</span>
  <span class="hljs-title function_">setMaxListeners</span>(<span class="hljs-number">11</span>, et);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getMaxListeners</span>(et)); <span class="hljs-comment">// 11</span>
}</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>events.once(emitter, name[, options])</code><span><a class="mark" href="#all_events_eventsonceemitter-name-options" id="all_events_eventsonceemitter-name-options">#</a></span><a aria-hidden="true" class="legacy" id="events_events_once_emitter_name_options"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>The <code>signal</code> option is supported now.</p></td></tr>
<tr><td>v11.13.0, v10.16.0</td>
<td><p><span>Added in: v11.13.0, v10.16.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>emitter</code> <a href="#all_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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type">&#x3C;symbol></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>
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> Can be used to cancel waiting for the event.</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 <code>Promise</code> that is fulfilled when the <code>EventEmitter</code> emits the given
event or that is rejected if the <code>EventEmitter</code> emits <code>'error'</code> while waiting.
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 class="with-54-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { once, <span class="hljs-title class_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();

process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> {
  ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'myevent'</span>, <span class="hljs-number">42</span>);
});

<span class="hljs-keyword">const</span> [value] = <span class="hljs-keyword">await</span> <span class="hljs-title function_">once</span>(ee, <span class="hljs-string">'myevent'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(value);

<span class="hljs-keyword">const</span> err = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'kaboom'</span>);
process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> {
  ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'error'</span>, err);
});

<span class="hljs-keyword">try</span> {
  <span class="hljs-keyword">await</span> <span class="hljs-title function_">once</span>(ee, <span class="hljs-string">'myevent'</span>);
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'error happened'</span>, err);
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { once, <span class="hljs-title class_">EventEmitter</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">run</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();

  process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> {
    ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'myevent'</span>, <span class="hljs-number">42</span>);
  });

  <span class="hljs-keyword">const</span> [value] = <span class="hljs-keyword">await</span> <span class="hljs-title function_">once</span>(ee, <span class="hljs-string">'myevent'</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(value);

  <span class="hljs-keyword">const</span> err = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'kaboom'</span>);
  process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> {
    ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'error'</span>, err);
  });

  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">await</span> <span class="hljs-title function_">once</span>(ee, <span class="hljs-string">'myevent'</span>);
  } <span class="hljs-keyword">catch</span> (err) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'error happened'</span>, err);
  }
}

<span class="hljs-title function_">run</span>();</code><button class="copy-button">copy</button></pre>
<p>The special handling of the <code>'error'</code> event is only used when <code>events.once()</code>
is used to wait for another event. If <code>events.once()</code> is used to wait for the
'<code>error'</code> event itself, then it is treated as any other kind of event without
special handling:</p>

<pre class="with-54-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">EventEmitter</span>, once } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;

<span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();

<span class="hljs-title function_">once</span>(ee, <span class="hljs-string">'error'</span>)
  .<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">[err]</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'ok'</span>, err.<span class="hljs-property">message</span>))
  .<span class="hljs-title function_">catch</span>(<span class="hljs-function">(<span class="hljs-params">err</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'error'</span>, err.<span class="hljs-property">message</span>));

ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'error'</span>, <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'boom'</span>));

<span class="hljs-comment">// Prints: ok boom</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">EventEmitter</span>, once } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);

<span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();

<span class="hljs-title function_">once</span>(ee, <span class="hljs-string">'error'</span>)
  .<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">[err]</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'ok'</span>, err.<span class="hljs-property">message</span>))
  .<span class="hljs-title function_">catch</span>(<span class="hljs-function">(<span class="hljs-params">err</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'error'</span>, err.<span class="hljs-property">message</span>));

ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'error'</span>, <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'boom'</span>));

<span class="hljs-comment">// Prints: ok boom</span></code><button class="copy-button">copy</button></pre>
<p>An <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> can be used to cancel waiting for the event:</p>

<pre class="with-54-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">EventEmitter</span>, once } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;

<span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
<span class="hljs-keyword">const</span> ac = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">foo</span>(<span class="hljs-params">emitter, event, signal</span>) {
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">await</span> <span class="hljs-title function_">once</span>(emitter, event, { signal });
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'event emitted!'</span>);
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-keyword">if</span> (error.<span class="hljs-property">name</span> === <span class="hljs-string">'AbortError'</span>) {
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'Waiting for the event was canceled!'</span>);
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'There was an error'</span>, error.<span class="hljs-property">message</span>);
    }
  }
}

<span class="hljs-title function_">foo</span>(ee, <span class="hljs-string">'foo'</span>, ac.<span class="hljs-property">signal</span>);
ac.<span class="hljs-title function_">abort</span>(); <span class="hljs-comment">// Abort waiting for the event</span>
ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>); <span class="hljs-comment">// Prints: Waiting for the event was canceled!</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">EventEmitter</span>, once } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);

<span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
<span class="hljs-keyword">const</span> ac = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">foo</span>(<span class="hljs-params">emitter, event, signal</span>) {
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">await</span> <span class="hljs-title function_">once</span>(emitter, event, { signal });
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'event emitted!'</span>);
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-keyword">if</span> (error.<span class="hljs-property">name</span> === <span class="hljs-string">'AbortError'</span>) {
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'Waiting for the event was canceled!'</span>);
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'There was an error'</span>, error.<span class="hljs-property">message</span>);
    }
  }
}

<span class="hljs-title function_">foo</span>(ee, <span class="hljs-string">'foo'</span>, ac.<span class="hljs-property">signal</span>);
ac.<span class="hljs-title function_">abort</span>(); <span class="hljs-comment">// Abort waiting for the event</span>
ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>); <span class="hljs-comment">// Prints: Waiting for the event was canceled!</span></code><button class="copy-button">copy</button></pre>
<h4>Awaiting multiple events emitted on <code>process.nextTick()</code><span><a class="mark" href="#all_events_awaiting-multiple-events-emitted-on-processnexttick" id="all_events_awaiting-multiple-events-emitted-on-processnexttick">#</a></span><a aria-hidden="true" class="legacy" id="events_awaiting_multiple_events_emitted_on_process_nexttick"></a></h4>
<p>There is an edge case worth noting when using the <code>events.once()</code> function
to await multiple events emitted on in the same batch of <code>process.nextTick()</code>
operations, or whenever multiple events are emitted synchronously. Specifically,
because the <code>process.nextTick()</code> queue is drained before the <code>Promise</code> microtask
queue, and because <code>EventEmitter</code> emits all events synchronously, it is possible
for <code>events.once()</code> to miss an event.</p>

<pre class="with-54-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">EventEmitter</span>, once } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-keyword">const</span> myEE = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">foo</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">await</span> <span class="hljs-title function_">once</span>(myEE, <span class="hljs-string">'bar'</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'bar'</span>);

  <span class="hljs-comment">// This Promise will never resolve because the 'foo' event will</span>
  <span class="hljs-comment">// have already been emitted before the Promise is created.</span>
  <span class="hljs-keyword">await</span> <span class="hljs-title function_">once</span>(myEE, <span class="hljs-string">'foo'</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'foo'</span>);
}

process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> {
  myEE.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'bar'</span>);
  myEE.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>);
});

<span class="hljs-title function_">foo</span>().<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'done'</span>));</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">EventEmitter</span>, once } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);

<span class="hljs-keyword">const</span> myEE = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">foo</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">await</span> <span class="hljs-title function_">once</span>(myEE, <span class="hljs-string">'bar'</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'bar'</span>);

  <span class="hljs-comment">// This Promise will never resolve because the 'foo' event will</span>
  <span class="hljs-comment">// have already been emitted before the Promise is created.</span>
  <span class="hljs-keyword">await</span> <span class="hljs-title function_">once</span>(myEE, <span class="hljs-string">'foo'</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'foo'</span>);
}

process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> {
  myEE.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'bar'</span>);
  myEE.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>);
});

<span class="hljs-title function_">foo</span>().<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'done'</span>));</code><button class="copy-button">copy</button></pre>
<p>To catch both events, create each of the Promises <em>before</em> awaiting either
of them, then it becomes possible to use <code>Promise.all()</code>, <code>Promise.race()</code>,
or <code>Promise.allSettled()</code>:</p>

<pre class="with-54-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">EventEmitter</span>, once } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-keyword">const</span> myEE = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">foo</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">await</span> <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">all</span>([<span class="hljs-title function_">once</span>(myEE, <span class="hljs-string">'bar'</span>), <span class="hljs-title function_">once</span>(myEE, <span class="hljs-string">'foo'</span>)]);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-string">'bar'</span>);
}

process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> {
  myEE.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'bar'</span>);
  myEE.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>);
});

<span class="hljs-title function_">foo</span>().<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'done'</span>));</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">EventEmitter</span>, once } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);

<span class="hljs-keyword">const</span> myEE = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">foo</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">await</span> <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">all</span>([<span class="hljs-title function_">once</span>(myEE, <span class="hljs-string">'bar'</span>), <span class="hljs-title function_">once</span>(myEE, <span class="hljs-string">'foo'</span>)]);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-string">'bar'</span>);
}

process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> {
  myEE.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'bar'</span>);
  myEE.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>);
});

<span class="hljs-title function_">foo</span>().<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'done'</span>));</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>events.captureRejections</code><span><a class="mark" href="#all_events_eventscapturerejections" id="all_events_eventscapturerejections">#</a></span><a aria-hidden="true" class="legacy" id="events_events_capturerejections"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.4.0, v16.14.0</td>
<td><p>No longer experimental.</p></td></tr>
<tr><td>v13.4.0, v12.16.0</td>
<td><p><span>Added in: v13.4.0, v12.16.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<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>
</section><section><h3><code>events.captureRejectionSymbol</code><span><a class="mark" href="#all_events_eventscapturerejectionsymbol" id="all_events_eventscapturerejectionsymbol">#</a></span><a aria-hidden="true" class="legacy" id="events_events_capturerejectionsymbol"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.4.0, v16.14.0</td>
<td><p>No longer experimental.</p></td></tr>
<tr><td>v13.4.0, v12.16.0</td>
<td><p><span>Added in: v13.4.0, v12.16.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Value: <code>Symbol.for('nodejs.rejection')</code></p>
<p>See how to write a custom <a href="#all_events_emittersymbolfornodejsrejectionerr-eventname-args">rejection handler</a>.</p>
</section><section><h3><code>events.listenerCount(emitter, eventName)</code><span><a class="mark" href="#all_events_eventslistenercountemitter-eventname" id="all_events_eventslistenercountemitter-eventname">#</a></span><a aria-hidden="true" class="legacy" id="events_events_listenercount_emitter_eventname"></a></h3>
<div class="api_metadata">
<span>Added in: v0.9.12</span><span>Deprecated since: v3.2.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_events_emitterlistenercounteventname-listener"><code>emitter.listenerCount()</code></a> instead.</div><p></p>
<ul>
<li><code>emitter</code> <a href="#all_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 class="with-63-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">EventEmitter</span>, listenerCount } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;

<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> {});
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> {});
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">listenerCount</span>(myEmitter, <span class="hljs-string">'event'</span>));
<span class="hljs-comment">// Prints: 2</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">EventEmitter</span>, listenerCount } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);

<span class="hljs-keyword">const</span> myEmitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> {});
myEmitter.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> {});
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">listenerCount</span>(myEmitter, <span class="hljs-string">'event'</span>));
<span class="hljs-comment">// Prints: 2</span></code><button class="copy-button">copy</button></pre>
</section><section><h3><code>events.on(emitter, eventName[, options])</code><span><a class="mark" href="#all_events_eventsonemitter-eventname-options" id="all_events_eventsonemitter-eventname-options">#</a></span><a aria-hidden="true" class="legacy" id="events_events_on_emitter_eventname_options"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.13.0</td>
<td><p>Support <code>highWaterMark</code> and <code>lowWaterMark</code> options, For consistency. Old options are still supported.</p></td></tr>
<tr><td>v20.0.0</td>
<td><p>The <code>close</code>, <code>highWatermark</code>, and <code>lowWatermark</code> options are supported now.</p></td></tr>
<tr><td>v13.6.0, v12.16.0</td>
<td><p><span>Added in: v13.6.0, v12.16.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>emitter</code> <a href="#all_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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> Can be used to cancel awaiting events.</li>
<li><code>close</code> - <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> Names of events that will end the iteration.</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>Number.MAX_SAFE_INTEGER</code>
The high watermark. The emitter is paused every time the size of events
being buffered is higher than it. Supported only on emitters implementing
<code>pause()</code> and <code>resume()</code> methods.</li>
<li><code>lowWaterMark</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>1</code>
The low watermark. The emitter is resumed every time the size of events
being buffered is lower than it. Supported only on emitters implementing
<code>pause()</code> and <code>resume()</code> methods.</li>
</ul>
</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 class="with-52-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { on, <span class="hljs-title class_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();

<span class="hljs-comment">// Emit later on</span>
process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> {
  ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-string">'bar'</span>);
  ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-number">42</span>);
});

<span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> event <span class="hljs-keyword">of</span> <span class="hljs-title function_">on</span>(ee, <span class="hljs-string">'foo'</span>)) {
  <span class="hljs-comment">// The execution of this inner block is synchronous and it</span>
  <span class="hljs-comment">// processes one event at a time (even with await). Do not use</span>
  <span class="hljs-comment">// if concurrent execution is required.</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(event); <span class="hljs-comment">// prints ['bar'] [42]</span>
}
<span class="hljs-comment">// Unreachable here</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { on, <span class="hljs-title class_">EventEmitter</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);

(<span class="hljs-keyword">async</span> () => {
  <span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();

  <span class="hljs-comment">// Emit later on</span>
  process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> {
    ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-string">'bar'</span>);
    ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-number">42</span>);
  });

  <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> event <span class="hljs-keyword">of</span> <span class="hljs-title function_">on</span>(ee, <span class="hljs-string">'foo'</span>)) {
    <span class="hljs-comment">// The execution of this inner block is synchronous and it</span>
    <span class="hljs-comment">// processes one event at a time (even with await). Do not use</span>
    <span class="hljs-comment">// if concurrent execution is required.</span>
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(event); <span class="hljs-comment">// prints ['bar'] [42]</span>
  }
  <span class="hljs-comment">// Unreachable here</span>
})();</code><button class="copy-button">copy</button></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>
<p>An <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> can be used to cancel waiting on events:</p>

<pre class="with-52-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { on, <span class="hljs-title class_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-keyword">const</span> ac = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();

(<span class="hljs-keyword">async</span> () => {
  <span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();

  <span class="hljs-comment">// Emit later on</span>
  process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> {
    ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-string">'bar'</span>);
    ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-number">42</span>);
  });

  <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> event <span class="hljs-keyword">of</span> <span class="hljs-title function_">on</span>(ee, <span class="hljs-string">'foo'</span>, { <span class="hljs-attr">signal</span>: ac.<span class="hljs-property">signal</span> })) {
    <span class="hljs-comment">// The execution of this inner block is synchronous and it</span>
    <span class="hljs-comment">// processes one event at a time (even with await). Do not use</span>
    <span class="hljs-comment">// if concurrent execution is required.</span>
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(event); <span class="hljs-comment">// prints ['bar'] [42]</span>
  }
  <span class="hljs-comment">// Unreachable here</span>
})();

process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> ac.<span class="hljs-title function_">abort</span>());</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { on, <span class="hljs-title class_">EventEmitter</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);

<span class="hljs-keyword">const</span> ac = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();

(<span class="hljs-keyword">async</span> () => {
  <span class="hljs-keyword">const</span> ee = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();

  <span class="hljs-comment">// Emit later on</span>
  process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> {
    ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-string">'bar'</span>);
    ee.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-number">42</span>);
  });

  <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> event <span class="hljs-keyword">of</span> <span class="hljs-title function_">on</span>(ee, <span class="hljs-string">'foo'</span>, { <span class="hljs-attr">signal</span>: ac.<span class="hljs-property">signal</span> })) {
    <span class="hljs-comment">// The execution of this inner block is synchronous and it</span>
    <span class="hljs-comment">// processes one event at a time (even with await). Do not use</span>
    <span class="hljs-comment">// if concurrent execution is required.</span>
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(event); <span class="hljs-comment">// prints ['bar'] [42]</span>
  }
  <span class="hljs-comment">// Unreachable here</span>
})();

process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> ac.<span class="hljs-title function_">abort</span>());</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>events.setMaxListeners(n[, ...eventTargets])</code><span><a class="mark" href="#all_events_eventssetmaxlistenersn-eventtargets" id="all_events_eventssetmaxlistenersn-eventtargets">#</a></span><a aria-hidden="true" class="legacy" id="events_events_setmaxlisteners_n_eventtargets"></a></h3>
<div class="api_metadata">
<span>Added in: v15.4.0</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;number></a> A non-negative number. The maximum number of listeners per
<code>EventTarget</code> event.</li>
<li><code>...eventsTargets</code> <a href="#all_events_class-eventtarget" class="type">&#x3C;EventTarget[]></a> | <a href="#all_events_class-eventemitter" class="type">&#x3C;EventEmitter[]></a> Zero or more <a href="#all_events_class-eventtarget" class="type">&#x3C;EventTarget></a>
or <a href="#all_events_class-eventemitter" class="type">&#x3C;EventEmitter></a> instances. If none are specified, <code>n</code> is set as the default
max for all newly created <a href="#all_events_class-eventtarget" class="type">&#x3C;EventTarget></a> and <a href="#all_events_class-eventemitter" class="type">&#x3C;EventEmitter></a> objects.</li>
</ul>

<pre class="with-60-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { setMaxListeners, <span class="hljs-title class_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;

<span class="hljs-keyword">const</span> target = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventTarget</span>();
<span class="hljs-keyword">const</span> emitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();

<span class="hljs-title function_">setMaxListeners</span>(<span class="hljs-number">5</span>, target, emitter);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
  setMaxListeners,
  <span class="hljs-title class_">EventEmitter</span>,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);

<span class="hljs-keyword">const</span> target = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventTarget</span>();
<span class="hljs-keyword">const</span> emitter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();

<span class="hljs-title function_">setMaxListeners</span>(<span class="hljs-number">5</span>, target, emitter);</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>events.addAbortListener(signal, listener)</code><span><a class="mark" href="#all_events_eventsaddabortlistenersignal-listener" id="all_events_eventsaddabortlistenersignal-listener">#</a></span><a aria-hidden="true" class="legacy" id="events_events_addabortlistener_signal_listener"></a></h3>
<div class="api_metadata">
<span>Added in: v20.5.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></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> | <a href="#all_events_event-listener" class="type">&#x3C;EventListener></a></li>
<li>Returns: <a href="https://tc39.es/proposal-explicit-resource-management/#sec-disposable-interface" class="type">&#x3C;Disposable></a> A Disposable that removes the <code>abort</code> listener.</li>
</ul>
<p>Listens once to the <code>abort</code> event on the provided <code>signal</code>.</p>
<p>Listening to the <code>abort</code> event on abort signals is unsafe and may
lead to resource leaks since another third party with the signal can
call <a href="#all_events_eventstopimmediatepropagation"><code>e.stopImmediatePropagation()</code></a>. Unfortunately Node.js cannot change
this since it would violate the web standard. Additionally, the original
API makes it easy to forget to remove listeners.</p>
<p>This API allows safely using <code>AbortSignal</code>s in Node.js APIs by solving these
two issues by listening to the event such that <code>stopImmediatePropagation</code> does
not prevent the listener from running.</p>
<p>Returns a disposable so that it may be unsubscribed from more easily.</p>

<pre class="with-52-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { addAbortListener } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);

<span class="hljs-keyword">function</span> <span class="hljs-title function_">example</span>(<span class="hljs-params">signal</span>) {
  <span class="hljs-keyword">let</span> disposable;
  <span class="hljs-keyword">try</span> {
    signal.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">'abort'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =></span> e.<span class="hljs-title function_">stopImmediatePropagation</span>());
    disposable = <span class="hljs-title function_">addAbortListener</span>(signal, <span class="hljs-function">(<span class="hljs-params">e</span>) =></span> {
      <span class="hljs-comment">// Do something when signal is aborted.</span>
    });
  } <span class="hljs-keyword">finally</span> {
    disposable?.[<span class="hljs-title class_">Symbol</span>.<span class="hljs-property">dispose</span>]();
  }
}</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { addAbortListener } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;

<span class="hljs-keyword">function</span> <span class="hljs-title function_">example</span>(<span class="hljs-params">signal</span>) {
  <span class="hljs-keyword">let</span> disposable;
  <span class="hljs-keyword">try</span> {
    signal.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">'abort'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =></span> e.<span class="hljs-title function_">stopImmediatePropagation</span>());
    disposable = <span class="hljs-title function_">addAbortListener</span>(signal, <span class="hljs-function">(<span class="hljs-params">e</span>) =></span> {
      <span class="hljs-comment">// Do something when signal is aborted.</span>
    });
  } <span class="hljs-keyword">finally</span> {
    disposable?.[<span class="hljs-title class_">Symbol</span>.<span class="hljs-property">dispose</span>]();
  }
}</code><button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>events.EventEmitterAsyncResource extends EventEmitter</code><span><a class="mark" href="#all_events_class-eventseventemitterasyncresource-extends-eventemitter" id="all_events_class-eventseventemitterasyncresource-extends-eventemitter">#</a></span><a aria-hidden="true" class="legacy" id="events_class_events_eventemitterasyncresource_extends_eventemitter"></a></h3>
<div class="api_metadata">
<span>Added in: v17.4.0, v16.14.0</span>
</div>
<p>Integrates <code>EventEmitter</code> with <a href="#all_async_hooks_class-asyncresource" class="type">&#x3C;AsyncResource></a> for <code>EventEmitter</code>s that
require manual async tracking. Specifically, all events emitted by instances
of <code>events.EventEmitterAsyncResource</code> will run within its <a href="async_context.html">async context</a>.</p>

<pre class="with-75-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">EventEmitterAsyncResource</span>, <span class="hljs-title class_">EventEmitter</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">import</span> { notStrictEqual, strictEqual } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> { executionAsyncId, triggerAsyncId } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:async_hooks'</span>;

<span class="hljs-comment">// Async tracking tooling will identify this as 'Q'.</span>
<span class="hljs-keyword">const</span> ee1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitterAsyncResource</span>({ <span class="hljs-attr">name</span>: <span class="hljs-string">'Q'</span> });

<span class="hljs-comment">// 'foo' listeners will run in the EventEmitters async context.</span>
ee1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-title function_">strictEqual</span>(<span class="hljs-title function_">executionAsyncId</span>(), ee1.<span class="hljs-property">asyncId</span>);
  <span class="hljs-title function_">strictEqual</span>(<span class="hljs-title function_">triggerAsyncId</span>(), ee1.<span class="hljs-property">triggerAsyncId</span>);
});

<span class="hljs-keyword">const</span> ee2 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();

<span class="hljs-comment">// 'foo' listeners on ordinary EventEmitters that do not track async</span>
<span class="hljs-comment">// context, however, run in the same async context as the emit().</span>
ee2.<span class="hljs-title function_">on</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-title function_">notStrictEqual</span>(<span class="hljs-title function_">executionAsyncId</span>(), ee2.<span class="hljs-property">asyncId</span>);
  <span class="hljs-title function_">notStrictEqual</span>(<span class="hljs-title function_">triggerAsyncId</span>(), ee2.<span class="hljs-property">triggerAsyncId</span>);
});

<span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">resolve</span>().<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> {
  ee1.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>);
  ee2.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">EventEmitterAsyncResource</span>, <span class="hljs-title class_">EventEmitter</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">const</span> { notStrictEqual, strictEqual } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { executionAsyncId, triggerAsyncId } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);

<span class="hljs-comment">// Async tracking tooling will identify this as 'Q'.</span>
<span class="hljs-keyword">const</span> ee1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitterAsyncResource</span>({ <span class="hljs-attr">name</span>: <span class="hljs-string">'Q'</span> });

<span class="hljs-comment">// 'foo' listeners will run in the EventEmitters async context.</span>
ee1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-title function_">strictEqual</span>(<span class="hljs-title function_">executionAsyncId</span>(), ee1.<span class="hljs-property">asyncId</span>);
  <span class="hljs-title function_">strictEqual</span>(<span class="hljs-title function_">triggerAsyncId</span>(), ee1.<span class="hljs-property">triggerAsyncId</span>);
});

<span class="hljs-keyword">const</span> ee2 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();

<span class="hljs-comment">// 'foo' listeners on ordinary EventEmitters that do not track async</span>
<span class="hljs-comment">// context, however, run in the same async context as the emit().</span>
ee2.<span class="hljs-title function_">on</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-title function_">notStrictEqual</span>(<span class="hljs-title function_">executionAsyncId</span>(), ee2.<span class="hljs-property">asyncId</span>);
  <span class="hljs-title function_">notStrictEqual</span>(<span class="hljs-title function_">triggerAsyncId</span>(), ee2.<span class="hljs-property">triggerAsyncId</span>);
});

<span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">resolve</span>().<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> {
  ee1.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>);
  ee2.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'foo'</span>);
});</code><button class="copy-button">copy</button></pre>
<p>The <code>EventEmitterAsyncResource</code> class has the same methods and takes the
same options as <code>EventEmitter</code> and <code>AsyncResource</code> themselves.</p>
<h4><code>new events.EventEmitterAsyncResource([options])</code><span><a class="mark" href="#all_events_new-eventseventemitterasyncresourceoptions" id="all_events_new-eventseventemitterasyncresourceoptions">#</a></span><a aria-hidden="true" class="legacy" id="events_new_events_eventemitterasyncresource_options"></a></h4>
<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>
<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="#all_events_capture-rejections-of-promises">automatic capturing of promise rejection</a>.
<strong>Default:</strong> <code>false</code>.</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 type of async event. <strong>Default:</strong> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new.target"><code>new.target.name</code></a>.</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 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>
<h4><code>eventemitterasyncresource.asyncId</code><span><a class="mark" href="#all_events_eventemitterasyncresourceasyncid" id="all_events_eventemitterasyncresourceasyncid">#</a></span><a aria-hidden="true" class="legacy" id="events_eventemitterasyncresource_asyncid"></a></h4>
<ul>
<li>Type: <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>eventemitterasyncresource.asyncResource</code><span><a class="mark" href="#all_events_eventemitterasyncresourceasyncresource" id="all_events_eventemitterasyncresourceasyncresource">#</a></span><a aria-hidden="true" class="legacy" id="events_eventemitterasyncresource_asyncresource"></a></h4>
<ul>
<li>Type: The underlying <a href="#all_async_hooks_class-asyncresource" class="type">&#x3C;AsyncResource></a>.</li>
</ul>
<p>The returned <code>AsyncResource</code> object has an additional <code>eventEmitter</code> property
that provides a reference to this <code>EventEmitterAsyncResource</code>.</p>
<h4><code>eventemitterasyncresource.emitDestroy()</code><span><a class="mark" href="#all_events_eventemitterasyncresourceemitdestroy" id="all_events_eventemitterasyncresourceemitdestroy">#</a></span><a aria-hidden="true" class="legacy" id="events_eventemitterasyncresource_emitdestroy"></a></h4>
<p>Call all <code>destroy</code> hooks. This should only ever be called once. An error will
be thrown if it is called more than once. This <strong>must</strong> be manually called. If
the resource is left to be collected by the GC then the <code>destroy</code> hooks will
never be called.</p>
<h4><code>eventemitterasyncresource.triggerAsyncId</code><span><a class="mark" href="#all_events_eventemitterasyncresourcetriggerasyncid" id="all_events_eventemitterasyncresourcetriggerasyncid">#</a></span><a aria-hidden="true" class="legacy" id="events_eventemitterasyncresource_triggerasyncid"></a></h4>
<ul>
<li>Type: <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="event-target-and-event-api"></a></p>
</section><section><h3><code>EventTarget</code> and <code>Event</code> API<span><a class="mark" href="#all_events_eventtarget-and-event-api" id="all_events_eventtarget-and-event-api">#</a></span><a aria-hidden="true" class="legacy" id="events_eventtarget_and_event_api"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0</td>
<td><p>changed EventTarget error handling.</p></td></tr>
<tr><td>v15.4.0</td>
<td><p>No longer experimental.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p>The <code>EventTarget</code> and <code>Event</code> classes are now available as globals.</p></td></tr>
<tr><td>v14.5.0</td>
<td><p><span>Added in: v14.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>The <code>EventTarget</code> and <code>Event</code> objects are a Node.js-specific implementation
of the <a href="https://dom.spec.whatwg.org/#eventtarget"><code>EventTarget</code> Web API</a> that are exposed by some Node.js core APIs.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> target = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventTarget</span>();

target.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-function">(<span class="hljs-params">event</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'foo event happened!'</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4>Node.js <code>EventTarget</code> vs. DOM <code>EventTarget</code><span><a class="mark" href="#all_events_nodejs-eventtarget-vs-dom-eventtarget" id="all_events_nodejs-eventtarget-vs-dom-eventtarget">#</a></span><a aria-hidden="true" class="legacy" id="events_node_js_eventtarget_vs_dom_eventtarget"></a></h4>
<p>There are two key differences between the Node.js <code>EventTarget</code> and the
<a href="https://dom.spec.whatwg.org/#eventtarget"><code>EventTarget</code> Web API</a>:</p>
<ol>
<li>Whereas DOM <code>EventTarget</code> instances <em>may</em> be hierarchical, there is no
concept of hierarchy and event propagation in Node.js. That is, an event
dispatched to an <code>EventTarget</code> does not propagate through a hierarchy of
nested target objects that may each have their own set of handlers for the
event.</li>
<li>In the Node.js <code>EventTarget</code>, if an event listener is an async function
or returns a <code>Promise</code>, and the returned <code>Promise</code> rejects, the rejection
is automatically captured and handled the same way as a listener that
throws synchronously (see <a href="#all_events_eventtarget-error-handling"><code>EventTarget</code> error handling</a> for details).</li>
</ol>
<h4><code>NodeEventTarget</code> vs. <code>EventEmitter</code><span><a class="mark" href="#all_events_nodeeventtarget-vs-eventemitter" id="all_events_nodeeventtarget-vs-eventemitter">#</a></span><a aria-hidden="true" class="legacy" id="events_nodeeventtarget_vs_eventemitter"></a></h4>
<p>The <code>NodeEventTarget</code> object implements a modified subset of the
<code>EventEmitter</code> API that allows it to closely <em>emulate</em> an <code>EventEmitter</code> in
certain situations. A <code>NodeEventTarget</code> is <em>not</em> an instance of <code>EventEmitter</code>
and cannot be used in place of an <code>EventEmitter</code> in most cases.</p>
<ol>
<li>Unlike <code>EventEmitter</code>, any given <code>listener</code> can be registered at most once
per event <code>type</code>. Attempts to register a <code>listener</code> multiple times are
ignored.</li>
<li>The <code>NodeEventTarget</code> does not emulate the full <code>EventEmitter</code> API.
Specifically the <code>prependListener()</code>, <code>prependOnceListener()</code>,
<code>rawListeners()</code>, and <code>errorMonitor</code> APIs are not emulated.
The <code>'newListener'</code> and <code>'removeListener'</code> events will also not be emitted.</li>
<li>The <code>NodeEventTarget</code> does not implement any special default behavior
for events with type <code>'error'</code>.</li>
<li>The <code>NodeEventTarget</code> supports <code>EventListener</code> objects as well as
functions as handlers for all event types.</li>
</ol>
<h4>Event listener<span><a class="mark" href="#all_events_event-listener" id="all_events_event-listener">#</a></span><a aria-hidden="true" class="legacy" id="events_event_listener"></a></h4>
<p>Event listeners registered for an event <code>type</code> may either be JavaScript
functions or objects with a <code>handleEvent</code> property whose value is a function.</p>
<p>In either case, the handler function is invoked with the <code>event</code> argument
passed to the <code>eventTarget.dispatchEvent()</code> function.</p>
<p>Async functions may be used as event listeners. If an async handler function
rejects, the rejection is captured and handled as described in
<a href="#all_events_eventtarget-error-handling"><code>EventTarget</code> error handling</a>.</p>
<p>An error thrown by one handler function does not prevent the other handlers
from being invoked.</p>
<p>The return value of a handler function is ignored.</p>
<p>Handlers are always invoked in the order they were added.</p>
<p>Handler functions may mutate the <code>event</code> object.</p>
<pre><code class="language-js"><span class="hljs-keyword">function</span> <span class="hljs-title function_">handler1</span>(<span class="hljs-params">event</span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(event.<span class="hljs-property">type</span>);  <span class="hljs-comment">// Prints 'foo'</span>
  event.<span class="hljs-property">a</span> = <span class="hljs-number">1</span>;
}

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">handler2</span>(<span class="hljs-params">event</span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(event.<span class="hljs-property">type</span>);  <span class="hljs-comment">// Prints 'foo'</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(event.<span class="hljs-property">a</span>);  <span class="hljs-comment">// Prints 1</span>
}

<span class="hljs-keyword">const</span> handler3 = {
  <span class="hljs-title function_">handleEvent</span>(<span class="hljs-params">event</span>) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(event.<span class="hljs-property">type</span>);  <span class="hljs-comment">// Prints 'foo'</span>
  },
};

<span class="hljs-keyword">const</span> handler4 = {
  <span class="hljs-keyword">async</span> <span class="hljs-title function_">handleEvent</span>(<span class="hljs-params">event</span>) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(event.<span class="hljs-property">type</span>);  <span class="hljs-comment">// Prints 'foo'</span>
  },
};

<span class="hljs-keyword">const</span> target = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventTarget</span>();

target.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">'foo'</span>, handler1);
target.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">'foo'</span>, handler2);
target.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">'foo'</span>, handler3);
target.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">'foo'</span>, handler4, { <span class="hljs-attr">once</span>: <span class="hljs-literal">true</span> });</code> <button class="copy-button">copy</button></pre>
<h4><code>EventTarget</code> error handling<span><a class="mark" href="#all_events_eventtarget-error-handling" id="all_events_eventtarget-error-handling">#</a></span><a aria-hidden="true" class="legacy" id="events_eventtarget_error_handling"></a></h4>
<p>When a registered event listener throws (or returns a Promise that rejects),
by default the error is treated as an uncaught exception on
<code>process.nextTick()</code>. This means uncaught exceptions in <code>EventTarget</code>s will
terminate the Node.js process by default.</p>
<p>Throwing within an event listener will <em>not</em> stop the other registered handlers
from being invoked.</p>
<p>The <code>EventTarget</code> does not implement any special default handling for <code>'error'</code>
type events like <code>EventEmitter</code>.</p>
<p>Currently errors are first forwarded to the <code>process.on('error')</code> event
before reaching <code>process.on('uncaughtException')</code>. This behavior is
deprecated and will change in a future release to align <code>EventTarget</code> with
other Node.js APIs. Any code relying on the <code>process.on('error')</code> event should
be aligned with the new behavior.</p>
<h4>Class: <code>Event</code><span><a class="mark" href="#all_events_class-event" id="all_events_class-event">#</a></span><a aria-hidden="true" class="legacy" id="events_class_event"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>The <code>Event</code> class is now available through the global object.</p></td></tr>
<tr><td>v14.5.0</td>
<td><p><span>Added in: v14.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>The <code>Event</code> object is an adaptation of the <a href="https://dom.spec.whatwg.org/#event"><code>Event</code> Web API</a>. Instances
are created internally by Node.js.</p>
<h5><code>event.bubbles</code><span><a class="mark" href="#all_events_eventbubbles" id="all_events_eventbubbles">#</a></span><a aria-hidden="true" class="legacy" id="events_event_bubbles"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Always returns <code>false</code>.</li>
</ul>
<p>This is not used in Node.js and is provided purely for completeness.</p>
<h5><code>event.cancelBubble</code><span><a class="mark" href="#all_events_eventcancelbubble" id="all_events_eventcancelbubble">#</a></span><a aria-hidden="true" class="legacy" id="events_event_cancelbubble"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy: Use <a href="#all_events_eventstoppropagation"><code>event.stopPropagation()</code></a> instead.</div><p></p>
<ul>
<li>Type: <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 <code>event.stopPropagation()</code> if set to <code>true</code>. This is not used
in Node.js and is provided purely for completeness.</p>
<h5><code>event.cancelable</code><span><a class="mark" href="#all_events_eventcancelable" id="all_events_eventcancelable">#</a></span><a aria-hidden="true" class="legacy" id="events_event_cancelable"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> True if the event was created with the <code>cancelable</code> option.</li>
</ul>
<h5><code>event.composed</code><span><a class="mark" href="#all_events_eventcomposed" id="all_events_eventcomposed">#</a></span><a aria-hidden="true" class="legacy" id="events_event_composed"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Always returns <code>false</code>.</li>
</ul>
<p>This is not used in Node.js and is provided purely for completeness.</p>
<h5><code>event.composedPath()</code><span><a class="mark" href="#all_events_eventcomposedpath" id="all_events_eventcomposedpath">#</a></span><a aria-hidden="true" class="legacy" id="events_event_composedpath"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<p>Returns an array containing the current <code>EventTarget</code> as the only entry or
empty if the event is not being dispatched. This is not used in
Node.js and is provided purely for completeness.</p>
<h5><code>event.currentTarget</code><span><a class="mark" href="#all_events_eventcurrenttarget" id="all_events_eventcurrenttarget">#</a></span><a aria-hidden="true" class="legacy" id="events_event_currenttarget"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li>Type: <a href="#all_events_class-eventtarget" class="type">&#x3C;EventTarget></a> The <code>EventTarget</code> dispatching the event.</li>
</ul>
<p>Alias for <code>event.target</code>.</p>
<h5><code>event.defaultPrevented</code><span><a class="mark" href="#all_events_eventdefaultprevented" id="all_events_eventdefaultprevented">#</a></span><a aria-hidden="true" class="legacy" id="events_event_defaultprevented"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li>Type: <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 <code>cancelable</code> is <code>true</code> and <code>event.preventDefault()</code> has been
called.</p>
<h5><code>event.eventPhase</code><span><a class="mark" href="#all_events_eventeventphase" id="all_events_eventeventphase">#</a></span><a aria-hidden="true" class="legacy" id="events_event_eventphase"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Returns <code>0</code> while an event is not being dispatched, <code>2</code> while
it is being dispatched.</li>
</ul>
<p>This is not used in Node.js and is provided purely for completeness.</p>
<h5><code>event.initEvent(type[, bubbles[, cancelable]])</code><span><a class="mark" href="#all_events_eventiniteventtype-bubbles-cancelable" id="all_events_eventiniteventtype-bubbles-cancelable">#</a></span><a aria-hidden="true" class="legacy" id="events_event_initevent_type_bubbles_cancelable"></a></h5>
<div class="api_metadata">
<span>Added in: v19.5.0</span>
</div>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy: The WHATWG spec considers it deprecated and users
shouldn't use it at all.</div><p></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></li>
<li><code>bubbles</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
<li><code>cancelable</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>Redundant with event constructors and incapable of setting <code>composed</code>.
This is not used in Node.js and is provided purely for completeness.</p>
<h5><code>event.isTrusted</code><span><a class="mark" href="#all_events_eventistrusted" id="all_events_eventistrusted">#</a></span><a aria-hidden="true" class="legacy" id="events_event_istrusted"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>The <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> <code>"abort"</code> event is emitted with <code>isTrusted</code> set to <code>true</code>. The
value is <code>false</code> in all other cases.</p>
<h5><code>event.preventDefault()</code><span><a class="mark" href="#all_events_eventpreventdefault" id="all_events_eventpreventdefault">#</a></span><a aria-hidden="true" class="legacy" id="events_event_preventdefault"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<p>Sets the <code>defaultPrevented</code> property to <code>true</code> if <code>cancelable</code> is <code>true</code>.</p>
<h5><code>event.returnValue</code><span><a class="mark" href="#all_events_eventreturnvalue" id="all_events_eventreturnvalue">#</a></span><a aria-hidden="true" class="legacy" id="events_event_returnvalue"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy: Use <a href="#all_events_eventdefaultprevented"><code>event.defaultPrevented</code></a> instead.</div><p></p>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> True if the event has not been canceled.</li>
</ul>
<p>The value of <code>event.returnValue</code> is always the opposite of <code>event.defaultPrevented</code>.
This is not used in Node.js and is provided purely for completeness.</p>
<h5><code>event.srcElement</code><span><a class="mark" href="#all_events_eventsrcelement" id="all_events_eventsrcelement">#</a></span><a aria-hidden="true" class="legacy" id="events_event_srcelement"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy: Use <a href="#all_events_eventtarget"><code>event.target</code></a> instead.</div><p></p>
<ul>
<li>Type: <a href="#all_events_class-eventtarget" class="type">&#x3C;EventTarget></a> The <code>EventTarget</code> dispatching the event.</li>
</ul>
<p>Alias for <code>event.target</code>.</p>
<h5><code>event.stopImmediatePropagation()</code><span><a class="mark" href="#all_events_eventstopimmediatepropagation" id="all_events_eventstopimmediatepropagation">#</a></span><a aria-hidden="true" class="legacy" id="events_event_stopimmediatepropagation"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<p>Stops the invocation of event listeners after the current one completes.</p>
<h5><code>event.stopPropagation()</code><span><a class="mark" href="#all_events_eventstoppropagation" id="all_events_eventstoppropagation">#</a></span><a aria-hidden="true" class="legacy" id="events_event_stoppropagation"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<p>This is not used in Node.js and is provided purely for completeness.</p>
<h5><code>event.target</code><span><a class="mark" href="#all_events_eventtarget" id="all_events_eventtarget">#</a></span><a aria-hidden="true" class="legacy" id="events_event_target"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li>Type: <a href="#all_events_class-eventtarget" class="type">&#x3C;EventTarget></a> The <code>EventTarget</code> dispatching the event.</li>
</ul>
<h5><code>event.timeStamp</code><span><a class="mark" href="#all_events_eventtimestamp" id="all_events_eventtimestamp">#</a></span><a aria-hidden="true" class="legacy" id="events_event_timestamp"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>The millisecond timestamp when the <code>Event</code> object was created.</p>
<h5><code>event.type</code><span><a class="mark" href="#all_events_eventtype" id="all_events_eventtype">#</a></span><a aria-hidden="true" class="legacy" id="events_event_type"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The event type identifier.</p>
<h4>Class: <code>EventTarget</code><span><a class="mark" href="#all_events_class-eventtarget" id="all_events_class-eventtarget">#</a></span><a aria-hidden="true" class="legacy" id="events_class_eventtarget"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>The <code>EventTarget</code> class is now available through the global object.</p></td></tr>
<tr><td>v14.5.0</td>
<td><p><span>Added in: v14.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<h5><code>eventTarget.addEventListener(type, listener[, options])</code><span><a class="mark" href="#all_events_eventtargetaddeventlistenertype-listener-options" id="all_events_eventtargetaddeventlistenertype-listener-options">#</a></span><a aria-hidden="true" class="legacy" id="events_eventtarget_addeventlistener_type_listener_options"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.4.0</td>
<td><p>add support for <code>signal</code> option.</p></td></tr>
<tr><td>v14.5.0</td>
<td><p><span>Added in: v14.5.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></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> | <a href="#all_events_event-listener" class="type">&#x3C;EventListener></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>
<ul>
<li><code>once</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 listener is automatically removed
when it is first invoked. <strong>Default:</strong> <code>false</code>.</li>
<li><code>passive</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>, serves as a hint that the listener will
not call the <code>Event</code> object's <code>preventDefault()</code> method.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>capture</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Not directly used by Node.js. Added for API
completeness. <strong>Default:</strong> <code>false</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> The listener will be removed when the given
AbortSignal object's <code>abort()</code> method is called.</li>
</ul>
</li>
</ul>
<p>Adds a new handler for the <code>type</code> event. Any given <code>listener</code> is added
only once per <code>type</code> and per <code>capture</code> option value.</p>
<p>If the <code>once</code> option is <code>true</code>, the <code>listener</code> is removed after the
next time a <code>type</code> event is dispatched.</p>
<p>The <code>capture</code> option is not used by Node.js in any functional way other than
tracking registered event listeners per the <code>EventTarget</code> specification.
Specifically, the <code>capture</code> option is used as part of the key when registering
a <code>listener</code>. Any individual <code>listener</code> may be added once with
<code>capture = false</code>, and once with <code>capture = true</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">function</span> <span class="hljs-title function_">handler</span>(<span class="hljs-params">event</span>) {}

<span class="hljs-keyword">const</span> target = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventTarget</span>();
target.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">'foo'</span>, handler, { <span class="hljs-attr">capture</span>: <span class="hljs-literal">true</span> });  <span class="hljs-comment">// first</span>
target.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">'foo'</span>, handler, { <span class="hljs-attr">capture</span>: <span class="hljs-literal">false</span> }); <span class="hljs-comment">// second</span>

<span class="hljs-comment">// Removes the second instance of handler</span>
target.<span class="hljs-title function_">removeEventListener</span>(<span class="hljs-string">'foo'</span>, handler);

<span class="hljs-comment">// Removes the first instance of handler</span>
target.<span class="hljs-title function_">removeEventListener</span>(<span class="hljs-string">'foo'</span>, handler, { <span class="hljs-attr">capture</span>: <span class="hljs-literal">true</span> });</code> <button class="copy-button">copy</button></pre>
<h5><code>eventTarget.dispatchEvent(event)</code><span><a class="mark" href="#all_events_eventtargetdispatcheventevent" id="all_events_eventtargetdispatcheventevent">#</a></span><a aria-hidden="true" class="legacy" id="events_eventtarget_dispatchevent_event"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li><code>event</code> <a href="#all_events_class-event" class="type">&#x3C;Event></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 either event's <code>cancelable</code> attribute value is
false or its <code>preventDefault()</code> method was not invoked, otherwise <code>false</code>.</li>
</ul>
<p>Dispatches the <code>event</code> to the list of handlers for <code>event.type</code>.</p>
<p>The registered event listeners is synchronously invoked in the order they
were registered.</p>
<h5><code>eventTarget.removeEventListener(type, listener[, options])</code><span><a class="mark" href="#all_events_eventtargetremoveeventlistenertype-listener-options" id="all_events_eventtargetremoveeventlistenertype-listener-options">#</a></span><a aria-hidden="true" class="legacy" id="events_eventtarget_removeeventlistener_type_listener_options"></a></h5>
<div class="api_metadata">
<span>Added in: v14.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><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="#all_events_event-listener" class="type">&#x3C;EventListener></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>
<ul>
<li><code>capture</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>Removes the <code>listener</code> from the list of handlers for event <code>type</code>.</p>
<h4>Class: <code>CustomEvent</code><span><a class="mark" href="#all_events_class-customevent" id="all_events_class-customevent">#</a></span><a aria-hidden="true" class="legacy" id="events_class_customevent"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.13.0</td>
<td><p>CustomEvent is now stable.</p></td></tr>
<tr><td>v18.7.0, v16.17.0</td>
<td><p><span>Added in: v18.7.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<ul>
<li>Extends: <a href="#all_events_class-event" class="type">&#x3C;Event></a></li>
</ul>
<p>The <code>CustomEvent</code> object is an adaptation of the <a href="https://dom.spec.whatwg.org/#customevent"><code>CustomEvent</code> Web API</a>.
Instances are created internally by Node.js.</p>
<h5><code>event.detail</code><span><a class="mark" href="#all_events_eventdetail" id="all_events_eventdetail">#</a></span><a aria-hidden="true" class="legacy" id="events_event_detail"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.13.0</td>
<td><p>CustomEvent is now stable.</p></td></tr>
<tr><td>v18.7.0, v16.17.0</td>
<td><p><span>Added in: v18.7.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> Returns custom data passed when initializing.</li>
</ul>
<p>Read-only.</p>
<h4>Class: <code>NodeEventTarget</code><span><a class="mark" href="#all_events_class-nodeeventtarget" id="all_events_class-nodeeventtarget">#</a></span><a aria-hidden="true" class="legacy" id="events_class_nodeeventtarget"></a></h4>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li>Extends: <a href="#all_events_class-eventtarget" class="type">&#x3C;EventTarget></a></li>
</ul>
<p>The <code>NodeEventTarget</code> is a Node.js-specific extension to <code>EventTarget</code>
that emulates a subset of the <code>EventEmitter</code> API.</p>
<h5><code>nodeEventTarget.addListener(type, listener)</code><span><a class="mark" href="#all_events_nodeeventtargetaddlistenertype-listener" id="all_events_nodeeventtargetaddlistenertype-listener">#</a></span><a aria-hidden="true" class="legacy" id="events_nodeeventtarget_addlistener_type_listener"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li>
<p><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></p>
</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="#all_events_event-listener" class="type">&#x3C;EventListener></a></p>
</li>
<li>
<p>Returns: <a href="#all_events_class-eventtarget" class="type">&#x3C;EventTarget></a> this</p>
</li>
</ul>
<p>Node.js-specific extension to the <code>EventTarget</code> class that emulates the
equivalent <code>EventEmitter</code> API. The only difference between <code>addListener()</code> and
<code>addEventListener()</code> is that <code>addListener()</code> will return a reference to the
<code>EventTarget</code>.</p>
<h5><code>nodeEventTarget.emit(type, arg)</code><span><a class="mark" href="#all_events_nodeeventtargetemittype-arg" id="all_events_nodeeventtargetemittype-arg">#</a></span><a aria-hidden="true" class="legacy" id="events_nodeeventtarget_emit_type_arg"></a></h5>
<div class="api_metadata">
<span>Added in: v15.2.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><code>arg</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> <code>true</code> if event listeners registered for the <code>type</code> exist,
otherwise <code>false</code>.</li>
</ul>
<p>Node.js-specific extension to the <code>EventTarget</code> class that dispatches the
<code>arg</code> to the list of handlers for <code>type</code>.</p>
<h5><code>nodeEventTarget.eventNames()</code><span><a class="mark" href="#all_events_nodeeventtargeteventnames" id="all_events_nodeeventtargeteventnames">#</a></span><a aria-hidden="true" class="legacy" id="events_nodeeventtarget_eventnames"></a></h5>
<div class="api_metadata">
<span>Added in: v14.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>Node.js-specific extension to the <code>EventTarget</code> class that returns an array
of event <code>type</code> names for which event listeners are registered.</p>
<h5><code>nodeEventTarget.listenerCount(type)</code><span><a class="mark" href="#all_events_nodeeventtargetlistenercounttype" id="all_events_nodeeventtargetlistenercounttype">#</a></span><a aria-hidden="true" class="legacy" id="events_nodeeventtarget_listenercount_type"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li>
<p><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></p>
</li>
<li>
<p>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></p>
</li>
</ul>
<p>Node.js-specific extension to the <code>EventTarget</code> class that returns the number
of event listeners registered for the <code>type</code>.</p>
<h5><code>nodeEventTarget.setMaxListeners(n)</code><span><a class="mark" href="#all_events_nodeeventtargetsetmaxlistenersn" id="all_events_nodeeventtargetsetmaxlistenersn">#</a></span><a aria-hidden="true" class="legacy" id="events_nodeeventtarget_setmaxlisteners_n"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</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;number></a></li>
</ul>
<p>Node.js-specific extension to the <code>EventTarget</code> class that sets the number
of max event listeners as <code>n</code>.</p>
<h5><code>nodeEventTarget.getMaxListeners()</code><span><a class="mark" href="#all_events_nodeeventtargetgetmaxlisteners" id="all_events_nodeeventtargetgetmaxlisteners">#</a></span><a aria-hidden="true" class="legacy" id="events_nodeeventtarget_getmaxlisteners"></a></h5>
<div class="api_metadata">
<span>Added in: v14.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>Node.js-specific extension to the <code>EventTarget</code> class that returns the number
of max event listeners.</p>
<h5><code>nodeEventTarget.off(type, listener[, options])</code><span><a class="mark" href="#all_events_nodeeventtargetofftype-listener-options" id="all_events_nodeeventtargetofftype-listener-options">#</a></span><a aria-hidden="true" class="legacy" id="events_nodeeventtarget_off_type_listener_options"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li>
<p><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></p>
</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="#all_events_event-listener" class="type">&#x3C;EventListener></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>capture</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
</li>
<li>
<p>Returns: <a href="#all_events_class-eventtarget" class="type">&#x3C;EventTarget></a> this</p>
</li>
</ul>
<p>Node.js-specific alias for <code>eventTarget.removeEventListener()</code>.</p>
<h5><code>nodeEventTarget.on(type, listener)</code><span><a class="mark" href="#all_events_nodeeventtargetontype-listener" id="all_events_nodeeventtargetontype-listener">#</a></span><a aria-hidden="true" class="legacy" id="events_nodeeventtarget_on_type_listener"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li>
<p><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></p>
</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="#all_events_event-listener" class="type">&#x3C;EventListener></a></p>
</li>
<li>
<p>Returns: <a href="#all_events_class-eventtarget" class="type">&#x3C;EventTarget></a> this</p>
</li>
</ul>
<p>Node.js-specific alias for <code>eventTarget.addEventListener()</code>.</p>
<h5><code>nodeEventTarget.once(type, listener)</code><span><a class="mark" href="#all_events_nodeeventtargetoncetype-listener" id="all_events_nodeeventtargetoncetype-listener">#</a></span><a aria-hidden="true" class="legacy" id="events_nodeeventtarget_once_type_listener"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li>
<p><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></p>
</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="#all_events_event-listener" class="type">&#x3C;EventListener></a></p>
</li>
<li>
<p>Returns: <a href="#all_events_class-eventtarget" class="type">&#x3C;EventTarget></a> this</p>
</li>
</ul>
<p>Node.js-specific extension to the <code>EventTarget</code> class that adds a <code>once</code>
listener for the given event <code>type</code>. This is equivalent to calling <code>on</code>
with the <code>once</code> option set to <code>true</code>.</p>
<h5><code>nodeEventTarget.removeAllListeners([type])</code><span><a class="mark" href="#all_events_nodeeventtargetremovealllistenerstype" id="all_events_nodeeventtargetremovealllistenerstype">#</a></span><a aria-hidden="true" class="legacy" id="events_nodeeventtarget_removealllisteners_type"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li>
<p><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></p>
</li>
<li>
<p>Returns: <a href="#all_events_class-eventtarget" class="type">&#x3C;EventTarget></a> this</p>
</li>
</ul>
<p>Node.js-specific extension to the <code>EventTarget</code> class. If <code>type</code> is specified,
removes all registered listeners for <code>type</code>, otherwise removes all registered
listeners.</p>
<h5><code>nodeEventTarget.removeListener(type, listener[, options])</code><span><a class="mark" href="#all_events_nodeeventtargetremovelistenertype-listener-options" id="all_events_nodeeventtargetremovelistenertype-listener-options">#</a></span><a aria-hidden="true" class="legacy" id="events_nodeeventtarget_removelistener_type_listener_options"></a></h5>
<div class="api_metadata">
<span>Added in: v14.5.0</span>
</div>
<ul>
<li>
<p><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></p>
</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="#all_events_event-listener" class="type">&#x3C;EventListener></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>capture</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
</li>
<li>
<p>Returns: <a href="#all_events_class-eventtarget" class="type">&#x3C;EventTarget></a> this</p>
</li>
</ul>
<p>Node.js-specific extension to the <code>EventTarget</code> class that removes the
<code>listener</code> for the given <code>type</code>. The only difference between <code>removeListener()</code>
and <code>removeEventListener()</code> is that <code>removeListener()</code> will return a reference
to the <code>EventTarget</code>.</p></section>
        </section>
<section><h2>File system<span><a class="mark" href="#all_fs_file-system" id="all_fs_file-system">#</a></span><a aria-hidden="true" class="legacy" id="fs_file_system"></a></h2>

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

<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/fs.js">lib/fs.js</a></p>
<p>The <code>node:fs</code> module enables interacting with the file system in a
way modeled on standard POSIX functions.</p>
<p>To use the promise-based APIs:</p>

<pre class="with-39-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs/promises'</span>);</code><button class="copy-button">copy</button></pre>
<p>To use the callback and sync APIs:</p>

<pre class="with-30-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);</code><button class="copy-button">copy</button></pre>
<p>All file system operations have synchronous, callback, and promise-based
forms, and are accessible using both CommonJS syntax and ES6 Modules (ESM).</p>
<section><h3>Promise example<span><a class="mark" href="#all_fs_promise-example" id="all_fs_promise-example">#</a></span><a aria-hidden="true" class="legacy" id="fs_promise_example"></a></h3>
<p>Promise-based operations return a promise that is fulfilled when the
asynchronous operation is complete.</p>

<pre class="with-47-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { unlink } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;

<span class="hljs-keyword">try</span> {
  <span class="hljs-keyword">await</span> <span class="hljs-title function_">unlink</span>(<span class="hljs-string">'/tmp/hello'</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'successfully deleted /tmp/hello'</span>);
} <span class="hljs-keyword">catch</span> (error) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'there was an error:'</span>, error.<span class="hljs-property">message</span>);
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { unlink } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs/promises'</span>);

(<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>(<span class="hljs-params">path</span>) {
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">await</span> <span class="hljs-title function_">unlink</span>(path);
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`successfully deleted <span class="hljs-subst">${path}</span>`</span>);
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'there was an error:'</span>, error.<span class="hljs-property">message</span>);
  }
})(<span class="hljs-string">'/tmp/hello'</span>);</code><button class="copy-button">copy</button></pre>
</section><section><h3>Callback example<span><a class="mark" href="#all_fs_callback-example" id="all_fs_callback-example">#</a></span><a aria-hidden="true" class="legacy" id="fs_callback_example"></a></h3>
<p>The callback form takes a completion callback function as its last
argument and invokes the operation asynchronously. The arguments passed to
the completion callback depend on the method, but the first argument is always
reserved for an exception. If the operation is completed successfully, then
the first argument is <code>null</code> or <code>undefined</code>.</p>

<pre class="with-38-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { unlink } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-title function_">unlink</span>(<span class="hljs-string">'/tmp/hello'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'successfully deleted /tmp/hello'</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { unlink } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);

<span class="hljs-title function_">unlink</span>(<span class="hljs-string">'/tmp/hello'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'successfully deleted /tmp/hello'</span>);
});</code><button class="copy-button">copy</button></pre>
<p>The callback-based versions of the <code>node:fs</code> module APIs are preferable over
the use of the promise APIs when maximal performance (both in terms of
execution time and memory allocation) is required.</p>
</section><section><h3>Synchronous example<span><a class="mark" href="#all_fs_synchronous-example" id="all_fs_synchronous-example">#</a></span><a aria-hidden="true" class="legacy" id="fs_synchronous_example"></a></h3>
<p>The synchronous APIs block the Node.js event loop and further JavaScript
execution until the operation is complete. Exceptions are thrown immediately
and can be handled using <code>try…catch</code>, or can be allowed to bubble up.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { unlinkSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-keyword">try</span> {
  <span class="hljs-title function_">unlinkSync</span>(<span class="hljs-string">'/tmp/hello'</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'successfully deleted /tmp/hello'</span>);
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-comment">// handle the error</span>
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { unlinkSync } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);

<span class="hljs-keyword">try</span> {
  <span class="hljs-title function_">unlinkSync</span>(<span class="hljs-string">'/tmp/hello'</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'successfully deleted /tmp/hello'</span>);
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-comment">// handle the error</span>
}</code><button class="copy-button">copy</button></pre>
</section><section><h3>Promises API<span><a class="mark" href="#all_fs_promises-api" id="all_fs_promises-api">#</a></span><a aria-hidden="true" class="legacy" id="fs_promises_api"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.0.0</td>
<td><p>Exposed as <code>require('fs/promises')</code>.</p></td></tr>
<tr><td>v11.14.0, v10.17.0</td>
<td><p>This API is no longer experimental.</p></td></tr>
<tr><td>v10.1.0</td>
<td><p>The API is accessible via <code>require('fs').promises</code> only.</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>The <code>fs/promises</code> API provides asynchronous file system methods that return
promises.</p>
<p>The promise APIs use the underlying Node.js threadpool to perform file
system operations off the event loop thread. These operations are not
synchronized or threadsafe. Care must be taken when performing multiple
concurrent modifications on the same file or data corruption may occur.</p>
<h4>Class: <code>FileHandle</code><span><a class="mark" href="#all_fs_class-filehandle" id="all_fs_class-filehandle">#</a></span><a aria-hidden="true" class="legacy" id="fs_class_filehandle"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<p>A <a href="#all_fs_class-filehandle" class="type">&#x3C;FileHandle></a> object is an object wrapper for a numeric file descriptor.</p>
<p>Instances of the <a href="#all_fs_class-filehandle" class="type">&#x3C;FileHandle></a> object are created by the <code>fsPromises.open()</code>
method.</p>
<p>All <a href="#all_fs_class-filehandle" class="type">&#x3C;FileHandle></a> objects are <a href="#all_events_class-eventemitter" class="type">&#x3C;EventEmitter></a>s.</p>
<p>If a <a href="#all_fs_class-filehandle" class="type">&#x3C;FileHandle></a> is not closed using the <code>filehandle.close()</code> method, it will
try to automatically close the file descriptor and emit a process warning,
helping to prevent memory leaks. Please do not rely on this behavior because
it can be unreliable and the file may not be closed. Instead, always explicitly
close <a href="#all_fs_class-filehandle" class="type">&#x3C;FileHandle></a>s. Node.js may change this behavior in the future.</p>
<h5>Event: <code>'close'</code><span><a class="mark" href="#all_fs_event-close" id="all_fs_event-close">#</a></span><a aria-hidden="true" class="legacy" id="fs_event_close"></a></h5>
<div class="api_metadata">
<span>Added in: v15.4.0</span>
</div>
<p>The <code>'close'</code> event is emitted when the <a href="#all_fs_class-filehandle" class="type">&#x3C;FileHandle></a> has been closed and can no
longer be used.</p>
<h5><code>filehandle.appendFile(data[, options])</code><span><a class="mark" href="#all_fs_filehandleappendfiledata-options" id="all_fs_filehandleappendfiledata-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_appendfile_data_options"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.10.0</td>
<td><p>The <code>flush</code> option is now supported.</p></td></tr>
<tr><td>v15.14.0, v14.18.0</td>
<td><p>The <code>data</code> argument supports <code>AsyncIterable</code>, <code>Iterable</code>, and <code>Stream</code>.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>The <code>data</code> parameter won't coerce unsupported input to strings anymore.</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>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#all_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://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type">&#x3C;AsyncIterable></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol" class="type">&#x3C;Iterable></a> | <a href="#all_stream_stream" class="type">&#x3C;Stream></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>
<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>flush</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 underlying file descriptor is flushed
prior to closing it. <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> Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>Alias of <a href="#all_fs_filehandlewritefiledata-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="#all_fs_fspromisesopenpath-flags-mode"><code>fsPromises.open()</code></a>. Therefore, this is equivalent to
<a href="#all_fs_filehandlewritefiledata-options"><code>filehandle.writeFile()</code></a>.</p>
<h5><code>filehandle.chmod(mode)</code><span><a class="mark" href="#all_fs_filehandlechmodmode" id="all_fs_filehandlechmodmode">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_chmod_mode"></a></h5>
<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> the file mode bit mask.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>Modifies the permissions on the file. See <a href="http://man7.org/linux/man-pages/man2/chmod.2.html"><code>chmod(2)</code></a>.</p>
<h5><code>filehandle.chown(uid, gid)</code><span><a class="mark" href="#all_fs_filehandlechownuid-gid" id="all_fs_filehandlechownuid-gid">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_chown_uid_gid"></a></h5>
<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> The file's new owner's user id.</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> The file's new group's group id.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>Changes the ownership of the file. A wrapper for <a href="http://man7.org/linux/man-pages/man2/chown.2.html"><code>chown(2)</code></a>.</p>
<h5><code>filehandle.close()</code><span><a class="mark" href="#all_fs_filehandleclose" id="all_fs_filehandleclose">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_close"></a></h5>
<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> Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>Closes the file handle after waiting for any pending operation on the handle to
complete.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { open } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;

<span class="hljs-keyword">let</span> filehandle;
<span class="hljs-keyword">try</span> {
  filehandle = <span class="hljs-keyword">await</span> <span class="hljs-title function_">open</span>(<span class="hljs-string">'thefile.txt'</span>, <span class="hljs-string">'r'</span>);
} <span class="hljs-keyword">finally</span> {
  <span class="hljs-keyword">await</span> filehandle?.<span class="hljs-title function_">close</span>();
}</code> <button class="copy-button">copy</button></pre>
<h5><code>filehandle.createReadStream([options])</code><span><a class="mark" href="#all_fs_filehandlecreatereadstreamoptions" id="all_fs_filehandlecreatereadstreamoptions">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_createreadstream_options"></a></h5>
<div class="api_metadata">
<span>Added in: v16.11.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>
<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>null</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>true</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>
</ul>
</li>
<li>Returns: <a href="#all_fs_class-fsreadstream" class="type">&#x3C;fs.ReadStream></a></li>
</ul>
<p>Unlike the 16 KiB default <code>highWaterMark</code> for a <a href="#all_stream_class-streamreadable" class="type">&#x3C;stream.Readable></a>, the stream
returned by this method has a default <code>highWaterMark</code> of 64 KiB.</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>start</code> is
omitted or <code>undefined</code>, <code>filehandle.createReadStream()</code> reads sequentially from
the current file position. The <code>encoding</code> can be any one of those accepted by
<a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a>.</p>
<p>If the <code>FileHandle</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 emit a <code>'close'</code> event after it has been
destroyed.  Set the <code>emitClose</code> option to <code>false</code> to change this behavior.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { open } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;

<span class="hljs-keyword">const</span> fd = <span class="hljs-keyword">await</span> <span class="hljs-title function_">open</span>(<span class="hljs-string">'/dev/input/event0'</span>);
<span class="hljs-comment">// Create a stream from some character device.</span>
<span class="hljs-keyword">const</span> stream = fd.<span class="hljs-title function_">createReadStream</span>();
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
  stream.<span class="hljs-title function_">close</span>(); <span class="hljs-comment">// This may not close the stream.</span>
  <span class="hljs-comment">// Artificially marking end-of-stream, as if the underlying resource had</span>
  <span class="hljs-comment">// indicated end-of-file by itself, allows the stream to close.</span>
  <span class="hljs-comment">// This does not cancel pending read operations, and if there is such an</span>
  <span class="hljs-comment">// operation, the process may still not be able to exit successfully</span>
  <span class="hljs-comment">// until it finishes.</span>
  stream.<span class="hljs-title function_">push</span>(<span class="hljs-literal">null</span>);
  stream.<span class="hljs-title function_">read</span>(<span class="hljs-number">0</span>);
}, <span class="hljs-number">100</span>);</code> <button class="copy-button">copy</button></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>An example to read the last 10 bytes of a file which is 100 bytes long:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { open } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;

<span class="hljs-keyword">const</span> fd = <span class="hljs-keyword">await</span> <span class="hljs-title function_">open</span>(<span class="hljs-string">'sample.txt'</span>);
fd.<span class="hljs-title function_">createReadStream</span>({ <span class="hljs-attr">start</span>: <span class="hljs-number">90</span>, <span class="hljs-attr">end</span>: <span class="hljs-number">99</span> });</code> <button class="copy-button">copy</button></pre>
<h5><code>filehandle.createWriteStream([options])</code><span><a class="mark" href="#all_fs_filehandlecreatewritestreamoptions" id="all_fs_filehandlecreatewritestreamoptions">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_createwritestream_options"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.10.0</td>
<td><p>The <code>flush</code> option is now supported.</p></td></tr>
<tr><td>v16.11.0</td>
<td><p><span>Added in: v16.11.0</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>
<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>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>true</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>highWaterMark</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>16384</code></li>
<li><code>flush</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 underlying file descriptor is flushed
prior to closing it. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>Returns: <a href="#all_fs_class-fswritestream" class="type">&#x3C;fs.WriteStream></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 the <code>flags</code> <code>open</code> option to be set to <code>r+</code> rather than
the default <code>r</code>. The <code>encoding</code> can be any one of those accepted by <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></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 emit a <code>'close'</code> event after it has been
destroyed.  Set the <code>emitClose</code> option to <code>false</code> to change this behavior.</p>
<h5><code>filehandle.datasync()</code><span><a class="mark" href="#all_fs_filehandledatasync" id="all_fs_filehandledatasync">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_datasync"></a></h5>
<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> Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>Forces all currently queued I/O operations associated with the file to the
operating system's synchronized I/O completion state. Refer to the POSIX
<a href="http://man7.org/linux/man-pages/man2/fdatasync.2.html"><code>fdatasync(2)</code></a> documentation for details.</p>
<p>Unlike <code>filehandle.sync</code> this method does not flush modified metadata.</p>
<h5><code>filehandle.fd</code><span><a class="mark" href="#all_fs_filehandlefd" id="all_fs_filehandlefd">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_fd"></a></h5>
<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 <a href="#all_fs_class-filehandle" class="type">&#x3C;FileHandle></a> object.</li>
</ul>
<h5><code>filehandle.read(buffer, offset, length, position)</code><span><a class="mark" href="#all_fs_filehandlereadbuffer-offset-length-position" id="all_fs_filehandlereadbuffer-offset-length-position">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_read_buffer_offset_length_position"></a></h5>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>buffer</code> <a href="#all_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 that will be filled with the
file data read.</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> The location in the buffer at which to start filling.
<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> The number of bytes to read. <strong>Default:</strong>
<code>buffer.byteLength - offset</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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type">&#x3C;bigint></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a> The location where to begin reading data
from the file. If <code>null</code> or <code>-1</code>, data will be read from the current file
position, and the position will be updated. If <code>position</code> is a non-negative
integer, the current file position will remain unchanged.
<strong>Default:</strong>: <code>null</code></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> Fulfills upon success with an object with two properties:
<ul>
<li><code>bytesRead</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> The number of bytes read</li>
<li><code>buffer</code> <a href="#all_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 reference to the passed in <code>buffer</code>
argument.</li>
</ul>
</li>
</ul>
<p>Reads data from the file and stores that in the given buffer.</p>
<p>If the file is not modified concurrently, the end-of-file is reached when the
number of bytes read is zero.</p>
<h5><code>filehandle.read([options])</code><span><a class="mark" href="#all_fs_filehandlereadoptions" id="all_fs_filehandlereadoptions">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_read_options"></a></h5>
<div class="api_metadata">
<span>Added in: v13.11.0, v12.17.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>
<ul>
<li><code>buffer</code> <a href="#all_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 that will be filled with the
file data read. <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> The location in the buffer at which to start filling.
<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> The number of bytes to read. <strong>Default:</strong>
<code>buffer.byteLength - offset</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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a> The location where to begin reading data from the
file. If <code>null</code>, data will be read from the current file position, and
the position will be updated. If <code>position</code> is an integer, the current
file position will remain unchanged. <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> Fulfills upon success with an object with two properties:
<ul>
<li><code>bytesRead</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> The number of bytes read</li>
<li><code>buffer</code> <a href="#all_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 reference to the passed in <code>buffer</code>
argument.</li>
</ul>
</li>
</ul>
<p>Reads data from the file and stores that in the given buffer.</p>
<p>If the file is not modified concurrently, the end-of-file is reached when the
number of bytes read is zero.</p>
<h5><code>filehandle.read(buffer[, options])</code><span><a class="mark" href="#all_fs_filehandlereadbuffer-options" id="all_fs_filehandlereadbuffer-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_read_buffer_options"></a></h5>
<div class="api_metadata">
<span>Added in: v18.2.0, v16.17.0</span>
</div>
<ul>
<li><code>buffer</code> <a href="#all_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 that will be filled with the
file data read.</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>
<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> The location in the buffer at which to start filling.
<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> The number of bytes to read. <strong>Default:</strong>
<code>buffer.byteLength - offset</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> The location where to begin reading data from the
file. If <code>null</code>, data will be read from the current file position, and
the position will be updated. If <code>position</code> is an integer, the current
file position will remain unchanged. <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> Fulfills upon success with an object with two properties:
<ul>
<li><code>bytesRead</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> The number of bytes read</li>
<li><code>buffer</code> <a href="#all_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 reference to the passed in <code>buffer</code>
argument.</li>
</ul>
</li>
</ul>
<p>Reads data from the file and stores that in the given buffer.</p>
<p>If the file is not modified concurrently, the end-of-file is reached when the
number of bytes read is zero.</p>
<h5><code>filehandle.readableWebStream([options])</code><span><a class="mark" href="#all_fs_filehandlereadablewebstreamoptions" id="all_fs_filehandlereadablewebstreamoptions">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_readablewebstream_options"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>Added option to create a 'bytes' stream.</p></td></tr>
<tr><td>v17.0.0</td>
<td><p><span>Added in: v17.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></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>type</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#Undefined_type" class="type">&#x3C;undefined></a> Whether to open a normal or a <code>'bytes'</code> stream.
<strong>Default:</strong> <code>undefined</code></li>
</ul>
</li>
<li>
<p>Returns: <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a></p>
</li>
</ul>
<p>Returns a <code>ReadableStream</code> that may be used to read the files data.</p>
<p>An error will be thrown if this method is called more than once or is called
after the <code>FileHandle</code> is closed or closing.</p>

<pre class="with-8-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> {
  open,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;

<span class="hljs-keyword">const</span> file = <span class="hljs-keyword">await</span> <span class="hljs-title function_">open</span>(<span class="hljs-string">'./some/file/to/read'</span>);

<span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> file.<span class="hljs-title function_">readableWebStream</span>())
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk);

<span class="hljs-keyword">await</span> file.<span class="hljs-title function_">close</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
  open,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs/promises'</span>);

(<span class="hljs-keyword">async</span> () => {
  <span class="hljs-keyword">const</span> file = <span class="hljs-keyword">await</span> <span class="hljs-title function_">open</span>(<span class="hljs-string">'./some/file/to/read'</span>);

  <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> file.<span class="hljs-title function_">readableWebStream</span>())
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk);

  <span class="hljs-keyword">await</span> file.<span class="hljs-title function_">close</span>();
})();</code><button class="copy-button">copy</button></pre>
<p>While the <code>ReadableStream</code> will read the file to completion, it will not
close the <code>FileHandle</code> automatically. User code must still call the
<code>fileHandle.close()</code> method.</p>
<h5><code>filehandle.readFile(options)</code><span><a class="mark" href="#all_fs_filehandlereadfileoptions" id="all_fs_filehandlereadfileoptions">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_readfile_options"></a></h5>
<div class="api_metadata">
<span>Added in: v10.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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a>
<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>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> allows aborting an in-progress readFile</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> Fulfills upon a successful read with the contents of the
file. If no encoding is specified (using <code>options.encoding</code>), the data is
returned as a <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> object. Otherwise, the data will be a string.</li>
</ul>
<p>Asynchronously reads the entire contents of a file.</p>
<p>If <code>options</code> is a string, then it specifies the <code>encoding</code>.</p>
<p>The <a href="#all_fs_class-filehandle" class="type">&#x3C;FileHandle></a> 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>
<h5><code>filehandle.readLines([options])</code><span><a class="mark" href="#all_fs_filehandlereadlinesoptions" id="all_fs_filehandlereadlinesoptions">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_readlines_options"></a></h5>
<div class="api_metadata">
<span>Added in: v18.11.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>
<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>null</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>true</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>
</ul>
</li>
<li>Returns: <a href="#all_readline_class-interfaceconstructor" class="type">&#x3C;readline.InterfaceConstructor></a></li>
</ul>
<p>Convenience method to create a <code>readline</code> interface and stream over the file.
See <a href="#all_fs_filehandlecreatereadstreamoptions"><code>filehandle.createReadStream()</code></a> for the options.</p>

<pre class="with-45-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { open } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;

<span class="hljs-keyword">const</span> file = <span class="hljs-keyword">await</span> <span class="hljs-title function_">open</span>(<span class="hljs-string">'./some/file/to/read'</span>);

<span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> line <span class="hljs-keyword">of</span> file.<span class="hljs-title function_">readLines</span>()) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(line);
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { open } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs/promises'</span>);

(<span class="hljs-keyword">async</span> () => {
  <span class="hljs-keyword">const</span> file = <span class="hljs-keyword">await</span> <span class="hljs-title function_">open</span>(<span class="hljs-string">'./some/file/to/read'</span>);

  <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> line <span class="hljs-keyword">of</span> file.<span class="hljs-title function_">readLines</span>()) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(line);
  }
})();</code><button class="copy-button">copy</button></pre>
<h5><code>filehandle.readv(buffers[, position])</code><span><a class="mark" href="#all_fs_filehandlereadvbuffers-position" id="all_fs_filehandlereadvbuffers-position">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_readv_buffers_position"></a></h5>
<div class="api_metadata">
<span>Added in: v13.13.0, v12.17.0</span>
</div>
<ul>
<li><code>buffers</code> <a href="#all_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>position</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#Null_type" class="type">&#x3C;null></a> The offset from the beginning of the file where
the data should be read from. If <code>position</code> is not a <code>number</code>, the data will
be read from the current position. <strong>Default:</strong> <code>null</code></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> Fulfills upon success an object containing two properties:
<ul>
<li><code>bytesRead</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> the number of bytes read</li>
<li><code>buffers</code> <a href="#all_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> property containing
a reference to the <code>buffers</code> input.</li>
</ul>
</li>
</ul>
<p>Read from a file and write to an array of <a href="https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView" class="type">&#x3C;ArrayBufferView></a>s</p>
<h5><code>filehandle.stat([options])</code><span><a class="mark" href="#all_fs_filehandlestatoptions" id="all_fs_filehandlestatoptions">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_stat_options"></a></h5>
<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>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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="#all_fs_class-fsstats" class="type">&#x3C;fs.Stats></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> Fulfills with an <a href="#all_fs_class-fsstats" class="type">&#x3C;fs.Stats></a> for the file.</li>
</ul>
<h5><code>filehandle.sync()</code><span><a class="mark" href="#all_fs_filehandlesync" id="all_fs_filehandlesync">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_sync"></a></h5>
<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> Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>Request that all data for the open file descriptor is flushed to the storage
device. The specific implementation is operating system and device specific.
Refer to the POSIX <a href="http://man7.org/linux/man-pages/man2/fsync.2.html"><code>fsync(2)</code></a> documentation for more detail.</p>
<h5><code>filehandle.truncate(len)</code><span><a class="mark" href="#all_fs_filehandletruncatelen" id="all_fs_filehandletruncatelen">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_truncate_len"></a></h5>
<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> Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>Truncates the file.</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>The following example retains only the first four bytes of the file:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { open } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;

<span class="hljs-keyword">let</span> filehandle = <span class="hljs-literal">null</span>;
<span class="hljs-keyword">try</span> {
  filehandle = <span class="hljs-keyword">await</span> <span class="hljs-title function_">open</span>(<span class="hljs-string">'temp.txt'</span>, <span class="hljs-string">'r+'</span>);
  <span class="hljs-keyword">await</span> filehandle.<span class="hljs-title function_">truncate</span>(<span class="hljs-number">4</span>);
} <span class="hljs-keyword">finally</span> {
  <span class="hljs-keyword">await</span> filehandle?.<span class="hljs-title function_">close</span>();
}</code> <button class="copy-button">copy</button></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>
<p>If <code>len</code> is negative then <code>0</code> will be used.</p>
<h5><code>filehandle.utimes(atime, mtime)</code><span><a class="mark" href="#all_fs_filehandleutimesatime-mtime" id="all_fs_filehandleutimesatime-mtime">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_utimes_atime_mtime"></a></h5>
<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 <a href="#all_fs_class-filehandle" class="type">&#x3C;FileHandle></a>
then fulfills the promise with no arguments upon success.</p>
<h5><code>filehandle.write(buffer, offset[, length[, position]])</code><span><a class="mark" href="#all_fs_filehandlewritebuffer-offset-length-position" id="all_fs_filehandlewritebuffer-offset-length-position">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_write_buffer_offset_length_position"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.0.0</td>
<td><p>The <code>buffer</code> parameter won't coerce unsupported input to buffers anymore.</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>buffer</code> <a href="#all_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> The start position from within <code>buffer</code> where the data
to write begins.</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> The number of bytes from <code>buffer</code> to write. <strong>Default:</strong>
<code>buffer.byteLength - offset</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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a> The offset from the beginning of the file where the
data from <code>buffer</code> should be written. If <code>position</code> is not a <code>number</code>,
the data will be written at the current position. See the POSIX <a href="http://man7.org/linux/man-pages/man2/pwrite.2.html"><code>pwrite(2)</code></a>
documentation for more detail. <strong>Default:</strong> <code>null</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>buffer</code> to the file.</p>
<p>The promise is fulfilled with an object containing two properties:</p>
<ul>
<li><code>bytesWritten</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> the number of bytes written</li>
<li><code>buffer</code> <a href="#all_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 reference to the
<code>buffer</code> written.</li>
</ul>
<p>It is unsafe to use <code>filehandle.write()</code> multiple times on the same file
without waiting for the promise to be fulfilled (or rejected). For this
scenario, use <a href="#all_fs_filehandlecreatewritestreamoptions"><code>filehandle.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>
<h5><code>filehandle.write(buffer[, options])</code><span><a class="mark" href="#all_fs_filehandlewritebuffer-options" id="all_fs_filehandlewritebuffer-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_write_buffer_options"></a></h5>
<div class="api_metadata">
<span>Added in: v18.3.0, v16.17.0</span>
</div>
<ul>
<li><code>buffer</code> <a href="#all_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>
<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.byteLength - offset</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>
<p>Write <code>buffer</code> to the file.</p>
<p>Similar to the above <code>filehandle.write</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>
<h5><code>filehandle.write(string[, position[, encoding]])</code><span><a class="mark" href="#all_fs_filehandlewritestring-position-encoding" id="all_fs_filehandlewritestring-position-encoding">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_write_string_position_encoding"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.0.0</td>
<td><p>The <code>string</code> parameter won't coerce unsupported input to strings anymore.</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>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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a> The offset from the beginning of the file where the
data from <code>string</code> should be written. If <code>position</code> is not a <code>number</code> the
data will be written at the current position. See the POSIX <a href="http://man7.org/linux/man-pages/man2/pwrite.2.html"><code>pwrite(2)</code></a>
documentation for more detail. <strong>Default:</strong> <code>null</code></li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The expected string encoding. <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, the promise is
rejected with an error.</p>
<p>The promise is fulfilled with an object containing two properties:</p>
<ul>
<li><code>bytesWritten</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> the number of bytes written</li>
<li><code>buffer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> a reference to the <code>string</code> written.</li>
</ul>
<p>It is unsafe to use <code>filehandle.write()</code> multiple times on the same file
without waiting for the promise to be fulfilled (or rejected). For this
scenario, use <a href="#all_fs_filehandlecreatewritestreamoptions"><code>filehandle.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>
<h5><code>filehandle.writeFile(data, options)</code><span><a class="mark" href="#all_fs_filehandlewritefiledata-options" id="all_fs_filehandlewritefiledata-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_writefile_data_options"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.14.0, v14.18.0</td>
<td><p>The <code>data</code> argument supports <code>AsyncIterable</code>, <code>Iterable</code>, and <code>Stream</code>.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>The <code>data</code> parameter won't coerce unsupported input to strings anymore.</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>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#all_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://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type">&#x3C;AsyncIterable></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol" class="type">&#x3C;Iterable></a> | <a href="#all_stream_stream" class="type">&#x3C;Stream></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>
<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> The expected character encoding when <code>data</code> is a
string. <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, a buffer, an <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type">&#x3C;AsyncIterable></a>, or an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol" class="type">&#x3C;Iterable></a> object.
The promise is fulfilled with no arguments upon success.</p>
<p>If <code>options</code> is a string, then it specifies the <code>encoding</code>.</p>
<p>The <a href="#all_fs_class-filehandle" class="type">&#x3C;FileHandle></a> 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 promise to be fulfilled (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>
<h5><code>filehandle.writev(buffers[, position])</code><span><a class="mark" href="#all_fs_filehandlewritevbuffers-position" id="all_fs_filehandlewritevbuffers-position">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_writev_buffers_position"></a></h5>
<div class="api_metadata">
<span>Added in: v12.9.0</span>
</div>
<ul>
<li><code>buffers</code> <a href="#all_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>position</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#Null_type" class="type">&#x3C;null></a> The offset from the beginning of the file where the
data from <code>buffers</code> should be written. If <code>position</code> is not a <code>number</code>,
the data will be written at the current position. <strong>Default:</strong> <code>null</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 an array of <a href="https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView" class="type">&#x3C;ArrayBufferView></a>s to the file.</p>
<p>The promise is fulfilled with an object containing a two properties:</p>
<ul>
<li><code>bytesWritten</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> the number of bytes written</li>
<li><code>buffers</code> <a href="#all_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 reference to the <code>buffers</code>
input.</li>
</ul>
<p>It is unsafe to call <code>writev()</code> multiple times on the same file without waiting
for the promise to be fulfilled (or rejected).</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>
<h5><code>filehandle[Symbol.asyncDispose]()</code><span><a class="mark" href="#all_fs_filehandlesymbolasyncdispose" id="all_fs_filehandlesymbolasyncdispose">#</a></span><a aria-hidden="true" class="legacy" id="fs_filehandle_symbol_asyncdispose"></a></h5>
<div class="api_metadata">
<span>Added in: v20.4.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>An alias for <code>filehandle.close()</code>.</p>
<h4><code>fsPromises.access(path[, mode])</code><span><a class="mark" href="#all_fs_fspromisesaccesspath-mode" id="all_fs_fspromisesaccesspath-mode">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_access_path_mode"></a></h4>
<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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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> Fulfills with <code>undefined</code> upon success.</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. <code>mode</code> should be either the value <code>fs.constants.F_OK</code>
or a mask consisting of the bitwise OR of any of <code>fs.constants.R_OK</code>,
<code>fs.constants.W_OK</code>, and <code>fs.constants.X_OK</code> (e.g.
<code>fs.constants.W_OK | fs.constants.R_OK</code>). Check <a href="#all_fs_file-access-constants">File access constants</a> for
possible values of <code>mode</code>.</p>
<p>If the accessibility check is successful, the promise is fulfilled with no
value. If any of the accessibility checks fail, the promise is rejected
with an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a> 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 mjs"><span class="hljs-keyword">import</span> { access, constants } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;

<span class="hljs-keyword">try</span> {
  <span class="hljs-keyword">await</span> <span class="hljs-title function_">access</span>(<span class="hljs-string">'/etc/passwd'</span>, constants.<span class="hljs-property">R_OK</span> | constants.<span class="hljs-property">W_OK</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'can access'</span>);
} <span class="hljs-keyword">catch</span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'cannot access'</span>);
}</code> <button class="copy-button">copy</button></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>
<h4><code>fsPromises.appendFile(path, data[, options])</code><span><a class="mark" href="#all_fs_fspromisesappendfilepath-data-options" id="all_fs_fspromisesappendfilepath-data-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_appendfile_path_data_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.10.0</td>
<td><p>The <code>flush</code> option is 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>
<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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></a> | <a href="#all_fs_class-filehandle" class="type">&#x3C;FileHandle></a> filename or <a href="#all_fs_class-filehandle" class="type">&#x3C;FileHandle></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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></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>
<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="#all_fs_file-system-flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'a'</code>.</li>
<li><code>flush</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 underlying file descriptor is flushed
prior to closing it. <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> Fulfills with <code>undefined</code> upon success.</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a>.</p>
<p>If <code>options</code> is a string, then it specifies the <code>encoding</code>.</p>
<p>The <code>mode</code> option only affects the newly created file. See <a href="#all_fs_fsopenpath-flags-mode-callback"><code>fs.open()</code></a>
for more details.</p>
<p>The <code>path</code> may be specified as a <a href="#all_fs_class-filehandle" class="type">&#x3C;FileHandle></a> that has been opened
for appending (using <code>fsPromises.open()</code>).</p>
<h4><code>fsPromises.chmod(path, mode)</code><span><a class="mark" href="#all_fs_fspromiseschmodpath-mode" id="all_fs_fspromiseschmodpath-mode">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_chmod_path_mode"></a></h4>
<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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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> Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>Changes the permissions of a file.</p>
<h4><code>fsPromises.chown(path, uid, gid)</code><span><a class="mark" href="#all_fs_fspromiseschownpath-uid-gid" id="all_fs_fspromiseschownpath-uid-gid">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_chown_path_uid_gid"></a></h4>
<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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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> Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>Changes the ownership of a file.</p>
<h4><code>fsPromises.copyFile(src, dest[, mode])</code><span><a class="mark" href="#all_fs_fspromisescopyfilesrc-dest-mode" id="all_fs_fspromisescopyfilesrc-dest-mode">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_copyfile_src_dest_mode"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.0.0</td>
<td><p>Changed <code>flags</code> argument to <code>mode</code> and imposed stricter type validation.</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>src</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></a> destination filename of the copy operation</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> Optional modifiers that specify 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>)
<strong>Default:</strong> <code>0</code>.
<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>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>Asynchronously copies <code>src</code> to <code>dest</code>. By default, <code>dest</code> is overwritten if it
already exists.</p>
<p>No guarantees are made about the atomicity of the copy operation. If an
error occurs after the destination file has been opened for writing, an attempt
will be made to remove the destination.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { copyFile, constants } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;

<span class="hljs-keyword">try</span> {
  <span class="hljs-keyword">await</span> <span class="hljs-title function_">copyFile</span>(<span class="hljs-string">'source.txt'</span>, <span class="hljs-string">'destination.txt'</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'source.txt was copied to destination.txt'</span>);
} <span class="hljs-keyword">catch</span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'The file could not be copied'</span>);
}

<span class="hljs-comment">// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.</span>
<span class="hljs-keyword">try</span> {
  <span class="hljs-keyword">await</span> <span class="hljs-title function_">copyFile</span>(<span class="hljs-string">'source.txt'</span>, <span class="hljs-string">'destination.txt'</span>, constants.<span class="hljs-property">COPYFILE_EXCL</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'source.txt was copied to destination.txt'</span>);
} <span class="hljs-keyword">catch</span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'The file could not be copied'</span>);
}</code> <button class="copy-button">copy</button></pre>
<h4><code>fsPromises.cp(src, dest[, options])</code><span><a class="mark" href="#all_fs_fspromisescpsrc-dest-options" id="all_fs_fspromisescpsrc-dest-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_cp_src_dest_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.1.0</td>
<td><p>Accept an additional <code>mode</code> option to specify the copy behavior as the <code>mode</code> argument of <code>fs.copyFile()</code>.</p></td></tr>
<tr><td>v17.6.0, v16.15.0</td>
<td><p>Accepts an additional <code>verbatimSymlinks</code> option to specify whether to perform path resolution for symlinks.</p></td></tr>
<tr><td>v16.7.0</td>
<td><p><span>Added in: v16.7.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<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="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></a> source path 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="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></a> destination path to copy to.</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>
<ul>
<li><code>dereference</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> dereference symlinks. <strong>Default:</strong> <code>false</code>.</li>
<li><code>errorOnExist</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> when <code>force</code> is <code>false</code>, and the destination
exists, throw an error. <strong>Default:</strong> <code>false</code>.</li>
<li><code>filter</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Function to filter copied files/directories. Return
<code>true</code> to copy the item, <code>false</code> to ignore it. When ignoring a directory,
all of its contents will be skipped as well. Can also return a <code>Promise</code>
that resolves to <code>true</code> or <code>false</code> <strong>Default:</strong> <code>undefined</code>.
<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> source path 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> destination path to copy to.</li>
<li>Returns: <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/Promise" class="type">&#x3C;Promise></a> A value that is coercible to <code>boolean</code> or
a <code>Promise</code> that fulfils with such value.</li>
</ul>
</li>
<li><code>force</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> overwrite existing file or directory. The copy
operation will ignore errors if you set this to false and the destination
exists. Use the <code>errorOnExist</code> option to change this behavior.
<strong>Default:</strong> <code>true</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> modifiers for copy operation. <strong>Default:</strong> <code>0</code>.
See <code>mode</code> flag of <a href="#all_fs_fspromisescopyfilesrc-dest-mode"><code>fsPromises.copyFile()</code></a>.</li>
<li><code>preserveTimestamps</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> timestamps from <code>src</code> will
be preserved. <strong>Default:</strong> <code>false</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> copy directories recursively <strong>Default:</strong> <code>false</code></li>
<li><code>verbatimSymlinks</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>, path resolution for symlinks will
be skipped. <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> Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>Asynchronously copies the entire directory structure from <code>src</code> to <code>dest</code>,
including subdirectories and files.</p>
<p>When copying a directory to another directory, globs are not supported and
behavior is similar to <code>cp dir1/ dir2/</code>.</p>
<h4><code>fsPromises.lchmod(path, mode)</code><span><a class="mark" href="#all_fs_fspromiseslchmodpath-mode" id="all_fs_fspromiseslchmodpath-mode">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_lchmod_path_mode"></a></h4>
<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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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> Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>Changes the permissions on a symbolic link.</p>
<p>This method is only implemented on macOS.</p>
<h4><code>fsPromises.lchown(path, uid, gid)</code><span><a class="mark" href="#all_fs_fspromiseslchownpath-uid-gid" id="all_fs_fspromiseslchownpath-uid-gid">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_lchown_path_uid_gid"></a></h4>
<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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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>  Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>Changes the ownership on a symbolic link.</p>
<h4><code>fsPromises.lutimes(path, atime, mtime)</code><span><a class="mark" href="#all_fs_fspromiseslutimespath-atime-mtime" id="all_fs_fspromiseslutimespath-atime-mtime">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_lutimes_path_atime_mtime"></a></h4>
<div class="api_metadata">
<span>Added in: v14.5.0, v12.19.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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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>  Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>Changes the access and modification times of a file in the same way as
<a href="#all_fs_fspromisesutimespath-atime-mtime"><code>fsPromises.utimes()</code></a>, with the difference that if the path refers to a
symbolic link, then the link is not dereferenced: instead, the timestamps of
the symbolic link itself are changed.</p>
<h4><code>fsPromises.link(existingPath, newPath)</code><span><a class="mark" href="#all_fs_fspromiseslinkexistingpath-newpath" id="all_fs_fspromiseslinkexistingpath-newpath">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_link_existingpath_newpath"></a></h4>
<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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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>  Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>Creates a new link from the <code>existingPath</code> to the <code>newPath</code>. See the POSIX
<a href="http://man7.org/linux/man-pages/man2/link.2.html"><code>link(2)</code></a> documentation for more detail.</p>
<h4><code>fsPromises.lstat(path[, options])</code><span><a class="mark" href="#all_fs_fspromiseslstatpath-options" id="all_fs_fspromiseslstatpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_lstat_path_options"></a></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><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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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>
<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="#all_fs_class-fsstats" class="type">&#x3C;fs.Stats></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>  Fulfills with the <a href="#all_fs_class-fsstats" class="type">&#x3C;fs.Stats></a> object for the given
symbolic link <code>path</code>.</li>
</ul>
<p>Equivalent to <a href="#all_fs_fspromisesstatpath-options"><code>fsPromises.stat()</code></a> unless <code>path</code> refers to a symbolic link,
in which case the link itself is stat-ed, not the file that it refers to.
Refer to the POSIX <a href="http://man7.org/linux/man-pages/man2/lstat.2.html"><code>lstat(2)</code></a> document for more detail.</p>
<h4><code>fsPromises.mkdir(path[, options])</code><span><a class="mark" href="#all_fs_fspromisesmkdirpath-options" id="all_fs_fspromisesmkdirpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_mkdir_path_options"></a></h4>
<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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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#Number_type" class="type">&#x3C;integer></a>
<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> Upon success, fulfills with <code>undefined</code> if <code>recursive</code>
is <code>false</code>, or the first directory path created if <code>recursive</code> is <code>true</code>.</li>
</ul>
<p>Asynchronously creates a directory.</p>
<p>The optional <code>options</code> argument can be an integer specifying <code>mode</code> (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>

<pre class="with-46-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { mkdir } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;

<span class="hljs-keyword">try</span> {
  <span class="hljs-keyword">const</span> projectFolder = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'./test/project/'</span>, <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>);
  <span class="hljs-keyword">const</span> createDir = <span class="hljs-keyword">await</span> <span class="hljs-title function_">mkdir</span>(projectFolder, { <span class="hljs-attr">recursive</span>: <span class="hljs-literal">true</span> });

  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`created <span class="hljs-subst">${createDir}</span>`</span>);
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err.<span class="hljs-property">message</span>);
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { mkdir } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs/promises'</span>);
<span class="hljs-keyword">const</span> { join } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:path'</span>);

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">makeDirectory</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">const</span> projectFolder = <span class="hljs-title function_">join</span>(__dirname, <span class="hljs-string">'test'</span>, <span class="hljs-string">'project'</span>);
  <span class="hljs-keyword">const</span> dirCreation = <span class="hljs-keyword">await</span> <span class="hljs-title function_">mkdir</span>(projectFolder, { <span class="hljs-attr">recursive</span>: <span class="hljs-literal">true</span> });

  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(dirCreation);
  <span class="hljs-keyword">return</span> dirCreation;
}

<span class="hljs-title function_">makeDirectory</span>().<span class="hljs-title function_">catch</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">error</span>);</code><button class="copy-button">copy</button></pre>
<h4><code>fsPromises.mkdtemp(prefix[, options])</code><span><a class="mark" href="#all_fs_fspromisesmkdtempprefix-options" id="all_fs_fspromisesmkdtempprefix-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_mkdtemp_prefix_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.6.0</td>
<td><p>The <code>prefix</code> parameter now accepts buffers and URL.</p></td></tr>
<tr><td>v16.5.0, v14.18.0</td>
<td><p>The <code>prefix</code> parameter now accepts an empty string.</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>prefix</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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/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>
<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>  Fulfills with a string containing the file system path
of the newly created temporary directory.</li>
</ul>
<p>Creates a unique temporary directory. 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 mjs"><span class="hljs-keyword">import</span> { mkdtemp } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
<span class="hljs-keyword">import</span> { join } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:path'</span>;
<span class="hljs-keyword">import</span> { tmpdir } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:os'</span>;

<span class="hljs-keyword">try</span> {
  <span class="hljs-keyword">await</span> <span class="hljs-title function_">mkdtemp</span>(<span class="hljs-title function_">join</span>(<span class="hljs-title function_">tmpdir</span>(), <span class="hljs-string">'foo-'</span>));
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err);
}</code> <button class="copy-button">copy</button></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('node:path').sep</code>).</p>
<h4><code>fsPromises.open(path, flags[, mode])</code><span><a class="mark" href="#all_fs_fspromisesopenpath-flags-mode" id="all_fs_fspromisesopenpath-flags-mode">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_open_path_flags_mode"></a></h4>
<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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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="#all_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> Sets the file mode (permission and sticky bits)
if the file is created. <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> Fulfills with a <a href="#all_fs_class-filehandle" class="type">&#x3C;FileHandle></a> object.</li>
</ul>
<p>Opens a <a href="#all_fs_class-filehandle" class="type">&#x3C;FileHandle></a>.</p>
<p>Refer to the POSIX <a href="http://man7.org/linux/man-pages/man2/open.2.html"><code>open(2)</code></a> documentation for more detail.</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>
<h4><code>fsPromises.opendir(path[, options])</code><span><a class="mark" href="#all_fs_fspromisesopendirpath-options" id="all_fs_fspromisesopendirpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_opendir_path_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.1.0</td>
<td><p>Added <code>recursive</code> option.</p></td></tr>
<tr><td>v13.1.0, 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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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>
<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>
<li><code>recursive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Resolved <code>Dir</code> will be an <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type">&#x3C;AsyncIterable></a>
containing all sub files and directories. <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>  Fulfills with an <a href="#all_fs_class-fsdir" class="type">&#x3C;fs.Dir></a>.</li>
</ul>
<p>Asynchronously open a directory for iterative scanning. See the POSIX
<a href="http://man7.org/linux/man-pages/man3/opendir.3.html"><code>opendir(3)</code></a> documentation for more detail.</p>
<p>Creates an <a href="#all_fs_class-fsdir" class="type">&#x3C;fs.Dir></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 mjs"><span class="hljs-keyword">import</span> { opendir } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;

<span class="hljs-keyword">try</span> {
  <span class="hljs-keyword">const</span> dir = <span class="hljs-keyword">await</span> <span class="hljs-title function_">opendir</span>(<span class="hljs-string">'./'</span>);
  <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> dirent <span class="hljs-keyword">of</span> dir)
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(dirent.<span class="hljs-property">name</span>);
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err);
}</code> <button class="copy-button">copy</button></pre>
<p>When using the async iterator, the <a href="#all_fs_class-fsdir" class="type">&#x3C;fs.Dir></a> object will be automatically
closed after the iterator exits.</p>
<h4><code>fsPromises.readdir(path[, options])</code><span><a class="mark" href="#all_fs_fspromisesreaddirpath-options" id="all_fs_fspromisesreaddirpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_readdir_path_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.1.0</td>
<td><p>Added <code>recursive</code> option.</p></td></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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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/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>
<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>
<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>, reads the contents of a directory
recursively. In recursive mode, it will list all files, sub files, and
directories. <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>  Fulfills with an array of the names of the files in
the directory excluding <code>'.'</code> and <code>'..'</code>.</li>
</ul>
<p>Reads the contents of a directory.</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 <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> objects.</p>
<p>If <code>options.withFileTypes</code> is set to <code>true</code>, the returned array will contain
<a href="#all_fs_class-fsdirent" class="type">&#x3C;fs.Dirent></a> objects.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { readdir } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;

<span class="hljs-keyword">try</span> {
  <span class="hljs-keyword">const</span> files = <span class="hljs-keyword">await</span> <span class="hljs-title function_">readdir</span>(path);
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> file <span class="hljs-keyword">of</span> files)
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(file);
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err);
}</code> <button class="copy-button">copy</button></pre>
<h4><code>fsPromises.readFile(path[, options])</code><span><a class="mark" href="#all_fs_fspromisesreadfilepath-options" id="all_fs_fspromisesreadfilepath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_readfile_path_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.2.0, v14.17.0</td>
<td><p>The options argument may include an AbortSignal to abort an ongoing readFile request.</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></a> | <a href="#all_fs_class-filehandle" class="type">&#x3C;FileHandle></a> filename or <code>FileHandle</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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a>
<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="#all_fs_file-system-flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'r'</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> allows aborting an in-progress readFile</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>  Fulfills with the contents of the file.</li>
</ul>
<p>Asynchronously reads the entire contents of a file.</p>
<p>If no encoding is specified (using <code>options.encoding</code>), the data is returned
as a <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> 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>An example of reading a <code>package.json</code> file located in the same directory of the
running code:</p>

<pre class="with-49-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { readFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
<span class="hljs-keyword">try</span> {
  <span class="hljs-keyword">const</span> filePath = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'./package.json'</span>, <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>);
  <span class="hljs-keyword">const</span> contents = <span class="hljs-keyword">await</span> <span class="hljs-title function_">readFile</span>(filePath, { <span class="hljs-attr">encoding</span>: <span class="hljs-string">'utf8'</span> });
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(contents);
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err.<span class="hljs-property">message</span>);
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { readFile } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs/promises'</span>);
<span class="hljs-keyword">const</span> { resolve } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:path'</span>);
<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">logFile</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> filePath = <span class="hljs-title function_">resolve</span>(<span class="hljs-string">'./package.json'</span>);
    <span class="hljs-keyword">const</span> contents = <span class="hljs-keyword">await</span> <span class="hljs-title function_">readFile</span>(filePath, { <span class="hljs-attr">encoding</span>: <span class="hljs-string">'utf8'</span> });
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(contents);
  } <span class="hljs-keyword">catch</span> (err) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err.<span class="hljs-property">message</span>);
  }
}
<span class="hljs-title function_">logFile</span>();</code><button class="copy-button">copy</button></pre>
<p>It is possible to abort an ongoing <code>readFile</code> using an <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a>. If a
request is aborted the promise returned is rejected with an <code>AbortError</code>:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { readFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;

<span class="hljs-keyword">try</span> {
  <span class="hljs-keyword">const</span> controller = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
  <span class="hljs-keyword">const</span> { signal } = controller;
  <span class="hljs-keyword">const</span> promise = <span class="hljs-title function_">readFile</span>(fileName, { signal });

  <span class="hljs-comment">// Abort the request before the promise settles.</span>
  controller.<span class="hljs-title function_">abort</span>();

  <span class="hljs-keyword">await</span> promise;
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-comment">// When a request is aborted - err is an AbortError</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err);
}</code> <button class="copy-button">copy</button></pre>
<p>Aborting an ongoing request does not abort individual operating
system requests but rather the internal buffering <code>fs.readFile</code> performs.</p>
<p>Any specified <a href="#all_fs_class-filehandle" class="type">&#x3C;FileHandle></a> has to support reading.</p>
<h4><code>fsPromises.readlink(path[, options])</code><span><a class="mark" href="#all_fs_fspromisesreadlinkpath-options" id="all_fs_fspromisesreadlinkpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_readlink_path_options"></a></h4>
<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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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/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>
<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> Fulfills with the <code>linkString</code> upon success.</li>
</ul>
<p>Reads the contents of the symbolic link referred to by <code>path</code>. See the POSIX
<a href="http://man7.org/linux/man-pages/man2/readlink.2.html"><code>readlink(2)</code></a> documentation for more detail. The promise is fulfilled 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 <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> object.</p>
<h4><code>fsPromises.realpath(path[, options])</code><span><a class="mark" href="#all_fs_fspromisesrealpathpath-options" id="all_fs_fspromisesrealpathpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_realpath_path_options"></a></h4>
<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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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/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>
<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>  Fulfills with the resolved path upon success.</li>
</ul>
<p>Determines the actual location of <code>path</code> using the same semantics as the
<code>fs.realpath.native()</code> function.</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 <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> 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>
<h4><code>fsPromises.rename(oldPath, newPath)</code><span><a class="mark" href="#all_fs_fspromisesrenameoldpath-newpath" id="all_fs_fspromisesrenameoldpath-newpath">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_rename_oldpath_newpath"></a></h4>
<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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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> Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>Renames <code>oldPath</code> to <code>newPath</code>.</p>
<h4><code>fsPromises.rmdir(path[, options])</code><span><a class="mark" href="#all_fs_fspromisesrmdirpath-options" id="all_fs_fspromisesrmdirpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_rmdir_path_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0</td>
<td><p>Using <code>fsPromises.rmdir(path, { recursive: true })</code> on a <code>path</code> that is a file is no longer permitted and results in an <code>ENOENT</code> error on Windows and an <code>ENOTDIR</code> error on POSIX.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p>Using <code>fsPromises.rmdir(path, { recursive: true })</code> on a <code>path</code> that does not exist is no longer permitted and results in a <code>ENOENT</code> error.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p>The <code>recursive</code> option is deprecated, using it triggers a deprecation warning.</p></td></tr>
<tr><td>v14.14.0</td>
<td><p>The <code>recursive</code> option is deprecated, use <code>fsPromises.rm</code> instead.</p></td></tr>
<tr><td>v13.3.0, 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>
<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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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>
<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 retries the operation with a linear
backoff wait of <code>retryDelay</code> milliseconds 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, operations are retried on failure. <strong>Default:</strong> <code>false</code>.
<strong>Deprecated.</strong></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> Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>Removes the directory identified by <code>path</code>.</p>
<p>Using <code>fsPromises.rmdir()</code> on a file (not a directory) results in the
promise being rejected with an <code>ENOENT</code> error on Windows and an <code>ENOTDIR</code>
error on POSIX.</p>
<p>To get a behavior similar to the <code>rm -rf</code> Unix command, use
<a href="#all_fs_fspromisesrmpath-options"><code>fsPromises.rm()</code></a> with options <code>{ recursive: true, force: true }</code>.</p>
<h4><code>fsPromises.rm(path[, options])</code><span><a class="mark" href="#all_fs_fspromisesrmpath-options" id="all_fs_fspromisesrmpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_rm_path_options"></a></h4>
<div class="api_metadata">
<span>Added in: v14.14.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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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>
<ul>
<li><code>force</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>, exceptions will be ignored if <code>path</code> does
not exist. <strong>Default:</strong> <code>false</code>.</li>
<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> milliseconds 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 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> Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>Removes files and directories (modeled on the standard POSIX <code>rm</code> utility).</p>
<h4><code>fsPromises.stat(path[, options])</code><span><a class="mark" href="#all_fs_fspromisesstatpath-options" id="all_fs_fspromisesstatpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_stat_path_options"></a></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><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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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>
<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="#all_fs_class-fsstats" class="type">&#x3C;fs.Stats></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>  Fulfills with the <a href="#all_fs_class-fsstats" class="type">&#x3C;fs.Stats></a> object for the
given <code>path</code>.</li>
</ul>
<h4><code>fsPromises.statfs(path[, options])</code><span><a class="mark" href="#all_fs_fspromisesstatfspath-options" id="all_fs_fspromisesstatfspath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_statfs_path_options"></a></h4>
<div class="api_metadata">
<span>Added in: v19.6.0, v18.15.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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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>
<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="#all_fs_class-fsstatfs" class="type">&#x3C;fs.StatFs></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> Fulfills with the <a href="#all_fs_class-fsstatfs" class="type">&#x3C;fs.StatFs></a> object for the
given <code>path</code>.</li>
</ul>
<h4><code>fsPromises.symlink(target, path[, type])</code><span><a class="mark" href="#all_fs_fspromisessymlinktarget-path-type" id="all_fs_fspromisessymlinktarget-path-type">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_symlink_target_path_type"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>If the <code>type</code> argument is <code>null</code> or omitted, Node.js will autodetect <code>target</code> type and automatically select <code>dir</code> or <code>file</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>target</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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> | <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>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>Creates a symbolic link.</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>. If the <code>type</code> argument is not a string, 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. Junction points on NTFS volumes
can only point to directories.</p>
<h4><code>fsPromises.truncate(path[, len])</code><span><a class="mark" href="#all_fs_fspromisestruncatepath-len" id="all_fs_fspromisestruncatepath-len">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_truncate_path_len"></a></h4>
<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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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> Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>Truncates (shortens or extends the length) of the content at <code>path</code> to <code>len</code>
bytes.</p>
<h4><code>fsPromises.unlink(path)</code><span><a class="mark" href="#all_fs_fspromisesunlinkpath" id="all_fs_fspromisesunlinkpath">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_unlink_path"></a></h4>
<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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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> Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>If <code>path</code> refers to a symbolic link, then the link is removed without affecting
the file or directory to which that link refers. If the <code>path</code> refers to a file
path that is not a symbolic link, the file is deleted. See the POSIX <a href="http://man7.org/linux/man-pages/man2/unlink.2.html"><code>unlink(2)</code></a>
documentation for more detail.</p>
<h4><code>fsPromises.utimes(path, atime, mtime)</code><span><a class="mark" href="#all_fs_fspromisesutimespath-atime-mtime" id="all_fs_fspromisesutimespath-atime-mtime">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_utimes_path_atime_mtime"></a></h4>
<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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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> Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>Change the file system timestamps of the object referenced by <code>path</code>.</p>
<p>The <code>atime</code> and <code>mtime</code> arguments follow these rules:</p>
<ul>
<li>Values can be either numbers representing Unix epoch time, <code>Date</code>s, or a
numeric string like <code>'123456789.0'</code>.</li>
<li>If the value can not be converted to a number, or is <code>NaN</code>, <code>Infinity</code>, or
<code>-Infinity</code>, an <code>Error</code> will be thrown.</li>
</ul>
<h4><code>fsPromises.watch(filename[, options])</code><span><a class="mark" href="#all_fs_fspromiseswatchfilename-options" id="all_fs_fspromiseswatchfilename-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_watch_filename_options"></a></h4>
<div class="api_metadata">
<span>Added in: v15.9.0, v14.18.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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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/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>
<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="#all_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>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> An <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> used to signal when the watcher
should stop.</li>
</ul>
</li>
<li>Returns: <a href="https://tc39.github.io/ecma262/#sec-asynciterator-interface" class="type">&#x3C;AsyncIterator></a> of objects with the properties:
<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</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="#all_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> The name of the file changed.</li>
</ul>
</li>
</ul>
<p>Returns an async iterator that watches for changes on <code>filename</code>, where <code>filename</code>
is either a file or a directory.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { watch } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs/promises'</span>);

<span class="hljs-keyword">const</span> ac = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
<span class="hljs-keyword">const</span> { signal } = ac;
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> ac.<span class="hljs-title function_">abort</span>(), <span class="hljs-number">10000</span>);

(<span class="hljs-keyword">async</span> () => {
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> watcher = <span class="hljs-title function_">watch</span>(__filename, { signal });
    <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> event <span class="hljs-keyword">of</span> watcher)
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(event);
  } <span class="hljs-keyword">catch</span> (err) {
    <span class="hljs-keyword">if</span> (err.<span class="hljs-property">name</span> === <span class="hljs-string">'AbortError'</span>)
      <span class="hljs-keyword">return</span>;
    <span class="hljs-keyword">throw</span> err;
  }
})();</code> <button class="copy-button">copy</button></pre>
<p>On most platforms, <code>'rename'</code> is emitted whenever a filename appears or
disappears in the directory.</p>
<p>All the <a href="#all_fs_caveats">caveats</a> for <code>fs.watch()</code> also apply to <code>fsPromises.watch()</code>.</p>
<h4><code>fsPromises.writeFile(file, data[, options])</code><span><a class="mark" href="#all_fs_fspromiseswritefilefile-data-options" id="all_fs_fspromiseswritefilefile-data-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_writefile_file_data_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.10.0</td>
<td><p>The <code>flush</code> option is now supported.</p></td></tr>
<tr><td>v15.14.0, v14.18.0</td>
<td><p>The <code>data</code> argument supports <code>AsyncIterable</code>, <code>Iterable</code>, and <code>Stream</code>.</p></td></tr>
<tr><td>v15.2.0, v14.17.0</td>
<td><p>The options argument may include an AbortSignal to abort an ongoing writeFile request.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>The <code>data</code> parameter won't coerce unsupported input to strings anymore.</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>file</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></a> | <a href="#all_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="#all_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://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type">&#x3C;AsyncIterable></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol" class="type">&#x3C;Iterable></a> | <a href="#all_stream_stream" class="type">&#x3C;Stream></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>
<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="#all_fs_file-system-flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'w'</code>.</li>
<li><code>flush</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If all data is successfully written to the file, and
<code>flush</code> is <code>true</code>, <code>filehandle.sync()</code> is used to flush the data.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> allows aborting an in-progress writeFile</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> Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>Asynchronously writes data to a file, replacing the file if it already exists.
<code>data</code> can be a string, a buffer, an <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type">&#x3C;AsyncIterable></a>, or an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol" class="type">&#x3C;Iterable></a> object.</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>mode</code> option only affects the newly created file. See <a href="#all_fs_fsopenpath-flags-mode-callback"><code>fs.open()</code></a>
for more details.</p>
<p>Any specified <a href="#all_fs_class-filehandle" class="type">&#x3C;FileHandle></a> 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 promise to be settled.</p>
<p>Similarly to <code>fsPromises.readFile</code> - <code>fsPromises.writeFile</code> is a convenience
method that performs multiple <code>write</code> calls internally to write the buffer
passed to it. For performance sensitive code consider using
<a href="#all_fs_fscreatewritestreampath-options"><code>fs.createWriteStream()</code></a> or <a href="#all_fs_filehandlecreatewritestreamoptions"><code>filehandle.createWriteStream()</code></a>.</p>
<p>It is possible to use an <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> to cancel an <code>fsPromises.writeFile()</code>.
Cancelation is "best effort", and some amount of data is likely still
to be written.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { writeFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">try</span> {
  <span class="hljs-keyword">const</span> controller = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
  <span class="hljs-keyword">const</span> { signal } = controller;
  <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'Hello Node.js'</span>));
  <span class="hljs-keyword">const</span> promise = <span class="hljs-title function_">writeFile</span>(<span class="hljs-string">'message.txt'</span>, data, { signal });

  <span class="hljs-comment">// Abort the request before the promise settles.</span>
  controller.<span class="hljs-title function_">abort</span>();

  <span class="hljs-keyword">await</span> promise;
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-comment">// When a request is aborted - err is an AbortError</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err);
}</code> <button class="copy-button">copy</button></pre>
<p>Aborting an ongoing request does not abort individual operating
system requests but rather the internal buffering <code>fs.writeFile</code> performs.</p>
<h4><code>fsPromises.constants</code><span><a class="mark" href="#all_fs_fspromisesconstants" id="all_fs_fspromisesconstants">#</a></span><a aria-hidden="true" class="legacy" id="fs_fspromises_constants"></a></h4>
<div class="api_metadata">
<span>Added in: v18.4.0, v16.17.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>Returns an object containing commonly used constants for file system
operations. The object is the same as <code>fs.constants</code>. See <a href="#all_fs_fs-constants">FS constants</a>
for more details.</p>
</section><section><h3>Callback API<span><a class="mark" href="#all_fs_callback-api" id="all_fs_callback-api">#</a></span><a aria-hidden="true" class="legacy" id="fs_callback_api"></a></h3>
<p>The callback APIs perform all operations asynchronously, without blocking the
event loop, then invoke a callback function upon completion or error.</p>
<p>The callback APIs use the underlying Node.js threadpool to perform file
system operations off the event loop thread. These operations are not
synchronized or threadsafe. Care must be taken when performing multiple
concurrent modifications on the same file or data corruption may occur.</p>
<h4><code>fs.access(path[, mode], callback)</code><span><a class="mark" href="#all_fs_fsaccesspath-mode-callback" id="all_fs_fsaccesspath-mode-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_access_path_mode_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.8.0</td>
<td><p>The constants <code>fs.F_OK</code>, <code>fs.R_OK</code>, <code>fs.W_OK</code> and <code>fs.X_OK</code> which were present directly on <code>fs</code> are deprecated.</p></td></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</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.</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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. <code>mode</code> should be either the value <code>fs.constants.F_OK</code>
or a mask consisting of the bitwise OR of any of <code>fs.constants.R_OK</code>,
<code>fs.constants.W_OK</code>, and <code>fs.constants.X_OK</code> (e.g.
<code>fs.constants.W_OK | fs.constants.R_OK</code>). Check <a href="#all_fs_file-access-constants">File access constants</a> for
possible values of <code>mode</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 mjs"><span class="hljs-keyword">import</span> { access, constants } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-keyword">const</span> file = <span class="hljs-string">'package.json'</span>;

<span class="hljs-comment">// Check if the file exists in the current directory.</span>
<span class="hljs-title function_">access</span>(file, constants.<span class="hljs-property">F_OK</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${file}</span> <span class="hljs-subst">${err ? <span class="hljs-string">'does not exist'</span> : <span class="hljs-string">'exists'</span>}</span>`</span>);
});

<span class="hljs-comment">// Check if the file is readable.</span>
<span class="hljs-title function_">access</span>(file, constants.<span class="hljs-property">R_OK</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${file}</span> <span class="hljs-subst">${err ? <span class="hljs-string">'is not readable'</span> : <span class="hljs-string">'is readable'</span>}</span>`</span>);
});

<span class="hljs-comment">// Check if the file is writable.</span>
<span class="hljs-title function_">access</span>(file, constants.<span class="hljs-property">W_OK</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${file}</span> <span class="hljs-subst">${err ? <span class="hljs-string">'is not writable'</span> : <span class="hljs-string">'is writable'</span>}</span>`</span>);
});

<span class="hljs-comment">// Check if the file is readable and writable.</span>
<span class="hljs-title function_">access</span>(file, constants.<span class="hljs-property">R_OK</span> | constants.<span class="hljs-property">W_OK</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${file}</span> <span class="hljs-subst">${err ? <span class="hljs-string">'is not'</span> : <span class="hljs-string">'is'</span>}</span> readable and writable`</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>Do not use <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>. 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 mjs"><span class="hljs-keyword">import</span> { access, open, close } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-title function_">access</span>(<span class="hljs-string">'myfile'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-keyword">if</span> (!err) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'myfile already exists'</span>);
    <span class="hljs-keyword">return</span>;
  }

  <span class="hljs-title function_">open</span>(<span class="hljs-string">'myfile'</span>, <span class="hljs-string">'wx'</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
    <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;

    <span class="hljs-keyword">try</span> {
      <span class="hljs-title function_">writeMyData</span>(fd);
    } <span class="hljs-keyword">finally</span> {
      <span class="hljs-title function_">close</span>(fd, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
        <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
      });
    }
  });
});</code> <button class="copy-button">copy</button></pre>
<p><strong>write (RECOMMENDED)</strong></p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { open, close } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-title function_">open</span>(<span class="hljs-string">'myfile'</span>, <span class="hljs-string">'wx'</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) {
    <span class="hljs-keyword">if</span> (err.<span class="hljs-property">code</span> === <span class="hljs-string">'EEXIST'</span>) {
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'myfile already exists'</span>);
      <span class="hljs-keyword">return</span>;
    }

    <span class="hljs-keyword">throw</span> err;
  }

  <span class="hljs-keyword">try</span> {
    <span class="hljs-title function_">writeMyData</span>(fd);
  } <span class="hljs-keyword">finally</span> {
    <span class="hljs-title function_">close</span>(fd, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
      <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
    });
  }
});</code> <button class="copy-button">copy</button></pre>
<p><strong>read (NOT RECOMMENDED)</strong></p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { access, open, close } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-title function_">access</span>(<span class="hljs-string">'myfile'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) {
    <span class="hljs-keyword">if</span> (err.<span class="hljs-property">code</span> === <span class="hljs-string">'ENOENT'</span>) {
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'myfile does not exist'</span>);
      <span class="hljs-keyword">return</span>;
    }

    <span class="hljs-keyword">throw</span> err;
  }

  <span class="hljs-title function_">open</span>(<span class="hljs-string">'myfile'</span>, <span class="hljs-string">'r'</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
    <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;

    <span class="hljs-keyword">try</span> {
      <span class="hljs-title function_">readMyData</span>(fd);
    } <span class="hljs-keyword">finally</span> {
      <span class="hljs-title function_">close</span>(fd, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
        <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
      });
    }
  });
});</code> <button class="copy-button">copy</button></pre>
<p><strong>read (RECOMMENDED)</strong></p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { open, close } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-title function_">open</span>(<span class="hljs-string">'myfile'</span>, <span class="hljs-string">'r'</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) {
    <span class="hljs-keyword">if</span> (err.<span class="hljs-property">code</span> === <span class="hljs-string">'ENOENT'</span>) {
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'myfile does not exist'</span>);
      <span class="hljs-keyword">return</span>;
    }

    <span class="hljs-keyword">throw</span> err;
  }

  <span class="hljs-keyword">try</span> {
    <span class="hljs-title function_">readMyData</span>(fd);
  } <span class="hljs-keyword">finally</span> {
    <span class="hljs-title function_">close</span>(fd, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
      <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
    });
  }
});</code> <button class="copy-button">copy</button></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>
<h4><code>fs.appendFile(path, data[, options], callback)</code><span><a class="mark" href="#all_fs_fsappendfilepath-data-options-callback" id="all_fs_fsappendfilepath-data-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_appendfile_path_data_options_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.10.0</td>
<td><p>The <code>flush</code> option is now supported.</p></td></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</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.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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></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>
<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="#all_fs_file-system-flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'a'</code>.</li>
<li><code>flush</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 underlying file descriptor is flushed
prior to closing it. <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>
<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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a>.</p>
<p>The <code>mode</code> option only affects the newly created file. See <a href="#all_fs_fsopenpath-flags-mode-callback"><code>fs.open()</code></a>
for more details.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { appendFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-title function_">appendFile</span>(<span class="hljs-string">'message.txt'</span>, <span class="hljs-string">'data to append'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'The "data to append" was appended to file!'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>If <code>options</code> is a string, then it specifies the encoding:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { appendFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-title function_">appendFile</span>(<span class="hljs-string">'message.txt'</span>, <span class="hljs-string">'data to append'</span>, <span class="hljs-string">'utf8'</span>, callback);</code> <button class="copy-button">copy</button></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 mjs"><span class="hljs-keyword">import</span> { open, close, appendFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-keyword">function</span> <span class="hljs-title function_">closeFd</span>(<span class="hljs-params">fd</span>) {
  <span class="hljs-title function_">close</span>(fd, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
    <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  });
}

<span class="hljs-title function_">open</span>(<span class="hljs-string">'message.txt'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;

  <span class="hljs-keyword">try</span> {
    <span class="hljs-title function_">appendFile</span>(fd, <span class="hljs-string">'data to append'</span>, <span class="hljs-string">'utf8'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
      <span class="hljs-title function_">closeFd</span>(fd);
      <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
    });
  } <span class="hljs-keyword">catch</span> (err) {
    <span class="hljs-title function_">closeFd</span>(fd);
    <span class="hljs-keyword">throw</span> err;
  }
});</code> <button class="copy-button">copy</button></pre>
<h4><code>fs.chmod(path, mode, callback)</code><span><a class="mark" href="#all_fs_fschmodpath-mode-callback" id="all_fs_fschmodpath-mode-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_chmod_path_mode_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</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.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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 the POSIX <a href="http://man7.org/linux/man-pages/man2/chmod.2.html"><code>chmod(2)</code></a> documentation for more detail.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { chmod } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-title function_">chmod</span>(<span class="hljs-string">'my_file.txt'</span>, <span class="hljs-number">0o775</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'The permissions for file "my_file.txt" have been changed!'</span>);
});</code> <button class="copy-button">copy</button></pre>
<h5>File modes<span><a class="mark" href="#all_fs_file-modes" id="all_fs_file-modes">#</a></span><a aria-hidden="true" class="legacy" id="fs_file_modes"></a></h5>
<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>
<h4><code>fs.chown(path, uid, gid, callback)</code><span><a class="mark" href="#all_fs_fschownpath-uid-gid-callback" id="all_fs_fschownpath-uid-gid-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_chown_path_uid_gid_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</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.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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 the POSIX <a href="http://man7.org/linux/man-pages/man2/chown.2.html"><code>chown(2)</code></a> documentation for more detail.</p>
<h4><code>fs.close(fd[, callback])</code><span><a class="mark" href="#all_fs_fsclosefd-callback" id="all_fs_fsclosefd-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_close_fd_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></tr>
<tr><td>v15.9.0, v14.17.0</td>
<td><p>A default callback is now used if one is not provided.</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.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>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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>Closes the file descriptor. 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>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/close.2.html"><code>close(2)</code></a> documentation for more detail.</p>
<h4><code>fs.copyFile(src, dest[, mode], callback)</code><span><a class="mark" href="#all_fs_fscopyfilesrc-dest-mode-callback" id="all_fs_fscopyfilesrc-dest-mode-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_copyfile_src_dest_mode_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>Changed <code>flags</code> argument to <code>mode</code> and imposed stricter type validation.</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>src</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></a> destination filename of the copy operation</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> 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>
<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 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>mode</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 mjs"><span class="hljs-keyword">import</span> { copyFile, constants } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-keyword">function</span> <span class="hljs-title function_">callback</span>(<span class="hljs-params">err</span>) {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'source.txt was copied to destination.txt'</span>);
}

<span class="hljs-comment">// destination.txt will be created or overwritten by default.</span>
<span class="hljs-title function_">copyFile</span>(<span class="hljs-string">'source.txt'</span>, <span class="hljs-string">'destination.txt'</span>, callback);

<span class="hljs-comment">// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.</span>
<span class="hljs-title function_">copyFile</span>(<span class="hljs-string">'source.txt'</span>, <span class="hljs-string">'destination.txt'</span>, constants.<span class="hljs-property">COPYFILE_EXCL</span>, callback);</code> <button class="copy-button">copy</button></pre>
<h4><code>fs.cp(src, dest[, options], callback)</code><span><a class="mark" href="#all_fs_fscpsrc-dest-options-callback" id="all_fs_fscpsrc-dest-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_cp_src_dest_options_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.1.0</td>
<td><p>Accept an additional <code>mode</code> option to specify the copy behavior as the <code>mode</code> argument of <code>fs.copyFile()</code>.</p></td></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></tr>
<tr><td>v17.6.0, v16.15.0</td>
<td><p>Accepts an additional <code>verbatimSymlinks</code> option to specify whether to perform path resolution for symlinks.</p></td></tr>
<tr><td>v16.7.0</td>
<td><p><span>Added in: v16.7.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<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="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></a> source path 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="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></a> destination path to copy to.</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>
<ul>
<li><code>dereference</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> dereference symlinks. <strong>Default:</strong> <code>false</code>.</li>
<li><code>errorOnExist</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> when <code>force</code> is <code>false</code>, and the destination
exists, throw an error. <strong>Default:</strong> <code>false</code>.</li>
<li><code>filter</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Function to filter copied files/directories. Return
<code>true</code> to copy the item, <code>false</code> to ignore it. When ignoring a directory,
all of its contents will be skipped as well. Can also return a <code>Promise</code>
that resolves to <code>true</code> or <code>false</code> <strong>Default:</strong> <code>undefined</code>.
<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> source path 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> destination path to copy to.</li>
<li>Returns: <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/Promise" class="type">&#x3C;Promise></a> A value that is coercible to <code>boolean</code> or
a <code>Promise</code> that fulfils with such value.</li>
</ul>
</li>
<li><code>force</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> overwrite existing file or directory. The copy
operation will ignore errors if you set this to false and the destination
exists. Use the <code>errorOnExist</code> option to change this behavior.
<strong>Default:</strong> <code>true</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> modifiers for copy operation. <strong>Default:</strong> <code>0</code>.
See <code>mode</code> flag of <a href="#all_fs_fscopyfilesrc-dest-mode-callback"><code>fs.copyFile()</code></a>.</li>
<li><code>preserveTimestamps</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> timestamps from <code>src</code> will
be preserved. <strong>Default:</strong> <code>false</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> copy directories recursively <strong>Default:</strong> <code>false</code></li>
<li><code>verbatimSymlinks</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>, path resolution for symlinks will
be skipped. <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>
<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 copies the entire directory structure from <code>src</code> to <code>dest</code>,
including subdirectories and files.</p>
<p>When copying a directory to another directory, globs are not supported and
behavior is similar to <code>cp dir1/ dir2/</code>.</p>
<h4><code>fs.createReadStream(path[, options])</code><span><a class="mark" href="#all_fs_fscreatereadstreampath-options" id="all_fs_fscreatereadstreampath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_createreadstream_path_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.10.0</td>
<td><p>The <code>fs</code> option does not need <code>open</code> method if an <code>fd</code> was provided.</p></td></tr>
<tr><td>v16.10.0</td>
<td><p>The <code>fs</code> option does not need <code>close</code> method if <code>autoClose</code> is <code>false</code>.</p></td></tr>
<tr><td>v15.5.0</td>
<td><p>Add support for <code>AbortSignal</code>.</p></td></tr>
<tr><td>v15.4.0</td>
<td><p>The <code>fd</code> option accepts FileHandle arguments.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>Change <code>emitClose</code> default to <code>true</code>.</p></td></tr>
<tr><td>v13.6.0, 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.</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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/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>
<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="#all_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> | <a href="#all_fs_class-filehandle" class="type">&#x3C;FileHandle></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>true</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>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></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="#all_fs_class-fsreadstream" class="type">&#x3C;fs.ReadStream></a></li>
</ul>
<p>Unlike the 16 KiB default <code>highWaterMark</code> for a <a href="#all_stream_class-streamreadable" class="type">&#x3C;stream.Readable></a>, the stream
returned by this method has a default <code>highWaterMark</code> of 64 KiB.</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></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="#all_net_class-netsocket" class="type">&#x3C;net.Socket></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 emit a <code>'close'</code> event after it has been
destroyed.  Set the <code>emitClose</code> option to <code>false</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,
an override for <code>read</code> is required. If no <code>fd</code> is provided, an override for
<code>open</code> is also required. If <code>autoClose</code> is <code>true</code>, an override for <code>close</code> is
also required.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { createReadStream } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-comment">// Create a stream from some character device.</span>
<span class="hljs-keyword">const</span> stream = <span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'/dev/input/event0'</span>);
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
  stream.<span class="hljs-title function_">close</span>(); <span class="hljs-comment">// This may not close the stream.</span>
  <span class="hljs-comment">// Artificially marking end-of-stream, as if the underlying resource had</span>
  <span class="hljs-comment">// indicated end-of-file by itself, allows the stream to close.</span>
  <span class="hljs-comment">// This does not cancel pending read operations, and if there is such an</span>
  <span class="hljs-comment">// operation, the process may still not be able to exit successfully</span>
  <span class="hljs-comment">// until it finishes.</span>
  stream.<span class="hljs-title function_">push</span>(<span class="hljs-literal">null</span>);
  stream.<span class="hljs-title function_">read</span>(<span class="hljs-number">0</span>);
}, <span class="hljs-number">100</span>);</code> <button class="copy-button">copy</button></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 mjs"><span class="hljs-keyword">import</span> { createReadStream } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'sample.txt'</span>, { <span class="hljs-attr">start</span>: <span class="hljs-number">90</span>, <span class="hljs-attr">end</span>: <span class="hljs-number">99</span> });</code> <button class="copy-button">copy</button></pre>
<p>If <code>options</code> is a string, then it specifies the encoding.</p>
<h4><code>fs.createWriteStream(path[, options])</code><span><a class="mark" href="#all_fs_fscreatewritestreampath-options" id="all_fs_fscreatewritestreampath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_createwritestream_path_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.10.0</td>
<td><p>The <code>flush</code> option is now supported.</p></td></tr>
<tr><td>v16.10.0</td>
<td><p>The <code>fs</code> option does not need <code>open</code> method if an <code>fd</code> was provided.</p></td></tr>
<tr><td>v16.10.0</td>
<td><p>The <code>fs</code> option does not need <code>close</code> method if <code>autoClose</code> is <code>false</code>.</p></td></tr>
<tr><td>v15.5.0</td>
<td><p>Add support for <code>AbortSignal</code>.</p></td></tr>
<tr><td>v15.4.0</td>
<td><p>The <code>fd</code> option accepts FileHandle arguments.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>Change <code>emitClose</code> default to <code>true</code>.</p></td></tr>
<tr><td>v13.6.0, 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.</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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/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>
<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="#all_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> | <a href="#all_fs_class-filehandle" class="type">&#x3C;FileHandle></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>true</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>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></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>highWaterMark</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>16384</code></li>
<li><code>flush</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 underlying file descriptor is flushed
prior to closing it. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>Returns: <a href="#all_fs_class-fswritestream" class="type">&#x3C;fs.WriteStream></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 the <code>flags</code> option to be set to <code>r+</code> rather than the
default <code>w</code>. The <code>encoding</code> can be any one of those accepted by <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></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 emit a <code>'close'</code> event after it has been
destroyed.  Set the <code>emitClose</code> option to <code>false</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 at least one of
<code>write</code> and <code>writev</code> are required. If no <code>fd</code> option is supplied, an override
for <code>open</code> is also required. If <code>autoClose</code> is <code>true</code>, an override for <code>close</code>
is also required.</p>
<p>Like <a href="#all_fs_class-fsreadstream" class="type">&#x3C;fs.ReadStream></a>, if <code>fd</code> is specified, <a href="#all_fs_class-fswritestream" class="type">&#x3C;fs.WriteStream></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="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a>.</p>
<p>If <code>options</code> is a string, then it specifies the encoding.</p>
<h4><code>fs.exists(path, callback)</code><span><a class="mark" href="#all_fs_fsexistspath-callback" id="all_fs_fsexistspath-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_exists_path_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</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.</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="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_fs_fsstatpath-options-callback"><code>fs.stat()</code></a> or <a href="#all_fs_fsaccesspath-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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></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>
<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 element at the given <code>path</code> 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 mjs"><span class="hljs-keyword">import</span> { exists } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-title function_">exists</span>(<span class="hljs-string">'/etc/passwd'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(e ? <span class="hljs-string">'it exists'</span> : <span class="hljs-string">'no passwd!'</span>);
});</code> <button class="copy-button">copy</button></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>If <code>path</code> is a symbolic link, it is followed. Thus, if <code>path</code> exists but points
to a non-existent element, the callback will receive the value <code>false</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 mjs"><span class="hljs-keyword">import</span> { exists, open, close } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-title function_">exists</span>(<span class="hljs-string">'myfile'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =></span> {
  <span class="hljs-keyword">if</span> (e) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'myfile already exists'</span>);
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-title function_">open</span>(<span class="hljs-string">'myfile'</span>, <span class="hljs-string">'wx'</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
      <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;

      <span class="hljs-keyword">try</span> {
        <span class="hljs-title function_">writeMyData</span>(fd);
      } <span class="hljs-keyword">finally</span> {
        <span class="hljs-title function_">close</span>(fd, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
          <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
        });
      }
    });
  }
});</code> <button class="copy-button">copy</button></pre>
<p><strong>write (RECOMMENDED)</strong></p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { open, close } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-title function_">open</span>(<span class="hljs-string">'myfile'</span>, <span class="hljs-string">'wx'</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) {
    <span class="hljs-keyword">if</span> (err.<span class="hljs-property">code</span> === <span class="hljs-string">'EEXIST'</span>) {
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'myfile already exists'</span>);
      <span class="hljs-keyword">return</span>;
    }

    <span class="hljs-keyword">throw</span> err;
  }

  <span class="hljs-keyword">try</span> {
    <span class="hljs-title function_">writeMyData</span>(fd);
  } <span class="hljs-keyword">finally</span> {
    <span class="hljs-title function_">close</span>(fd, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
      <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
    });
  }
});</code> <button class="copy-button">copy</button></pre>
<p><strong>read (NOT RECOMMENDED)</strong></p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { open, close, exists } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-title function_">exists</span>(<span class="hljs-string">'myfile'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =></span> {
  <span class="hljs-keyword">if</span> (e) {
    <span class="hljs-title function_">open</span>(<span class="hljs-string">'myfile'</span>, <span class="hljs-string">'r'</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
      <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;

      <span class="hljs-keyword">try</span> {
        <span class="hljs-title function_">readMyData</span>(fd);
      } <span class="hljs-keyword">finally</span> {
        <span class="hljs-title function_">close</span>(fd, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
          <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
        });
      }
    });
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'myfile does not exist'</span>);
  }
});</code> <button class="copy-button">copy</button></pre>
<p><strong>read (RECOMMENDED)</strong></p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { open, close } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-title function_">open</span>(<span class="hljs-string">'myfile'</span>, <span class="hljs-string">'r'</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) {
    <span class="hljs-keyword">if</span> (err.<span class="hljs-property">code</span> === <span class="hljs-string">'ENOENT'</span>) {
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'myfile does not exist'</span>);
      <span class="hljs-keyword">return</span>;
    }

    <span class="hljs-keyword">throw</span> err;
  }

  <span class="hljs-keyword">try</span> {
    <span class="hljs-title function_">readMyData</span>(fd);
  } <span class="hljs-keyword">finally</span> {
    <span class="hljs-title function_">close</span>(fd, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
      <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
    });
  }
});</code> <button class="copy-button">copy</button></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>
<h4><code>fs.fchmod(fd, mode, callback)</code><span><a class="mark" href="#all_fs_fsfchmodfd-mode-callback" id="all_fs_fsfchmodfd-mode-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_fchmod_fd_mode_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</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.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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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>Sets the permissions on the file. No arguments other than a possible exception
are given to the completion callback.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/fchmod.2.html"><code>fchmod(2)</code></a> documentation for more detail.</p>
<h4><code>fs.fchown(fd, uid, gid, callback)</code><span><a class="mark" href="#all_fs_fsfchownfd-uid-gid-callback" id="all_fs_fsfchownfd-uid-gid-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_fchown_fd_uid_gid_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</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.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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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>Sets the owner of the file. No arguments other than a possible exception are
given to the completion callback.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/fchown.2.html"><code>fchown(2)</code></a> documentation for more detail.</p>
<h4><code>fs.fdatasync(fd, callback)</code><span><a class="mark" href="#all_fs_fsfdatasyncfd-callback" id="all_fs_fsfdatasyncfd-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_fdatasync_fd_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</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.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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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>Forces all currently queued I/O operations associated with the file to the
operating system's synchronized I/O completion state. Refer to the POSIX
<a href="http://man7.org/linux/man-pages/man2/fdatasync.2.html"><code>fdatasync(2)</code></a> documentation for details. No arguments other than a possible
exception are given to the completion callback.</p>
<h4><code>fs.fstat(fd[, options], callback)</code><span><a class="mark" href="#all_fs_fsfstatfd-options-callback" id="all_fs_fsfstatfd-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_fstat_fd_options_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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="#all_fs_class-fsstats" class="type">&#x3C;fs.Stats></a> object should be <code>bigint</code>. <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>
<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="#all_fs_class-fsstats" class="type">&#x3C;fs.Stats></a></li>
</ul>
</li>
</ul>
<p>Invokes the callback with the <a href="#all_fs_class-fsstats" class="type">&#x3C;fs.Stats></a> for the file descriptor.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/fstat.2.html"><code>fstat(2)</code></a> documentation for more detail.</p>
<h4><code>fs.fsync(fd, callback)</code><span><a class="mark" href="#all_fs_fsfsyncfd-callback" id="all_fs_fsfsyncfd-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_fsync_fd_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</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.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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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>Request that all data for the open file descriptor is flushed to the storage
device. The specific implementation is operating system and device specific.
Refer to the POSIX <a href="http://man7.org/linux/man-pages/man2/fsync.2.html"><code>fsync(2)</code></a> documentation for more detail. No arguments other
than a possible exception are given to the completion callback.</p>
<h4><code>fs.ftruncate(fd[, len], callback)</code><span><a class="mark" href="#all_fs_fsftruncatefd-len-callback" id="all_fs_fsftruncatefd-len-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_ftruncate_fd_len_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</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.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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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>Truncates the file descriptor. No arguments other than a possible exception are
given to the completion callback.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/ftruncate.2.html"><code>ftruncate(2)</code></a> documentation for more detail.</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 mjs"><span class="hljs-keyword">import</span> { open, close, ftruncate } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-keyword">function</span> <span class="hljs-title function_">closeFd</span>(<span class="hljs-params">fd</span>) {
  <span class="hljs-title function_">close</span>(fd, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
    <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  });
}

<span class="hljs-title function_">open</span>(<span class="hljs-string">'temp.txt'</span>, <span class="hljs-string">'r+'</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;

  <span class="hljs-keyword">try</span> {
    <span class="hljs-title function_">ftruncate</span>(fd, <span class="hljs-number">4</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
      <span class="hljs-title function_">closeFd</span>(fd);
      <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
    });
  } <span class="hljs-keyword">catch</span> (err) {
    <span class="hljs-title function_">closeFd</span>(fd);
    <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  }
});</code> <button class="copy-button">copy</button></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>
<p>If <code>len</code> is negative then <code>0</code> will be used.</p>
<h4><code>fs.futimes(fd, atime, mtime, callback)</code><span><a class="mark" href="#all_fs_fsfutimesfd-atime-mtime-callback" id="all_fs_fsfutimesfd-atime-mtime-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_futimes_fd_atime_mtime_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</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.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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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="#all_fs_fsutimespath-atime-mtime-callback"><code>fs.utimes()</code></a>.</p>
<h4><code>fs.lchmod(path, mode, callback)</code><span><a class="mark" href="#all_fs_fslchmodpath-mode-callback" id="all_fs_fslchmodpath-mode-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_lchmod_path_mode_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p>The error returned may be an <code>AggregateError</code> if more than one error is returned.</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.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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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/Reference/Global_Objects/AggregateError" class="type">&#x3C;AggregateError></a></li>
</ul>
</li>
</ul>
<p>Changes the permissions on a symbolic link. No arguments other than a possible
exception are given to the completion callback.</p>
<p>This method is only implemented on macOS.</p>
<p>See the POSIX <a href="https://www.freebsd.org/cgi/man.cgi?query=lchmod&#x26;sektion=2"><code>lchmod(2)</code></a> documentation for more detail.</p>
<h4><code>fs.lchown(path, uid, gid, callback)</code><span><a class="mark" href="#all_fs_fslchownpath-uid-gid-callback" id="all_fs_fslchownpath-uid-gid-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_lchown_path_uid_gid_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></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>
<tr><td>v0.4.7</td>
<td><p>Documentation-only deprecation.</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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>Set the owner of the symbolic link. No arguments other than a possible
exception are given to the completion callback.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/lchown.2.html"><code>lchown(2)</code></a> documentation for more detail.</p>
<h4><code>fs.lutimes(path, atime, mtime, callback)</code><span><a class="mark" href="#all_fs_fslutimespath-atime-mtime-callback" id="all_fs_fslutimespath-atime-mtime-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_lutimes_path_atime_mtime_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></tr>
<tr><td>v14.5.0, v12.19.0</td>
<td><p><span>Added in: v14.5.0, v12.19.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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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>Changes the access and modification times of a file in the same way as
<a href="#all_fs_fsutimespath-atime-mtime-callback"><code>fs.utimes()</code></a>, with the difference that if the path refers to a symbolic
link, then the link is not dereferenced: instead, the timestamps of the
symbolic link itself are changed.</p>
<p>No arguments other than a possible exception are given to the completion
callback.</p>
<h4><code>fs.link(existingPath, newPath, callback)</code><span><a class="mark" href="#all_fs_fslinkexistingpath-newpath-callback" id="all_fs_fslinkexistingpath-newpath-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_link_existingpath_newpath_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</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.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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></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>
<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>Creates a new link from the <code>existingPath</code> to the <code>newPath</code>. See the POSIX
<a href="http://man7.org/linux/man-pages/man2/link.2.html"><code>link(2)</code></a> documentation for more detail. No arguments other than a possible
exception are given to the completion callback.</p>
<h4><code>fs.lstat(path[, options], callback)</code><span><a class="mark" href="#all_fs_fslstatpath-options-callback" id="all_fs_fslstatpath-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_lstat_path_options_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></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.</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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>
<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="#all_fs_class-fsstats" class="type">&#x3C;fs.Stats></a> object should be <code>bigint</code>. <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>
<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="#all_fs_class-fsstats" class="type">&#x3C;fs.Stats></a></li>
</ul>
</li>
</ul>
<p>Retrieves the <a href="#all_fs_class-fsstats" class="type">&#x3C;fs.Stats></a> for the symbolic link referred to by the path.
The callback gets two arguments <code>(err, stats)</code> where <code>stats</code> is a <a href="#all_fs_class-fsstats" class="type">&#x3C;fs.Stats></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>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/lstat.2.html"><code>lstat(2)</code></a> documentation for more details.</p>
<h4><code>fs.mkdir(path[, options], callback)</code><span><a class="mark" href="#all_fs_fsmkdirpath-options-callback" id="all_fs_fsmkdirpath-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_mkdir_path_options_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></tr>
<tr><td>v13.11.0, 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.</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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#Number_type" class="type">&#x3C;integer></a>
<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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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>path</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#Undefined_type" class="type">&#x3C;undefined></a> Present only if a directory is created with
<code>recursive</code> set to <code>true</code>.</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>.
<code>path</code> can still be <code>undefined</code> when <code>recursive</code> is <code>true</code>, if no directory was
created (for instance, if it was previously created).</p>
<p>The optional <code>options</code> argument can be an integer specifying <code>mode</code> (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. If <code>recursive</code> is false and the directory exists,
an <code>EEXIST</code> error occurs.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { mkdir } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-comment">// Create ./tmp/a/apple, regardless of whether ./tmp and ./tmp/a exist.</span>
<span class="hljs-title function_">mkdir</span>(<span class="hljs-string">'./tmp/a/apple'</span>, { <span class="hljs-attr">recursive</span>: <span class="hljs-literal">true</span> }, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
});</code> <button class="copy-button">copy</button></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 mjs"><span class="hljs-keyword">import</span> { mkdir } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-title function_">mkdir</span>(<span class="hljs-string">'/'</span>, { <span class="hljs-attr">recursive</span>: <span class="hljs-literal">true</span> }, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-comment">// => [Error: EPERM: operation not permitted, mkdir 'C:\']</span>
});</code> <button class="copy-button">copy</button></pre>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/mkdir.2.html"><code>mkdir(2)</code></a> documentation for more details.</p>
<h4><code>fs.mkdtemp(prefix[, options], callback)</code><span><a class="mark" href="#all_fs_fsmkdtempprefix-options-callback" id="all_fs_fsmkdtempprefix-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_mkdtemp_prefix_options_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.6.0</td>
<td><p>The <code>prefix</code> parameter now accepts buffers and URL.</p></td></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></tr>
<tr><td>v16.5.0, v14.18.0</td>
<td><p>The <code>prefix</code> parameter now accepts an empty string.</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>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> | <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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/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>
<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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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 mjs"><span class="hljs-keyword">import</span> { mkdtemp } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">import</span> { join } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:path'</span>;
<span class="hljs-keyword">import</span> { tmpdir } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:os'</span>;

<span class="hljs-title function_">mkdtemp</span>(<span class="hljs-title function_">join</span>(<span class="hljs-title function_">tmpdir</span>(), <span class="hljs-string">'foo-'</span>), <span class="hljs-function">(<span class="hljs-params">err, directory</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(directory);
  <span class="hljs-comment">// Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2</span>
});</code> <button class="copy-button">copy</button></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('node:path').sep</code>).</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { tmpdir } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:os'</span>;
<span class="hljs-keyword">import</span> { mkdtemp } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-comment">// The parent directory for the new temporary directory</span>
<span class="hljs-keyword">const</span> tmpDir = <span class="hljs-title function_">tmpdir</span>();

<span class="hljs-comment">// This method is *INCORRECT*:</span>
<span class="hljs-title function_">mkdtemp</span>(tmpDir, <span class="hljs-function">(<span class="hljs-params">err, directory</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(directory);
  <span class="hljs-comment">// Will print something similar to `/tmpabc123`.</span>
  <span class="hljs-comment">// A new temporary directory is created at the file system root</span>
  <span class="hljs-comment">// rather than *within* the /tmp directory.</span>
});

<span class="hljs-comment">// This method is *CORRECT*:</span>
<span class="hljs-keyword">import</span> { sep } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:path'</span>;
<span class="hljs-title function_">mkdtemp</span>(<span class="hljs-string">`<span class="hljs-subst">${tmpDir}</span><span class="hljs-subst">${sep}</span>`</span>, <span class="hljs-function">(<span class="hljs-params">err, directory</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(directory);
  <span class="hljs-comment">// Will print something similar to `/tmp/abc123`.</span>
  <span class="hljs-comment">// A new temporary directory is created within</span>
  <span class="hljs-comment">// the /tmp directory.</span>
});</code> <button class="copy-button">copy</button></pre>
<h4><code>fs.open(path[, flags[, mode]], callback)</code><span><a class="mark" href="#all_fs_fsopenpath-flags-mode-callback" id="all_fs_fsopenpath-flags-mode-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_open_path_flags_mode_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></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> flags 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.</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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="#all_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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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 the POSIX <a href="http://man7.org/linux/man-pages/man2/open.2.html"><code>open(2)</code></a> documentation for more details.</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="#all_fs_fschmodpath-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>
<h4><code>fs.openAsBlob(path[, options])</code><span><a class="mark" href="#all_fs_fsopenasblobpath-options" id="all_fs_fsopenasblobpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_openasblob_path_options"></a></h4>
<div class="api_metadata">
<span>Added in: v19.8.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - 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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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>
<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> An optional mime type for the blob.</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> Fulfills with a <a href="#all_buffer_class-blob" class="type">&#x3C;Blob></a> upon success.</li>
</ul>
<p>Returns a <a href="#all_buffer_class-blob" class="type">&#x3C;Blob></a> whose data is backed by the given file.</p>
<p>The file must not be modified after the <a href="#all_buffer_class-blob" class="type">&#x3C;Blob></a> is created. Any modifications
will cause reading the <a href="#all_buffer_class-blob" class="type">&#x3C;Blob></a> data to fail with a <code>DOMException</code> error.
Synchronous stat operations on the file when the <code>Blob</code> is created, and before
each read in order to detect whether the file data has been modified on disk.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { openAsBlob } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-keyword">const</span> blob = <span class="hljs-keyword">await</span> <span class="hljs-title function_">openAsBlob</span>(<span class="hljs-string">'the.file.txt'</span>);
<span class="hljs-keyword">const</span> ab = <span class="hljs-keyword">await</span> blob.<span class="hljs-title function_">arrayBuffer</span>();
blob.<span class="hljs-title function_">stream</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { openAsBlob } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);

(<span class="hljs-keyword">async</span> () => {
  <span class="hljs-keyword">const</span> blob = <span class="hljs-keyword">await</span> <span class="hljs-title function_">openAsBlob</span>(<span class="hljs-string">'the.file.txt'</span>);
  <span class="hljs-keyword">const</span> ab = <span class="hljs-keyword">await</span> blob.<span class="hljs-title function_">arrayBuffer</span>();
  blob.<span class="hljs-title function_">stream</span>();
})();</code><button class="copy-button">copy</button></pre>
<h4><code>fs.opendir(path[, options], callback)</code><span><a class="mark" href="#all_fs_fsopendirpath-options-callback" id="all_fs_fsopendirpath-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_opendir_path_options_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.1.0</td>
<td><p>Added <code>recursive</code> option.</p></td></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></tr>
<tr><td>v13.1.0, 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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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>
<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>
<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>
</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>
<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="#all_fs_class-fsdir" class="type">&#x3C;fs.Dir></a></li>
</ul>
</li>
</ul>
<p>Asynchronously open a directory. See the POSIX <a href="http://man7.org/linux/man-pages/man3/opendir.3.html"><code>opendir(3)</code></a> documentation for
more details.</p>
<p>Creates an <a href="#all_fs_class-fsdir" class="type">&#x3C;fs.Dir></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>
<h4><code>fs.read(fd, buffer, offset, length, position, callback)</code><span><a class="mark" href="#all_fs_fsreadfd-buffer-offset-length-position-callback" id="all_fs_fsreadfd-buffer-offset-length-position-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_read_fd_buffer_offset_length_position_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></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="#all_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 buffer that the data will be
written to.</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> The position in <code>buffer</code> to write the data to.</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> The number of bytes to read.</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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type">&#x3C;bigint></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a> Specifies where to begin reading from in the
file. If <code>position</code> is <code>null</code> or <code>-1 </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 be unchanged.</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>
<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="#all_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>The callback is given the three arguments, <code>(err, bytesRead, buffer)</code>.</p>
<p>If the file is not modified concurrently, the end-of-file is reached when the
number of bytes read is zero.</p>
<p>If this method is invoked as its <a href="#all_util_utilpromisifyoriginal"><code>util.promisify()</code></a>ed version, it returns
a promise for an <code>Object</code> with <code>bytesRead</code> and <code>buffer</code> properties.</p>
<p>The <code>fs.read()</code> method reads data from the file specified
by the file descriptor (<code>fd</code>).
The <code>length</code> argument indicates the maximum number
of bytes that Node.js
will attempt to read from the kernel.
However, the actual number of bytes read (<code>bytesRead</code>) can be lower
than the specified <code>length</code> for various reasons.</p>
<p>For example:</p>
<ul>
<li>If the file is shorter than the specified <code>length</code>, <code>bytesRead</code>
will be set to the actual number of bytes read.</li>
<li>If the file encounters EOF (End of File) before the buffer could
be filled, Node.js will read all available bytes until EOF is encountered,
and the <code>bytesRead</code> parameter in the callback will indicate
the actual number of bytes read, which may be less than the specified <code>length</code>.</li>
<li>If the file is on a slow network <code>filesystem</code>
or encounters any other issue during reading,
<code>bytesRead</code> can be lower than the specified <code>length</code>.</li>
</ul>
<p>Therefore, when using <code>fs.read()</code>, it's important to
check the <code>bytesRead</code> value to
determine how many bytes were actually read from the file.
Depending on your application
logic, you may need to handle cases where <code>bytesRead</code>
is lower than the specified <code>length</code>,
such as by wrapping the read call in a loop if you require
a minimum amount of bytes.</p>
<p>This behavior is similar to the POSIX <code>preadv2</code> function.</p>
<h4><code>fs.read(fd[, options], callback)</code><span><a class="mark" href="#all_fs_fsreadfd-options-callback" id="all_fs_fsreadfd-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_read_fd_options_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.11.0, 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>v13.11.0, v12.17.0</td>
<td><p><span>Added in: v13.11.0, 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>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>buffer</code> <a href="#all_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.byteLength - offset</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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type">&#x3C;bigint></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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a></li>
</ul>
</li>
</ul>
<p>Similar to the <a href="#all_fs_fsreadfd-buffer-offset-length-position-callback"><code>fs.read()</code></a> 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>
<h4><code>fs.read(fd, buffer[, options], callback)</code><span><a class="mark" href="#all_fs_fsreadfd-buffer-options-callback" id="all_fs_fsreadfd-buffer-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_read_fd_buffer_options_callback"></a></h4>
<div class="api_metadata">
<span>Added in: v18.2.0, v16.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>buffer</code> <a href="#all_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 buffer that the data will be
written to.</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>
<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.byteLength - offset</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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type">&#x3C;bigint></a> <strong>Default:</strong> <code>null</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>
<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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a></li>
</ul>
</li>
</ul>
<p>Similar to the <a href="#all_fs_fsreadfd-buffer-offset-length-position-callback"><code>fs.read()</code></a> 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>
<h4><code>fs.readdir(path[, options], callback)</code><span><a class="mark" href="#all_fs_fsreaddirpath-options-callback" id="all_fs_fsreaddirpath-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_readdir_path_options_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.1.0</td>
<td><p>Added <code>recursive</code> option.</p></td></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></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.</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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/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>
<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>
<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>, reads the contents of a directory
recursively. In recursive mode, it will list all files, sub files and
directories. <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>
<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="#all_buffer_class-buffer" class="type">&#x3C;Buffer[]></a> | <a href="#all_fs_class-fsdirent" class="type">&#x3C;fs.Dirent[]></a></li>
</ul>
</li>
</ul>
<p>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>See the POSIX <a href="http://man7.org/linux/man-pages/man3/readdir.3.html"><code>readdir(3)</code></a> documentation for more details.</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 <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> objects.</p>
<p>If <code>options.withFileTypes</code> is set to <code>true</code>, the <code>files</code> array will contain
<a href="#all_fs_class-fsdirent" class="type">&#x3C;fs.Dirent></a> objects.</p>
<h4><code>fs.readFile(path[, options], callback)</code><span><a class="mark" href="#all_fs_fsreadfilepath-options-callback" id="all_fs_fsreadfilepath-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_readfile_path_options_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p>The error returned may be an <code>AggregateError</code> if more than one error is returned.</p></td></tr>
<tr><td>v15.2.0, v14.17.0</td>
<td><p>The options argument may include an AbortSignal to abort an ongoing readFile request.</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.</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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>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>
<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="#all_fs_file-system-flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'r'</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> allows aborting an in-progress readFile</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>
<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/Reference/Global_Objects/AggregateError" class="type">&#x3C;AggregateError></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="#all_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 mjs"><span class="hljs-keyword">import</span> { readFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-title function_">readFile</span>(<span class="hljs-string">'/etc/passwd'</span>, <span class="hljs-function">(<span class="hljs-params">err, data</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data);
});</code> <button class="copy-button">copy</button></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 mjs"><span class="hljs-keyword">import</span> { readFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-title function_">readFile</span>(<span class="hljs-string">'/etc/passwd'</span>, <span class="hljs-string">'utf8'</span>, callback);</code> <button class="copy-button">copy</button></pre>
<p>When the path is a directory, the behavior of <code>fs.readFile()</code> and
<a href="#all_fs_fsreadfilesyncpath-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 mjs"><span class="hljs-keyword">import</span> { readFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-comment">// macOS, Linux, and Windows</span>
<span class="hljs-title function_">readFile</span>(<span class="hljs-string">'&#x3C;directory>'</span>, <span class="hljs-function">(<span class="hljs-params">err, data</span>) =></span> {
  <span class="hljs-comment">// => [Error: EISDIR: illegal operation on a directory, read &#x3C;directory>]</span>
});

<span class="hljs-comment">//  FreeBSD</span>
<span class="hljs-title function_">readFile</span>(<span class="hljs-string">'&#x3C;directory>'</span>, <span class="hljs-function">(<span class="hljs-params">err, data</span>) =></span> {
  <span class="hljs-comment">// => null, &#x3C;data></span>
});</code> <button class="copy-button">copy</button></pre>
<p>It is possible to abort an ongoing request using an <code>AbortSignal</code>. If a
request is aborted the callback is called with an <code>AbortError</code>:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { readFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-keyword">const</span> controller = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
<span class="hljs-keyword">const</span> signal = controller.<span class="hljs-property">signal</span>;
<span class="hljs-title function_">readFile</span>(fileInfo[<span class="hljs-number">0</span>].<span class="hljs-property">name</span>, { signal }, <span class="hljs-function">(<span class="hljs-params">err, buf</span>) =></span> {
  <span class="hljs-comment">// ...</span>
});
<span class="hljs-comment">// When you want to abort the request</span>
controller.<span class="hljs-title function_">abort</span>();</code> <button class="copy-button">copy</button></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>
<p>Aborting an ongoing request does not abort individual operating
system requests but rather the internal buffering <code>fs.readFile</code> performs.</p>
<h5>File descriptors<span><a class="mark" href="#all_fs_file-descriptors" id="all_fs_file-descriptors">#</a></span><a aria-hidden="true" class="legacy" id="fs_file_descriptors"></a></h5>
<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>
<h5>Performance Considerations<span><a class="mark" href="#all_fs_performance-considerations" id="all_fs_performance-considerations">#</a></span><a aria-hidden="true" class="legacy" id="fs_performance_considerations"></a></h5>
<p>The <code>fs.readFile()</code> method asynchronously reads the contents of a file into
memory one chunk at a time, allowing the event loop to turn between each chunk.
This allows the read operation to have less impact on other activity that may
be using the underlying libuv thread pool but means that it will take longer
to read a complete file into memory.</p>
<p>The additional read overhead can vary broadly on different systems and depends
on the type of file being read. If the file type is not a regular file (a pipe
for instance) and Node.js is unable to determine an actual file size, each read
operation will load on 64 KiB of data. For regular files, each read will process
512 KiB of data.</p>
<p>For applications that require as-fast-as-possible reading of file contents, it
is better to use <code>fs.read()</code> directly and for application code to manage
reading the full contents of the file itself.</p>
<p>The Node.js GitHub issue <a href="https://github.com/nodejs/node/issues/25741">#25741</a> provides more information and a detailed
analysis on the performance of <code>fs.readFile()</code> for multiple file sizes in
different Node.js versions.</p>
<h4><code>fs.readlink(path[, options], callback)</code><span><a class="mark" href="#all_fs_fsreadlinkpath-options-callback" id="all_fs_fsreadlinkpath-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_readlink_path_options_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</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.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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/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>
<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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a></li>
</ul>
</li>
</ul>
<p>Reads the contents of the symbolic link referred to by <code>path</code>. The callback gets
two arguments <code>(err, linkString)</code>.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/readlink.2.html"><code>readlink(2)</code></a> documentation for more details.</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 <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> object.</p>
<h4><code>fs.readv(fd, buffers[, position], callback)</code><span><a class="mark" href="#all_fs_fsreadvfd-buffers-position-callback" id="all_fs_fsreadvfd-buffers-position-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_readv_fd_buffers_position_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></tr>
<tr><td>v13.13.0, v12.17.0</td>
<td><p><span>Added in: v13.13.0, 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>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> | <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>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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="#all_util_utilpromisifyoriginal"><code>util.promisify()</code></a>ed version, it returns
a promise for an <code>Object</code> with <code>bytesRead</code> and <code>buffers</code> properties.</p>
<h4><code>fs.realpath(path[, options], callback)</code><span><a class="mark" href="#all_fs_fsrealpathpath-options-callback" id="all_fs_fsrealpathpath-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_realpath_path_options_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</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>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.</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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/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>
<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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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="#all_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 <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> 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>
<p>A path that does not exist results in an ENOENT error.
<code>error.path</code> is the absolute file path.</p>
<h4><code>fs.realpath.native(path[, options], callback)</code><span><a class="mark" href="#all_fs_fsrealpathnativepath-options-callback" id="all_fs_fsrealpathnativepath-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_realpath_native_path_options_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></tr>
<tr><td>v9.2.0</td>
<td><p><span>Added in: v9.2.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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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/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>
<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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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="#all_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 <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> 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>
<h4><code>fs.rename(oldPath, newPath, callback)</code><span><a class="mark" href="#all_fs_fsrenameoldpath-newpath-callback" id="all_fs_fsrenameoldpath-newpath-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_rename_oldpath_newpath_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</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.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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></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>
<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 mjs"><span class="hljs-keyword">import</span> { rename } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-title function_">rename</span>(<span class="hljs-string">'oldFile.txt'</span>, <span class="hljs-string">'newFile.txt'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Rename complete!'</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4><code>fs.rmdir(path[, options], callback)</code><span><a class="mark" href="#all_fs_fsrmdirpath-options-callback" id="all_fs_fsrmdirpath-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_rmdir_path_options_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p>Using <code>fs.rmdir(path, { recursive: true })</code> on a <code>path</code> that is a file is no longer permitted and results in an <code>ENOENT</code> error on Windows and an <code>ENOTDIR</code> error on POSIX.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p>Using <code>fs.rmdir(path, { recursive: true })</code> on a <code>path</code> that does not exist is no longer permitted and results in a <code>ENOENT</code> error.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p>The <code>recursive</code> option is deprecated, using it triggers a deprecation warning.</p></td></tr>
<tr><td>v14.14.0</td>
<td><p>The <code>recursive</code> option is deprecated, use <code>fs.rm</code> instead.</p></td></tr>
<tr><td>v13.3.0, 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.</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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>
<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 retries the operation with a linear
backoff wait of <code>retryDelay</code> milliseconds 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, operations are retried on failure. <strong>Default:</strong> <code>false</code>.
<strong>Deprecated.</strong></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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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>
<p>To get a behavior similar to the <code>rm -rf</code> Unix command, use <a href="#all_fs_fsrmpath-options-callback"><code>fs.rm()</code></a>
with options <code>{ recursive: true, force: true }</code>.</p>
<h4><code>fs.rm(path[, options], callback)</code><span><a class="mark" href="#all_fs_fsrmpath-options-callback" id="all_fs_fsrmpath-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_rm_path_options_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.3.0, v16.14.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v14.14.0</td>
<td><p><span>Added in: v14.14.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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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>
<ul>
<li><code>force</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>, exceptions will be ignored if <code>path</code> does
not exist. <strong>Default:</strong> <code>false</code>.</li>
<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> milliseconds 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 removal. In
recursive mode 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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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 files and directories (modeled on the standard POSIX <code>rm</code>
utility). No arguments other than a possible exception are given to the
completion callback.</p>
<h4><code>fs.stat(path[, options], callback)</code><span><a class="mark" href="#all_fs_fsstatpath-options-callback" id="all_fs_fsstatpath-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_stat_path_options_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></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.</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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>
<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="#all_fs_class-fsstats" class="type">&#x3C;fs.Stats></a> object should be <code>bigint</code>. <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>
<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="#all_fs_class-fsstats" 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="#all_fs_class-fsstats" class="type">&#x3C;fs.Stats></a> object.</p>
<p>In case of an error, the <code>err.code</code> will be one of <a href="#all_errors_common-system-errors">Common System Errors</a>.</p>
<p><a href="#all_fs_fsstatpath-options-callback"><code>fs.stat()</code></a> follows symbolic links. Use <a href="#all_fs_fslstatpath-options-callback"><code>fs.lstat()</code></a> to look at the
links themselves.</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="#all_fs_fsaccesspath-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> <button class="copy-button">copy</button></pre>
<p>The next program will check for the stats of the given paths:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { stat } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-keyword">const</span> pathsToCheck = [<span class="hljs-string">'./txtDir'</span>, <span class="hljs-string">'./txtDir/file.txt'</span>];

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; pathsToCheck.<span class="hljs-property">length</span>; i++) {
  <span class="hljs-title function_">stat</span>(pathsToCheck[i], <span class="hljs-function">(<span class="hljs-params">err, stats</span>) =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(stats.<span class="hljs-title function_">isDirectory</span>());
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(stats);
  });
}</code> <button class="copy-button">copy</button></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> <button class="copy-button">copy</button></pre>
<h4><code>fs.statfs(path[, options], callback)</code><span><a class="mark" href="#all_fs_fsstatfspath-options-callback" id="all_fs_fsstatfspath-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_statfs_path_options_callback"></a></h4>
<div class="api_metadata">
<span>Added in: v19.6.0, v18.15.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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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>
<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="#all_fs_class-fsstatfs" class="type">&#x3C;fs.StatFs></a> object should be <code>bigint</code>. <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>
<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="#all_fs_class-fsstatfs" class="type">&#x3C;fs.StatFs></a></li>
</ul>
</li>
</ul>
<p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/statfs.2.html"><code>statfs(2)</code></a>. Returns information about the mounted file system which
contains <code>path</code>. The callback gets two arguments <code>(err, stats)</code> where <code>stats</code>
is an <a href="#all_fs_class-fsstatfs" class="type">&#x3C;fs.StatFs></a> object.</p>
<p>In case of an error, the <code>err.code</code> will be one of <a href="#all_errors_common-system-errors">Common System Errors</a>.</p>
<h4><code>fs.symlink(target, path[, type], callback)</code><span><a class="mark" href="#all_fs_fssymlinktarget-path-type-callback" id="all_fs_fssymlinktarget-path-type-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_symlink_target_path_type_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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> | <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>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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>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>See the POSIX <a href="http://man7.org/linux/man-pages/man2/symlink.2.html"><code>symlink(2)</code></a> documentation for more details.</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 a string, 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. Junction
points on NTFS volumes can only point to directories.</p>
<p>Relative targets are relative to the link's parent directory.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { symlink } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-title function_">symlink</span>(<span class="hljs-string">'./mew'</span>, <span class="hljs-string">'./mewtwo'</span>, callback);</code> <button class="copy-button">copy</button></pre>
<p>The above example creates a symbolic link <code>mewtwo</code> which points to <code>mew</code> in the
same directory:</p>
<pre><code class="language-bash">$ tree .
.
├── mew
└── mewtwo -> ./mew</code> <button class="copy-button">copy</button></pre>
<h4><code>fs.truncate(path[, len], callback)</code><span><a class="mark" href="#all_fs_fstruncatepath-len-callback" id="all_fs_fstruncatepath-len-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_truncate_path_len_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p>The error returned may be an <code>AggregateError</code> if more than one error is returned.</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.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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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/Reference/Global_Objects/AggregateError" class="type">&#x3C;AggregateError></a></li>
</ul>
</li>
</ul>
<p>Truncates the file. 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>

<pre class="with-51-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { truncate } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-comment">// Assuming that 'path/file.txt' is a regular file.</span>
<span class="hljs-title function_">truncate</span>(<span class="hljs-string">'path/file.txt'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'path/file.txt was truncated'</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { truncate } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-comment">// Assuming that 'path/file.txt' is a regular file.</span>
<span class="hljs-title function_">truncate</span>(<span class="hljs-string">'path/file.txt'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'path/file.txt was truncated'</span>);
});</code><button class="copy-button">copy</button></pre>
<p>Passing a file descriptor is deprecated and may result in an error being thrown
in the future.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/truncate.2.html"><code>truncate(2)</code></a> documentation for more details.</p>
<h4><code>fs.unlink(path, callback)</code><span><a class="mark" href="#all_fs_fsunlinkpath-callback" id="all_fs_fsunlinkpath-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_unlink_path_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</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.6.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></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>
<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 mjs"><span class="hljs-keyword">import</span> { unlink } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-comment">// Assuming that 'path/file.txt' is a regular file.</span>
<span class="hljs-title function_">unlink</span>(<span class="hljs-string">'path/file.txt'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'path/file.txt was deleted'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p><code>fs.unlink()</code> will not work on a directory, empty or otherwise. To remove a
directory, use <a href="#all_fs_fsrmdirpath-options-callback"><code>fs.rmdir()</code></a>.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/unlink.2.html"><code>unlink(2)</code></a> documentation for more details.</p>
<h4><code>fs.unwatchFile(filename[, listener])</code><span><a class="mark" href="#all_fs_fsunwatchfilefilename-listener" id="all_fs_fsunwatchfilefilename-listener">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_unwatchfile_filename_listener"></a></h4>
<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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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="#all_fs_fswatchfilename-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>
<h4><code>fs.utimes(path, atime, mtime, callback)</code><span><a class="mark" href="#all_fs_fsutimespath-atime-mtime-callback" id="all_fs_fsutimespath-atime-mtime-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_utimes_path_atime_mtime_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</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>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.</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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>
<h4><code>fs.watch(filename[, options][, listener])</code><span><a class="mark" href="#all_fs_fswatchfilename-options-listener" id="all_fs_fswatchfilename-options-listener">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_watch_filename_options_listener"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.1.0</td>
<td><p>Added recursive support for Linux, AIX and IBMi.</p></td></tr>
<tr><td>v15.9.0, v14.17.0</td>
<td><p>Added support for closing the watcher with an AbortSignal.</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.</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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/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>
<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="#all_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>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> allows closing the watcher with an AbortSignal.</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> | <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>
<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="#all_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></li>
</ul>
</li>
<li>Returns: <a href="#all_fs_class-fsfswatcher" 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="#all_fs_class-fsfswatcher" class="type">&#x3C;fs.FSWatcher></a>, but it is not the same thing as the <code>'change'</code> value of
<code>eventType</code>.</p>
<p>If a <code>signal</code> is passed, aborting the corresponding AbortController will close
the returned <a href="#all_fs_class-fsfswatcher" class="type">&#x3C;fs.FSWatcher></a>.</p>
<h5>Caveats<span><a class="mark" href="#all_fs_caveats" id="all_fs_caveats">#</a></span><a aria-hidden="true" class="legacy" id="fs_caveats"></a></h5>

<p>The <code>fs.watch</code> API is not 100% consistent across platforms, and is
unavailable in some situations.</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>
<h6>Availability<span><a class="mark" href="#all_fs_availability" id="all_fs_availability">#</a></span><a aria-hidden="true" class="legacy" id="fs_availability"></a></h6>

<p>This feature depends on the underlying operating system providing a way
to be notified of file system changes.</p>
<ul>
<li>On Linux systems, this uses <a href="https://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://developer.ibm.com/articles/au-aix_event_infrastructure/"><code>AHAFS</code></a>, which must be enabled.</li>
<li>On IBM i systems, this feature is not supported.</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 throw 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>
<h6>Inodes<span><a class="mark" href="#all_fs_inodes" id="all_fs_inodes">#</a></span><a aria-hidden="true" class="legacy" id="fs_inodes"></a></h6>

<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>
<h6>Filename argument<span><a class="mark" href="#all_fs_filename-argument" id="all_fs_filename-argument">#</a></span><a aria-hidden="true" class="legacy" id="fs_filename_argument"></a></h6>

<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 mjs"><span class="hljs-keyword">import</span> { watch } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-title function_">watch</span>(<span class="hljs-string">'somedir'</span>, <span class="hljs-function">(<span class="hljs-params">eventType, filename</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`event type is: <span class="hljs-subst">${eventType}</span>`</span>);
  <span class="hljs-keyword">if</span> (filename) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`filename provided: <span class="hljs-subst">${filename}</span>`</span>);
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'filename not provided'</span>);
  }
});</code> <button class="copy-button">copy</button></pre>
<h4><code>fs.watchFile(filename[, options], listener)</code><span><a class="mark" href="#all_fs_fswatchfilefilename-options-listener" id="all_fs_fswatchfilefilename-options-listener">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_watchfile_filename_options_listener"></a></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>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.</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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>
<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><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<ul>
<li><code>current</code> <a href="#all_fs_class-fsstats" class="type">&#x3C;fs.Stats></a></li>
<li><code>previous</code> <a href="#all_fs_class-fsstats" class="type">&#x3C;fs.Stats></a></li>
</ul>
</li>
<li>Returns: <a href="#all_fs_class-fsstatwatcher" class="type">&#x3C;fs.StatWatcher></a></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 mjs"><span class="hljs-keyword">import</span> { watchFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-title function_">watchFile</span>(<span class="hljs-string">'message.text'</span>, <span class="hljs-function">(<span class="hljs-params">curr, prev</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`the current mtime is: <span class="hljs-subst">${curr.mtime}</span>`</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`the previous mtime was: <span class="hljs-subst">${prev.mtime}</span>`</span>);
});</code> <button class="copy-button">copy</button></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.mtimeMs</code> and <code>prev.mtimeMs</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="#all_fs_fswatchfilename-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 contents of <code>previous</code> in the second callback event (the file's
reappearance) will be the same as the contents of <code>previous</code> in 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>
<h4><code>fs.write(fd, buffer, offset[, length[, position]], callback)</code><span><a class="mark" href="#all_fs_fswritefd-buffer-offset-length-position-callback" id="all_fs_fswritefd-buffer-offset-length-position-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_write_fd_buffer_offset_length_position_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>The <code>buffer</code> parameter won't coerce unsupported input to strings anymore.</p></td></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="#all_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> <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.byteLength - offset</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> | <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>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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="#all_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="#all_util_utilpromisifyoriginal"><code>util.promisify()</code></a>ed version, it returns
a promise 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="#all_fs_fscreatewritestreampath-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>
<h4><code>fs.write(fd, buffer[, options], callback)</code><span><a class="mark" href="#all_fs_fswritefd-buffer-options-callback" id="all_fs_fswritefd-buffer-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_write_fd_buffer_options_callback"></a></h4>
<div class="api_metadata">
<span>Added in: v18.3.0, v16.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>buffer</code> <a href="#all_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>
<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.byteLength - offset</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><code>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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="#all_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>Similar to the above <code>fs.write</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>
<h4><code>fs.write(fd, string[, position[, encoding]], callback)</code><span><a class="mark" href="#all_fs_fswritefd-string-position-encoding-callback" id="all_fs_fswritefd-string-position-encoding-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_write_fd_string_position_encoding_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>Passing to the <code>string</code> parameter an object with an own <code>toString</code> function is no longer supported.</p></td></tr>
<tr><td>v17.8.0</td>
<td><p>Passing to the <code>string</code> parameter an object with an own <code>toString</code> function is deprecated.</p></td></tr>
<tr><td>v14.12.0</td>
<td><p>The <code>string</code> parameter will stringify an object with an explicit <code>toString</code> function.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>The <code>string</code> parameter won't coerce unsupported input to strings anymore.</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.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> | <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>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>
<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,
an exception is thrown.</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="#all_buffer_static-method-bufferbytelengthstring-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="#all_fs_fscreatewritestreampath-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>
<h4><code>fs.writeFile(file, data[, options], callback)</code><span><a class="mark" href="#all_fs_fswritefilefile-data-options-callback" id="all_fs_fswritefilefile-data-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_writefile_file_data_options_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.10.0</td>
<td><p>The <code>flush</code> option is now supported.</p></td></tr>
<tr><td>v19.0.0</td>
<td><p>Passing to the <code>string</code> parameter an object with an own <code>toString</code> function is no longer supported.</p></td></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></tr>
<tr><td>v17.8.0</td>
<td><p>Passing to the <code>string</code> parameter an object with an own <code>toString</code> function is deprecated.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p>The error returned may be an <code>AggregateError</code> if more than one error is returned.</p></td></tr>
<tr><td>v15.2.0, v14.17.0</td>
<td><p>The options argument may include an AbortSignal to abort an ongoing writeFile request.</p></td></tr>
<tr><td>v14.12.0</td>
<td><p>The <code>data</code> parameter will stringify an object with an explicit <code>toString</code> function.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>The <code>data</code> parameter won't coerce unsupported input to strings anymore.</p></td></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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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="#all_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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a>
<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="#all_fs_file-system-flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'w'</code>.</li>
<li><code>flush</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If all data is successfully written to the file, and
<code>flush</code> is <code>true</code>, <code>fs.fsync()</code> is used to flush the data.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> allows aborting an in-progress writeFile</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>
<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/Reference/Global_Objects/AggregateError" class="type">&#x3C;AggregateError></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>
<p>The <code>mode</code> option only affects the newly created file. See <a href="#all_fs_fsopenpath-flags-mode-callback"><code>fs.open()</code></a>
for more details.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { writeFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> data = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'Hello Node.js'</span>));
<span class="hljs-title function_">writeFile</span>(<span class="hljs-string">'message.txt'</span>, data, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'The file has been saved!'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>If <code>options</code> is a string, then it specifies the encoding:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { writeFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-title function_">writeFile</span>(<span class="hljs-string">'message.txt'</span>, <span class="hljs-string">'Hello Node.js'</span>, <span class="hljs-string">'utf8'</span>, callback);</code> <button class="copy-button">copy</button></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="#all_fs_fscreatewritestreampath-options"><code>fs.createWriteStream()</code></a> is
recommended.</p>
<p>Similarly to <code>fs.readFile</code> - <code>fs.writeFile</code> is a convenience method that
performs multiple <code>write</code> calls internally to write the buffer passed to it.
For performance sensitive code consider using <a href="#all_fs_fscreatewritestreampath-options"><code>fs.createWriteStream()</code></a>.</p>
<p>It is possible to use an <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> to cancel an <code>fs.writeFile()</code>.
Cancelation is "best effort", and some amount of data is likely still
to be written.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { writeFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> controller = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
<span class="hljs-keyword">const</span> { signal } = controller;
<span class="hljs-keyword">const</span> data = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'Hello Node.js'</span>));
<span class="hljs-title function_">writeFile</span>(<span class="hljs-string">'message.txt'</span>, data, { signal }, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-comment">// When a request is aborted - the callback is called with an AbortError</span>
});
<span class="hljs-comment">// When the request should be aborted</span>
controller.<span class="hljs-title function_">abort</span>();</code> <button class="copy-button">copy</button></pre>
<p>Aborting an ongoing request does not abort individual operating
system requests but rather the internal buffering <code>fs.writeFile</code> performs.</p>
<h5>Using <code>fs.writeFile()</code> with file descriptors<span><a class="mark" href="#all_fs_using-fswritefile-with-file-descriptors" id="all_fs_using-fswritefile-with-file-descriptors">#</a></span><a aria-hidden="true" class="legacy" id="fs_using_fs_writefile_with_file_descriptors"></a></h5>
<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 mjs"><span class="hljs-keyword">import</span> { write } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-title function_">write</span>(fd, <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(data, options.<span class="hljs-property">encoding</span>), callback);</code> <button class="copy-button">copy</button></pre>
<p>The difference from directly calling <code>fs.write()</code> is that under some unusual
conditions, <code>fs.write()</code> might write only part of the buffer and need to be
retried to write the remaining data, whereas <code>fs.writeFile()</code> retries 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>
<h4><code>fs.writev(fd, buffers[, position], callback)</code><span><a class="mark" href="#all_fs_fswritevfd-buffers-position-callback" id="all_fs_fswritevfd-buffers-position-callback">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_writev_fd_buffers_position_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></tr>
<tr><td>v12.9.0</td>
<td><p><span>Added in: v12.9.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>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> | <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>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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="#all_util_utilpromisifyoriginal"><code>util.promisify()</code></a>ed, it returns a promise 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="#all_fs_fscreatewritestreampath-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>
</section><section><h3>Synchronous API<span><a class="mark" href="#all_fs_synchronous-api" id="all_fs_synchronous-api">#</a></span><a aria-hidden="true" class="legacy" id="fs_synchronous_api"></a></h3>
<p>The synchronous APIs perform all operations synchronously, blocking the
event loop until the operation completes or fails.</p>
<h4><code>fs.accessSync(path[, mode])</code><span><a class="mark" href="#all_fs_fsaccesssyncpath-mode" id="all_fs_fsaccesssyncpath-mode">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_accesssync_path_mode"></a></h4>
<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.</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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. <code>mode</code> should be either the value
<code>fs.constants.F_OK</code> or a mask consisting of the bitwise OR of any of
<code>fs.constants.R_OK</code>, <code>fs.constants.W_OK</code>, and <code>fs.constants.X_OK</code> (e.g.
<code>fs.constants.W_OK | fs.constants.R_OK</code>). Check <a href="#all_fs_file-access-constants">File access constants</a> for
possible values of <code>mode</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 mjs"><span class="hljs-keyword">import</span> { accessSync, constants } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-keyword">try</span> {
  <span class="hljs-title function_">accessSync</span>(<span class="hljs-string">'etc/passwd'</span>, constants.<span class="hljs-property">R_OK</span> | constants.<span class="hljs-property">W_OK</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'can read/write'</span>);
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'no access!'</span>);
}</code> <button class="copy-button">copy</button></pre>
<h4><code>fs.appendFileSync(path, data[, options])</code><span><a class="mark" href="#all_fs_fsappendfilesyncpath-data-options" id="all_fs_fsappendfilesyncpath-data-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_appendfilesync_path_data_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.10.0</td>
<td><p>The <code>flush</code> option is now supported.</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></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>
<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="#all_fs_file-system-flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'a'</code>.</li>
<li><code>flush</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 underlying file descriptor is flushed
prior to closing it. <strong>Default:</strong> <code>false</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a>.</p>
<p>The <code>mode</code> option only affects the newly created file. See <a href="#all_fs_fsopenpath-flags-mode-callback"><code>fs.open()</code></a>
for more details.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { appendFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-keyword">try</span> {
  <span class="hljs-title function_">appendFileSync</span>(<span class="hljs-string">'message.txt'</span>, <span class="hljs-string">'data to append'</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'The "data to append" was appended to file!'</span>);
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-comment">/* Handle the error */</span>
}</code> <button class="copy-button">copy</button></pre>
<p>If <code>options</code> is a string, then it specifies the encoding:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { appendFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-title function_">appendFileSync</span>(<span class="hljs-string">'message.txt'</span>, <span class="hljs-string">'data to append'</span>, <span class="hljs-string">'utf8'</span>);</code> <button class="copy-button">copy</button></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 mjs"><span class="hljs-keyword">import</span> { openSync, closeSync, appendFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-keyword">let</span> fd;

<span class="hljs-keyword">try</span> {
  fd = <span class="hljs-title function_">openSync</span>(<span class="hljs-string">'message.txt'</span>, <span class="hljs-string">'a'</span>);
  <span class="hljs-title function_">appendFileSync</span>(fd, <span class="hljs-string">'data to append'</span>, <span class="hljs-string">'utf8'</span>);
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-comment">/* Handle the error */</span>
} <span class="hljs-keyword">finally</span> {
  <span class="hljs-keyword">if</span> (fd !== <span class="hljs-literal">undefined</span>)
    <span class="hljs-title function_">closeSync</span>(fd);
}</code> <button class="copy-button">copy</button></pre>
<h4><code>fs.chmodSync(path, mode)</code><span><a class="mark" href="#all_fs_fschmodsyncpath-mode" id="all_fs_fschmodsyncpath-mode">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_chmodsync_path_mode"></a></h4>
<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.</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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="#all_fs_fschmodpath-mode-callback"><code>fs.chmod()</code></a>.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/chmod.2.html"><code>chmod(2)</code></a> documentation for more detail.</p>
<h4><code>fs.chownSync(path, uid, gid)</code><span><a class="mark" href="#all_fs_fschownsyncpath-uid-gid" id="all_fs_fschownsyncpath-uid-gid">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_chownsync_path_uid_gid"></a></h4>
<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.</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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="#all_fs_fschownpath-uid-gid-callback"><code>fs.chown()</code></a>.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/chown.2.html"><code>chown(2)</code></a> documentation for more detail.</p>
<h4><code>fs.closeSync(fd)</code><span><a class="mark" href="#all_fs_fsclosesyncfd" id="all_fs_fsclosesyncfd">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_closesync_fd"></a></h4>
<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>Closes the file descriptor. 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>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/close.2.html"><code>close(2)</code></a> documentation for more detail.</p>
<h4><code>fs.copyFileSync(src, dest[, mode])</code><span><a class="mark" href="#all_fs_fscopyfilesyncsrc-dest-mode" id="all_fs_fscopyfilesyncsrc-dest-mode">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_copyfilesync_src_dest_mode"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.0.0</td>
<td><p>Changed <code>flags</code> argument to <code>mode</code> and imposed stricter type validation.</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>src</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></a> destination filename of the copy operation</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> 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>mode</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 mjs"><span class="hljs-keyword">import</span> { copyFileSync, constants } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-comment">// destination.txt will be created or overwritten by default.</span>
<span class="hljs-title function_">copyFileSync</span>(<span class="hljs-string">'source.txt'</span>, <span class="hljs-string">'destination.txt'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'source.txt was copied to destination.txt'</span>);

<span class="hljs-comment">// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.</span>
<span class="hljs-title function_">copyFileSync</span>(<span class="hljs-string">'source.txt'</span>, <span class="hljs-string">'destination.txt'</span>, constants.<span class="hljs-property">COPYFILE_EXCL</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>fs.cpSync(src, dest[, options])</code><span><a class="mark" href="#all_fs_fscpsyncsrc-dest-options" id="all_fs_fscpsyncsrc-dest-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_cpsync_src_dest_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.1.0</td>
<td><p>Accept an additional <code>mode</code> option to specify the copy behavior as the <code>mode</code> argument of <code>fs.copyFile()</code>.</p></td></tr>
<tr><td>v17.6.0, v16.15.0</td>
<td><p>Accepts an additional <code>verbatimSymlinks</code> option to specify whether to perform path resolution for symlinks.</p></td></tr>
<tr><td>v16.7.0</td>
<td><p><span>Added in: v16.7.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<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="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></a> source path 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="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></a> destination path to copy to.</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>
<ul>
<li><code>dereference</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> dereference symlinks. <strong>Default:</strong> <code>false</code>.</li>
<li><code>errorOnExist</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> when <code>force</code> is <code>false</code>, and the destination
exists, throw an error. <strong>Default:</strong> <code>false</code>.</li>
<li><code>filter</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Function to filter copied files/directories. Return
<code>true</code> to copy the item, <code>false</code> to ignore it. When ignoring a directory,
all of its contents will be skipped as well. <strong>Default:</strong> <code>undefined</code>
<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> source path 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> destination path to copy to.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Any non-<code>Promise</code> value that is coercible
to <code>boolean</code>.</li>
</ul>
</li>
<li><code>force</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> overwrite existing file or directory. The copy
operation will ignore errors if you set this to false and the destination
exists. Use the <code>errorOnExist</code> option to change this behavior.
<strong>Default:</strong> <code>true</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> modifiers for copy operation. <strong>Default:</strong> <code>0</code>.
See <code>mode</code> flag of <a href="#all_fs_fscopyfilesyncsrc-dest-mode"><code>fs.copyFileSync()</code></a>.</li>
<li><code>preserveTimestamps</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> timestamps from <code>src</code> will
be preserved. <strong>Default:</strong> <code>false</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> copy directories recursively <strong>Default:</strong> <code>false</code></li>
<li><code>verbatimSymlinks</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>, path resolution for symlinks will
be skipped. <strong>Default:</strong> <code>false</code></li>
</ul>
</li>
</ul>
<p>Synchronously copies the entire directory structure from <code>src</code> to <code>dest</code>,
including subdirectories and files.</p>
<p>When copying a directory to another directory, globs are not supported and
behavior is similar to <code>cp dir1/ dir2/</code>.</p>
<h4><code>fs.existsSync(path)</code><span><a class="mark" href="#all_fs_fsexistssyncpath" id="all_fs_fsexistssyncpath">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_existssync_path"></a></h4>
<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.</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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="#all_fs_fsexistspath-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 mjs"><span class="hljs-keyword">import</span> { existsSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-keyword">if</span> (<span class="hljs-title function_">existsSync</span>(<span class="hljs-string">'/etc/passwd'</span>))
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'The path exists.'</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>fs.fchmodSync(fd, mode)</code><span><a class="mark" href="#all_fs_fsfchmodsyncfd-mode" id="all_fs_fsfchmodsyncfd-mode">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_fchmodsync_fd_mode"></a></h4>
<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>Sets the permissions on the file. Returns <code>undefined</code>.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/fchmod.2.html"><code>fchmod(2)</code></a> documentation for more detail.</p>
<h4><code>fs.fchownSync(fd, uid, gid)</code><span><a class="mark" href="#all_fs_fsfchownsyncfd-uid-gid" id="all_fs_fsfchownsyncfd-uid-gid">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_fchownsync_fd_uid_gid"></a></h4>
<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> The file's new owner's user id.</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> The file's new group's group id.</li>
</ul>
<p>Sets the owner of the file. Returns <code>undefined</code>.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/fchown.2.html"><code>fchown(2)</code></a> documentation for more detail.</p>
<h4><code>fs.fdatasyncSync(fd)</code><span><a class="mark" href="#all_fs_fsfdatasyncsyncfd" id="all_fs_fsfdatasyncsyncfd">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_fdatasyncsync_fd"></a></h4>
<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>Forces all currently queued I/O operations associated with the file to the
operating system's synchronized I/O completion state. Refer to the POSIX
<a href="http://man7.org/linux/man-pages/man2/fdatasync.2.html"><code>fdatasync(2)</code></a> documentation for details. Returns <code>undefined</code>.</p>
<h4><code>fs.fstatSync(fd[, options])</code><span><a class="mark" href="#all_fs_fsfstatsyncfd-options" id="all_fs_fsfstatsyncfd-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_fstatsync_fd_options"></a></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>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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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="#all_fs_class-fsstats" class="type">&#x3C;fs.Stats></a> object should be <code>bigint</code>. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>Returns: <a href="#all_fs_class-fsstats" class="type">&#x3C;fs.Stats></a></li>
</ul>
<p>Retrieves the <a href="#all_fs_class-fsstats" class="type">&#x3C;fs.Stats></a> for the file descriptor.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/fstat.2.html"><code>fstat(2)</code></a> documentation for more detail.</p>
<h4><code>fs.fsyncSync(fd)</code><span><a class="mark" href="#all_fs_fsfsyncsyncfd" id="all_fs_fsfsyncsyncfd">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_fsyncsync_fd"></a></h4>
<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>Request that all data for the open file descriptor is flushed to the storage
device. The specific implementation is operating system and device specific.
Refer to the POSIX <a href="http://man7.org/linux/man-pages/man2/fsync.2.html"><code>fsync(2)</code></a> documentation for more detail. Returns <code>undefined</code>.</p>
<h4><code>fs.ftruncateSync(fd[, len])</code><span><a class="mark" href="#all_fs_fsftruncatesyncfd-len" id="all_fs_fsftruncatesyncfd-len">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_ftruncatesync_fd_len"></a></h4>
<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>Truncates the file descriptor. Returns <code>undefined</code>.</p>
<p>For detailed information, see the documentation of the asynchronous version of
this API: <a href="#all_fs_fsftruncatefd-len-callback"><code>fs.ftruncate()</code></a>.</p>
<h4><code>fs.futimesSync(fd, atime, mtime)</code><span><a class="mark" href="#all_fs_fsfutimessyncfd-atime-mtime" id="all_fs_fsfutimessyncfd-atime-mtime">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_futimessync_fd_atime_mtime"></a></h4>
<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="#all_fs_fsfutimesfd-atime-mtime-callback"><code>fs.futimes()</code></a>. Returns <code>undefined</code>.</p>
<h4><code>fs.lchmodSync(path, mode)</code><span><a class="mark" href="#all_fs_fslchmodsyncpath-mode" id="all_fs_fslchmodsyncpath-mode">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_lchmodsync_path_mode"></a></h4>
<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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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>Changes the permissions on a symbolic link. Returns <code>undefined</code>.</p>
<p>This method is only implemented on macOS.</p>
<p>See the POSIX <a href="https://www.freebsd.org/cgi/man.cgi?query=lchmod&#x26;sektion=2"><code>lchmod(2)</code></a> documentation for more detail.</p>
<h4><code>fs.lchownSync(path, uid, gid)</code><span><a class="mark" href="#all_fs_fslchownsyncpath-uid-gid" id="all_fs_fslchownsyncpath-uid-gid">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_lchownsync_path_uid_gid"></a></h4>
<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>v0.4.7</td>
<td><p>Documentation-only deprecation.</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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> The file's new owner's user id.</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> The file's new group's group id.</li>
</ul>
<p>Set the owner for the path. Returns <code>undefined</code>.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/lchown.2.html"><code>lchown(2)</code></a> documentation for more details.</p>
<h4><code>fs.lutimesSync(path, atime, mtime)</code><span><a class="mark" href="#all_fs_fslutimessyncpath-atime-mtime" id="all_fs_fslutimessyncpath-atime-mtime">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_lutimessync_path_atime_mtime"></a></h4>
<div class="api_metadata">
<span>Added in: v14.5.0, v12.19.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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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>Change the file system timestamps of the symbolic link referenced by <code>path</code>.
Returns <code>undefined</code>, or throws an exception when parameters are incorrect or
the operation fails. This is the synchronous version of <a href="#all_fs_fslutimespath-atime-mtime-callback"><code>fs.lutimes()</code></a>.</p>
<h4><code>fs.linkSync(existingPath, newPath)</code><span><a class="mark" href="#all_fs_fslinksyncexistingpath-newpath" id="all_fs_fslinksyncexistingpath-newpath">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_linksync_existingpath_newpath"></a></h4>
<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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></a></li>
</ul>
<p>Creates a new link from the <code>existingPath</code> to the <code>newPath</code>. See the POSIX
<a href="http://man7.org/linux/man-pages/man2/link.2.html"><code>link(2)</code></a> documentation for more detail. Returns <code>undefined</code>.</p>
<h4><code>fs.lstatSync(path[, options])</code><span><a class="mark" href="#all_fs_fslstatsyncpath-options" id="all_fs_fslstatsyncpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_lstatsync_path_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.3.0, v14.17.0</td>
<td><p>Accepts a <code>throwIfNoEntry</code> option to specify whether an exception should be thrown if the entry does not exist.</p></td></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.</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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>
<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="#all_fs_class-fsstats" class="type">&#x3C;fs.Stats></a> object should be <code>bigint</code>. <strong>Default:</strong> <code>false</code>.</li>
<li><code>throwIfNoEntry</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Whether an exception will be thrown
if no file system entry exists, rather than returning <code>undefined</code>.
<strong>Default:</strong> <code>true</code>.</li>
</ul>
</li>
<li>Returns: <a href="#all_fs_class-fsstats" class="type">&#x3C;fs.Stats></a></li>
</ul>
<p>Retrieves the <a href="#all_fs_class-fsstats" class="type">&#x3C;fs.Stats></a> for the symbolic link referred to by <code>path</code>.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/lstat.2.html"><code>lstat(2)</code></a> documentation for more details.</p>
<h4><code>fs.mkdirSync(path[, options])</code><span><a class="mark" href="#all_fs_fsmkdirsyncpath-options" id="all_fs_fsmkdirsyncpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_mkdirsync_path_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.11.0, 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.</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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#Number_type" class="type">&#x3C;integer></a>
<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="#all_fs_fsmkdirpath-options-callback"><code>fs.mkdir()</code></a>.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/mkdir.2.html"><code>mkdir(2)</code></a> documentation for more details.</p>
<h4><code>fs.mkdtempSync(prefix[, options])</code><span><a class="mark" href="#all_fs_fsmkdtempsyncprefix-options" id="all_fs_fsmkdtempsyncprefix-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_mkdtempsync_prefix_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.6.0</td>
<td><p>The <code>prefix</code> parameter now accepts buffers and URL.</p></td></tr>
<tr><td>v16.5.0, v14.18.0</td>
<td><p>The <code>prefix</code> parameter now accepts an empty string.</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> | <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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/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>
<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="#all_fs_fsmkdtempprefix-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>
<h4><code>fs.opendirSync(path[, options])</code><span><a class="mark" href="#all_fs_fsopendirsyncpath-options" id="all_fs_fsopendirsyncpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_opendirsync_path_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.1.0</td>
<td><p>Added <code>recursive</code> option.</p></td></tr>
<tr><td>v13.1.0, 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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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>
<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>
<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>
</ul>
</li>
<li>Returns: <a href="#all_fs_class-fsdir" 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="#all_fs_class-fsdir" class="type">&#x3C;fs.Dir></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>
<h4><code>fs.openSync(path[, flags[, mode]])</code><span><a class="mark" href="#all_fs_fsopensyncpath-flags-mode" id="all_fs_fsopensyncpath-flags-mode">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_opensync_path_flags_mode"></a></h4>
<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> flags 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.</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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="#all_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="#all_fs_fsopenpath-flags-mode-callback"><code>fs.open()</code></a>.</p>
<h4><code>fs.readdirSync(path[, options])</code><span><a class="mark" href="#all_fs_fsreaddirsyncpath-options" id="all_fs_fsreaddirsyncpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_readdirsync_path_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.1.0</td>
<td><p>Added <code>recursive</code> option.</p></td></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.</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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/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>
<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>
<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>, reads the contents of a directory
recursively. In recursive mode, it will list all files, sub files, and
directories. <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="#all_buffer_class-buffer" class="type">&#x3C;Buffer[]></a> | <a href="#all_fs_class-fsdirent" class="type">&#x3C;fs.Dirent[]></a></li>
</ul>
<p>Reads the contents of the directory.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man3/readdir.3.html"><code>readdir(3)</code></a> documentation for more details.</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 <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> objects.</p>
<p>If <code>options.withFileTypes</code> is set to <code>true</code>, the result will contain
<a href="#all_fs_class-fsdirent" class="type">&#x3C;fs.Dirent></a> objects.</p>
<h4><code>fs.readFileSync(path[, options])</code><span><a class="mark" href="#all_fs_fsreadfilesyncpath-options" id="all_fs_fsreadfilesyncpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_readfilesync_path_options"></a></h4>
<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.</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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>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>
<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="#all_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="#all_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="#all_fs_fsreadfilepath-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="#all_fs_fsreadfilepath-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 mjs"><span class="hljs-keyword">import</span> { readFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-comment">// macOS, Linux, and Windows</span>
<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'&#x3C;directory>'</span>);
<span class="hljs-comment">// => [Error: EISDIR: illegal operation on a directory, read &#x3C;directory>]</span>

<span class="hljs-comment">//  FreeBSD</span>
<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'&#x3C;directory>'</span>); <span class="hljs-comment">// => &#x3C;data></span></code> <button class="copy-button">copy</button></pre>
<h4><code>fs.readlinkSync(path[, options])</code><span><a class="mark" href="#all_fs_fsreadlinksyncpath-options" id="all_fs_fsreadlinksyncpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_readlinksync_path_options"></a></h4>
<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.</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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/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>
<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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a></li>
</ul>
<p>Returns the symbolic link's string value.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/readlink.2.html"><code>readlink(2)</code></a> documentation for more details.</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 <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> object.</p>
<h4><code>fs.readSync(fd, buffer, offset, length[, position])</code><span><a class="mark" href="#all_fs_fsreadsyncfd-buffer-offset-length-position" id="all_fs_fsreadsyncfd-buffer-offset-length-position">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_readsync_fd_buffer_offset_length_position"></a></h4>
<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="#all_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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type">&#x3C;bigint></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>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="#all_fs_fsreadfd-buffer-offset-length-position-callback"><code>fs.read()</code></a>.</p>
<h4><code>fs.readSync(fd, buffer[, options])</code><span><a class="mark" href="#all_fs_fsreadsyncfd-buffer-options" id="all_fs_fsreadsyncfd-buffer-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_readsync_fd_buffer_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.13.0, v12.17.0</td>
<td><p>Options object can be passed in to make offset, length, and position optional.</p></td></tr>
<tr><td>v13.13.0, v12.17.0</td>
<td><p><span>Added in: v13.13.0, 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="#all_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>
<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.byteLength - offset</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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt" class="type">&#x3C;bigint></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/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="#all_fs_fsreadfd-buffer-offset-length-position-callback"><code>fs.read()</code></a>.</p>
<h4><code>fs.readvSync(fd, buffers[, position])</code><span><a class="mark" href="#all_fs_fsreadvsyncfd-buffers-position" id="all_fs_fsreadvsyncfd-buffers-position">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_readvsync_fd_buffers_position"></a></h4>
<div class="api_metadata">
<span>Added in: v13.13.0, 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> | <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>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="#all_fs_fsreadvfd-buffers-position-callback"><code>fs.readv()</code></a>.</p>
<h4><code>fs.realpathSync(path[, options])</code><span><a class="mark" href="#all_fs_fsrealpathsyncpath-options" id="all_fs_fsrealpathsyncpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_realpathsync_path_options"></a></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>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.</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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/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>
<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="#all_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="#all_fs_fsrealpathpath-options-callback"><code>fs.realpath()</code></a>.</p>
<h4><code>fs.realpathSync.native(path[, options])</code><span><a class="mark" href="#all_fs_fsrealpathsyncnativepath-options" id="all_fs_fsrealpathsyncnativepath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_realpathsync_native_path_options"></a></h4>
<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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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/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>
<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="#all_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 <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> 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>
<h4><code>fs.renameSync(oldPath, newPath)</code><span><a class="mark" href="#all_fs_fsrenamesyncoldpath-newpath" id="all_fs_fsrenamesyncoldpath-newpath">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_renamesync_oldpath_newpath"></a></h4>
<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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></a></li>
</ul>
<p>Renames the file from <code>oldPath</code> to <code>newPath</code>. Returns <code>undefined</code>.</p>
<p>See the POSIX <a href="http://man7.org/linux/man-pages/man2/rename.2.html"><code>rename(2)</code></a> documentation for more details.</p>
<h4><code>fs.rmdirSync(path[, options])</code><span><a class="mark" href="#all_fs_fsrmdirsyncpath-options" id="all_fs_fsrmdirsyncpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_rmdirsync_path_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0</td>
<td><p>Using <code>fs.rmdirSync(path, { recursive: true })</code> on a <code>path</code> that is a file is no longer permitted and results in an <code>ENOENT</code> error on Windows and an <code>ENOTDIR</code> error on POSIX.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p>Using <code>fs.rmdirSync(path, { recursive: true })</code> on a <code>path</code> that does not exist is no longer permitted and results in a <code>ENOENT</code> error.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p>The <code>recursive</code> option is deprecated, using it triggers a deprecation warning.</p></td></tr>
<tr><td>v14.14.0</td>
<td><p>The <code>recursive</code> option is deprecated, use <code>fs.rmSync</code> instead.</p></td></tr>
<tr><td>v13.3.0, 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.</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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>
<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 retries the operation with a linear
backoff wait of <code>retryDelay</code> milliseconds 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, operations are retried on failure. <strong>Default:</strong> <code>false</code>.
<strong>Deprecated.</strong></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>
<p>To get a behavior similar to the <code>rm -rf</code> Unix command, use <a href="#all_fs_fsrmsyncpath-options"><code>fs.rmSync()</code></a>
with options <code>{ recursive: true, force: true }</code>.</p>
<h4><code>fs.rmSync(path[, options])</code><span><a class="mark" href="#all_fs_fsrmsyncpath-options" id="all_fs_fsrmsyncpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_rmsync_path_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.3.0, v16.14.0</td>
<td><p>The <code>path</code> parameter can be a WHATWG <code>URL</code> object using <code>file:</code> protocol.</p></td></tr>
<tr><td>v14.14.0</td>
<td><p><span>Added in: v14.14.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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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>
<ul>
<li><code>force</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>, exceptions will be ignored if <code>path</code> does
not exist. <strong>Default:</strong> <code>false</code>.</li>
<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> milliseconds 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 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>Synchronously removes files and directories (modeled on the standard POSIX <code>rm</code>
utility). Returns <code>undefined</code>.</p>
<h4><code>fs.statSync(path[, options])</code><span><a class="mark" href="#all_fs_fsstatsyncpath-options" id="all_fs_fsstatsyncpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_statsync_path_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.3.0, v14.17.0</td>
<td><p>Accepts a <code>throwIfNoEntry</code> option to specify whether an exception should be thrown if the entry does not exist.</p></td></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.</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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>
<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="#all_fs_class-fsstats" class="type">&#x3C;fs.Stats></a> object should be <code>bigint</code>. <strong>Default:</strong> <code>false</code>.</li>
<li><code>throwIfNoEntry</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Whether an exception will be thrown
if no file system entry exists, rather than returning <code>undefined</code>.
<strong>Default:</strong> <code>true</code>.</li>
</ul>
</li>
<li>Returns: <a href="#all_fs_class-fsstats" class="type">&#x3C;fs.Stats></a></li>
</ul>
<p>Retrieves the <a href="#all_fs_class-fsstats" class="type">&#x3C;fs.Stats></a> for the path.</p>
<h4><code>fs.statfsSync(path[, options])</code><span><a class="mark" href="#all_fs_fsstatfssyncpath-options" id="all_fs_fsstatfssyncpath-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_statfssync_path_options"></a></h4>
<div class="api_metadata">
<span>Added in: v19.6.0, v18.15.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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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>
<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="#all_fs_class-fsstatfs" class="type">&#x3C;fs.StatFs></a> object should be <code>bigint</code>. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>Returns: <a href="#all_fs_class-fsstatfs" class="type">&#x3C;fs.StatFs></a></li>
</ul>
<p>Synchronous <a href="http://man7.org/linux/man-pages/man2/statfs.2.html"><code>statfs(2)</code></a>. Returns information about the mounted file system which
contains <code>path</code>.</p>
<p>In case of an error, the <code>err.code</code> will be one of <a href="#all_errors_common-system-errors">Common System Errors</a>.</p>
<h4><code>fs.symlinkSync(target, path[, type])</code><span><a class="mark" href="#all_fs_fssymlinksynctarget-path-type" id="all_fs_fssymlinksynctarget-path-type">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_symlinksync_target_path_type"></a></h4>
<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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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> | <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>
<p>Returns <code>undefined</code>.</p>
<p>For detailed information, see the documentation of the asynchronous version of
this API: <a href="#all_fs_fssymlinktarget-path-type-callback"><code>fs.symlink()</code></a>.</p>
<h4><code>fs.truncateSync(path[, len])</code><span><a class="mark" href="#all_fs_fstruncatesyncpath-len" id="all_fs_fstruncatesyncpath-len">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_truncatesync_path_len"></a></h4>
<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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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>Truncates the file. 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>
<h4><code>fs.unlinkSync(path)</code><span><a class="mark" href="#all_fs_fsunlinksyncpath" id="all_fs_fsunlinksyncpath">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_unlinksync_path"></a></h4>
<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.</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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>
<h4><code>fs.utimesSync(path, atime, mtime)</code><span><a class="mark" href="#all_fs_fsutimessyncpath-atime-mtime" id="all_fs_fsutimessyncpath-atime-mtime">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_utimessync_path_atime_mtime"></a></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><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.</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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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="#all_fs_fsutimespath-atime-mtime-callback"><code>fs.utimes()</code></a>.</p>
<h4><code>fs.writeFileSync(file, data[, options])</code><span><a class="mark" href="#all_fs_fswritefilesyncfile-data-options" id="all_fs_fswritefilesyncfile-data-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_writefilesync_file_data_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.10.0</td>
<td><p>The <code>flush</code> option is now supported.</p></td></tr>
<tr><td>v19.0.0</td>
<td><p>Passing to the <code>data</code> parameter an object with an own <code>toString</code> function is no longer supported.</p></td></tr>
<tr><td>v17.8.0</td>
<td><p>Passing to the <code>data</code> parameter an object with an own <code>toString</code> function is deprecated.</p></td></tr>
<tr><td>v14.12.0</td>
<td><p>The <code>data</code> parameter will stringify an object with an explicit <code>toString</code> function.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>The <code>data</code> parameter won't coerce unsupported input to strings anymore.</p></td></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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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="#all_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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a>
<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="#all_fs_file-system-flags">support of file system <code>flags</code></a>. <strong>Default:</strong> <code>'w'</code>.</li>
<li><code>flush</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If all data is successfully written to the file, and
<code>flush</code> is <code>true</code>, <code>fs.fsyncSync()</code> is used to flush the data.</li>
</ul>
</li>
</ul>
<p>Returns <code>undefined</code>.</p>
<p>The <code>mode</code> option only affects the newly created file. See <a href="#all_fs_fsopenpath-flags-mode-callback"><code>fs.open()</code></a>
for more details.</p>
<p>For detailed information, see the documentation of the asynchronous version of
this API: <a href="#all_fs_fswritefilefile-data-options-callback"><code>fs.writeFile()</code></a>.</p>
<h4><code>fs.writeSync(fd, buffer, offset[, length[, position]])</code><span><a class="mark" href="#all_fs_fswritesyncfd-buffer-offset-length-position" id="all_fs_fswritesyncfd-buffer-offset-length-position">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_writesync_fd_buffer_offset_length_position"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.0.0</td>
<td><p>The <code>buffer</code> parameter won't coerce unsupported input to strings anymore.</p></td></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="#all_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> <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.byteLength - offset</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> | <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>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="#all_fs_fswritefd-buffer-offset-length-position-callback"><code>fs.write(fd, buffer...)</code></a>.</p>
<h4><code>fs.writeSync(fd, buffer[, options])</code><span><a class="mark" href="#all_fs_fswritesyncfd-buffer-options" id="all_fs_fswritesyncfd-buffer-options">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_writesync_fd_buffer_options"></a></h4>
<div class="api_metadata">
<span>Added in: v18.3.0, v16.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>buffer</code> <a href="#all_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>
<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.byteLength - offset</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> The number of bytes written.</li>
</ul>
<p>For detailed information, see the documentation of the asynchronous version of
this API: <a href="#all_fs_fswritefd-buffer-offset-length-position-callback"><code>fs.write(fd, buffer...)</code></a>.</p>
<h4><code>fs.writeSync(fd, string[, position[, encoding]])</code><span><a class="mark" href="#all_fs_fswritesyncfd-string-position-encoding" id="all_fs_fswritesyncfd-string-position-encoding">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_writesync_fd_string_position_encoding"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.0.0</td>
<td><p>The <code>string</code> parameter won't coerce unsupported input to strings anymore.</p></td></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> | <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>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/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="#all_fs_fswritefd-string-position-encoding-callback"><code>fs.write(fd, string...)</code></a>.</p>
<h4><code>fs.writevSync(fd, buffers[, position])</code><span><a class="mark" href="#all_fs_fswritevsyncfd-buffers-position" id="all_fs_fswritevsyncfd-buffers-position">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_writevsync_fd_buffers_position"></a></h4>
<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> | <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>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="#all_fs_fswritevfd-buffers-position-callback"><code>fs.writev()</code></a>.</p>
</section><section><h3>Common Objects<span><a class="mark" href="#all_fs_common-objects" id="all_fs_common-objects">#</a></span><a aria-hidden="true" class="legacy" id="fs_common_objects"></a></h3>
<p>The common objects are shared by all of the file system API variants
(promise, callback, and synchronous).</p>
<h4>Class: <code>fs.Dir</code><span><a class="mark" href="#all_fs_class-fsdir" id="all_fs_class-fsdir">#</a></span><a aria-hidden="true" class="legacy" id="fs_class_fs_dir"></a></h4>
<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="#all_fs_fsopendirpath-options-callback"><code>fs.opendir()</code></a>, <a href="#all_fs_fsopendirsyncpath-options"><code>fs.opendirSync()</code></a>, or
<a href="#all_fs_fspromisesopendirpath-options"><code>fsPromises.opendir()</code></a>.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { opendir } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;

<span class="hljs-keyword">try</span> {
  <span class="hljs-keyword">const</span> dir = <span class="hljs-keyword">await</span> <span class="hljs-title function_">opendir</span>(<span class="hljs-string">'./'</span>);
  <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> dirent <span class="hljs-keyword">of</span> dir)
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(dirent.<span class="hljs-property">name</span>);
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err);
}</code> <button class="copy-button">copy</button></pre>
<p>When using the async iterator, the <a href="#all_fs_class-fsdir" class="type">&#x3C;fs.Dir></a> object will be automatically
closed after the iterator exits.</p>
<h5><code>dir.close()</code><span><a class="mark" href="#all_fs_dirclose" id="all_fs_dirclose">#</a></span><a aria-hidden="true" class="legacy" id="fs_dir_close"></a></h5>
<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 promise is returned that will be fulfilled after the resource has been
closed.</p>
<h5><code>dir.close(callback)</code><span><a class="mark" href="#all_fs_dirclosecallback" id="all_fs_dirclosecallback">#</a></span><a aria-hidden="true" class="legacy" id="fs_dir_close_callback"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</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>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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>
<h5><code>dir.closeSync()</code><span><a class="mark" href="#all_fs_dirclosesync" id="all_fs_dirclosesync">#</a></span><a aria-hidden="true" class="legacy" id="fs_dir_closesync"></a></h5>
<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>
<h5><code>dir.path</code><span><a class="mark" href="#all_fs_dirpath" id="all_fs_dirpath">#</a></span><a aria-hidden="true" class="legacy" id="fs_dir_path"></a></h5>
<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="#all_fs_fsopendirpath-options-callback"><code>fs.opendir()</code></a>,
<a href="#all_fs_fsopendirsyncpath-options"><code>fs.opendirSync()</code></a>, or <a href="#all_fs_fspromisesopendirpath-options"><code>fsPromises.opendir()</code></a>.</p>
<h5><code>dir.read()</code><span><a class="mark" href="#all_fs_dirread" id="all_fs_dirread">#</a></span><a aria-hidden="true" class="legacy" id="fs_dir_read"></a></h5>
<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> Fulfills with a <a href="#all_fs_class-fsdirent" 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="#all_fs_class-fsdirent" class="type">&#x3C;fs.Dirent></a>.</p>
<p>A promise is returned that will be fulfilled with an <a href="#all_fs_class-fsdirent" class="type">&#x3C;fs.Dirent></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 might not be
included in the iteration results.</p>
<h5><code>dir.read(callback)</code><span><a class="mark" href="#all_fs_dirreadcallback" id="all_fs_dirreadcallback">#</a></span><a aria-hidden="true" class="legacy" id="fs_dir_read_callback"></a></h5>
<div class="api_metadata">
<span>Added in: v12.12.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>
<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="#all_fs_class-fsdirent" 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="#all_fs_class-fsdirent" class="type">&#x3C;fs.Dirent></a>.</p>
<p>After the read is completed, the <code>callback</code> will be called with an
<a href="#all_fs_class-fsdirent" class="type">&#x3C;fs.Dirent></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 might not be
included in the iteration results.</p>
<h5><code>dir.readSync()</code><span><a class="mark" href="#all_fs_dirreadsync" id="all_fs_dirreadsync">#</a></span><a aria-hidden="true" class="legacy" id="fs_dir_readsync"></a></h5>
<div class="api_metadata">
<span>Added in: v12.12.0</span>
</div>
<ul>
<li>Returns: <a href="#all_fs_class-fsdirent" 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 as an <a href="#all_fs_class-fsdirent" class="type">&#x3C;fs.Dirent></a>. See the
POSIX <a href="http://man7.org/linux/man-pages/man3/readdir.3.html"><code>readdir(3)</code></a> documentation for more detail.</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 might not be
included in the iteration results.</p>
<h5><code>dir[Symbol.asyncIterator]()</code><span><a class="mark" href="#all_fs_dirsymbolasynciterator" id="all_fs_dirsymbolasynciterator">#</a></span><a aria-hidden="true" class="legacy" id="fs_dir_symbol_asynciterator"></a></h5>
<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> An AsyncIterator of <a href="#all_fs_class-fsdirent" class="type">&#x3C;fs.Dirent></a></li>
</ul>
<p>Asynchronously iterates over the directory until all entries have
been read. Refer to the POSIX <a href="http://man7.org/linux/man-pages/man3/readdir.3.html"><code>readdir(3)</code></a> documentation for more detail.</p>
<p>Entries returned by the async iterator are always an <a href="#all_fs_class-fsdirent" class="type">&#x3C;fs.Dirent></a>.
The <code>null</code> case from <code>dir.read()</code> is handled internally.</p>
<p>See <a href="#all_fs_class-fsdir" class="type">&#x3C;fs.Dir></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 might not be
included in the iteration results.</p>
<h4>Class: <code>fs.Dirent</code><span><a class="mark" href="#all_fs_class-fsdirent" id="all_fs_class-fsdirent">#</a></span><a aria-hidden="true" class="legacy" id="fs_class_fs_dirent"></a></h4>
<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="#all_fs_class-fsdir" class="type">&#x3C;fs.Dir></a>. The
directory entry is a combination of the file name and file type pairs.</p>
<p>Additionally, when <a href="#all_fs_fsreaddirpath-options-callback"><code>fs.readdir()</code></a> or <a href="#all_fs_fsreaddirsyncpath-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
<a href="#all_fs_class-fsdirent" class="type">&#x3C;fs.Dirent></a> objects, rather than strings or <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a>s.</p>
<h5><code>dirent.isBlockDevice()</code><span><a class="mark" href="#all_fs_direntisblockdevice" id="all_fs_direntisblockdevice">#</a></span><a aria-hidden="true" class="legacy" id="fs_dirent_isblockdevice"></a></h5>
<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 <a href="#all_fs_class-fsdirent" class="type">&#x3C;fs.Dirent></a> object describes a block device.</p>
<h5><code>dirent.isCharacterDevice()</code><span><a class="mark" href="#all_fs_direntischaracterdevice" id="all_fs_direntischaracterdevice">#</a></span><a aria-hidden="true" class="legacy" id="fs_dirent_ischaracterdevice"></a></h5>
<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 <a href="#all_fs_class-fsdirent" class="type">&#x3C;fs.Dirent></a> object describes a character device.</p>
<h5><code>dirent.isDirectory()</code><span><a class="mark" href="#all_fs_direntisdirectory" id="all_fs_direntisdirectory">#</a></span><a aria-hidden="true" class="legacy" id="fs_dirent_isdirectory"></a></h5>
<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 <a href="#all_fs_class-fsdirent" class="type">&#x3C;fs.Dirent></a> object describes a file system
directory.</p>
<h5><code>dirent.isFIFO()</code><span><a class="mark" href="#all_fs_direntisfifo" id="all_fs_direntisfifo">#</a></span><a aria-hidden="true" class="legacy" id="fs_dirent_isfifo"></a></h5>
<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 <a href="#all_fs_class-fsdirent" class="type">&#x3C;fs.Dirent></a> object describes a first-in-first-out
(FIFO) pipe.</p>
<h5><code>dirent.isFile()</code><span><a class="mark" href="#all_fs_direntisfile" id="all_fs_direntisfile">#</a></span><a aria-hidden="true" class="legacy" id="fs_dirent_isfile"></a></h5>
<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 <a href="#all_fs_class-fsdirent" class="type">&#x3C;fs.Dirent></a> object describes a regular file.</p>
<h5><code>dirent.isSocket()</code><span><a class="mark" href="#all_fs_direntissocket" id="all_fs_direntissocket">#</a></span><a aria-hidden="true" class="legacy" id="fs_dirent_issocket"></a></h5>
<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 <a href="#all_fs_class-fsdirent" class="type">&#x3C;fs.Dirent></a> object describes a socket.</p>
<h5><code>dirent.isSymbolicLink()</code><span><a class="mark" href="#all_fs_direntissymboliclink" id="all_fs_direntissymboliclink">#</a></span><a aria-hidden="true" class="legacy" id="fs_dirent_issymboliclink"></a></h5>
<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 <a href="#all_fs_class-fsdirent" class="type">&#x3C;fs.Dirent></a> object describes a symbolic link.</p>
<h5><code>dirent.name</code><span><a class="mark" href="#all_fs_direntname" id="all_fs_direntname">#</a></span><a aria-hidden="true" class="legacy" id="fs_dirent_name"></a></h5>
<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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a></li>
</ul>
<p>The file name that this <a href="#all_fs_class-fsdirent" class="type">&#x3C;fs.Dirent></a> object refers to. The type of this
value is determined by the <code>options.encoding</code> passed to <a href="#all_fs_fsreaddirpath-options-callback"><code>fs.readdir()</code></a> or
<a href="#all_fs_fsreaddirsyncpath-options"><code>fs.readdirSync()</code></a>.</p>
<h5><code>dirent.parentPath</code><span><a class="mark" href="#all_fs_direntparentpath" id="all_fs_direntparentpath">#</a></span><a aria-hidden="true" class="legacy" id="fs_dirent_parentpath"></a></h5>
<div class="api_metadata">
<span>Added in: v20.12.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_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#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The path to the parent directory of the file this <a href="#all_fs_class-fsdirent" class="type">&#x3C;fs.Dirent></a> object refers to.</p>
<h5><code>dirent.path</code><span><a class="mark" href="#all_fs_direntpath" id="all_fs_direntpath">#</a></span><a aria-hidden="true" class="legacy" id="fs_dirent_path"></a></h5>
<div class="api_metadata">
<span>Added in: v20.1.0, v18.17.0</span><span>Deprecated since: v20.12.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_fs_direntparentpath"><code>dirent.parentPath</code></a> instead.</div><p></p>
<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>Alias for <code>dirent.parentPath</code>.</p>
<h4>Class: <code>fs.FSWatcher</code><span><a class="mark" href="#all_fs_class-fsfswatcher" id="all_fs_class-fsfswatcher">#</a></span><a aria-hidden="true" class="legacy" id="fs_class_fs_fswatcher"></a></h4>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<ul>
<li>Extends <a href="#all_events_class-eventemitter" class="type">&#x3C;EventEmitter></a></li>
</ul>
<p>A successful call to <a href="#all_fs_fswatchfilename-options-listener"><code>fs.watch()</code></a> method will return a new <a href="#all_fs_class-fsfswatcher" class="type">&#x3C;fs.FSWatcher></a>
object.</p>
<p>All <a href="#all_fs_class-fsfswatcher" class="type">&#x3C;fs.FSWatcher></a> objects emit a <code>'change'</code> event whenever a specific watched
file is modified.</p>
<h5>Event: <code>'change'</code><span><a class="mark" href="#all_fs_event-change" id="all_fs_event-change">#</a></span><a aria-hidden="true" class="legacy" id="fs_event_change"></a></h5>
<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="#all_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="#all_fs_fswatchfilename-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 <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> 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 mjs"><span class="hljs-keyword">import</span> { watch } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-comment">// Example when handled through fs.watch() listener</span>
<span class="hljs-title function_">watch</span>(<span class="hljs-string">'./tmp'</span>, { <span class="hljs-attr">encoding</span>: <span class="hljs-string">'buffer'</span> }, <span class="hljs-function">(<span class="hljs-params">eventType, filename</span>) =></span> {
  <span class="hljs-keyword">if</span> (filename) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(filename);
    <span class="hljs-comment">// Prints: &#x3C;Buffer ...></span>
  }
});</code> <button class="copy-button">copy</button></pre>
<h5>Event: <code>'close'</code><span><a class="mark" href="#all_fs_event-close_1" id="all_fs_event-close_1">#</a></span><a aria-hidden="true" class="legacy" id="fs_event_close_1"></a></h5>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<p>Emitted when the watcher stops watching for changes. The closed
<a href="#all_fs_class-fsfswatcher" class="type">&#x3C;fs.FSWatcher></a> object is no longer usable in the event handler.</p>
<h5>Event: <code>'error'</code><span><a class="mark" href="#all_fs_event-error" id="all_fs_event-error">#</a></span><a aria-hidden="true" class="legacy" id="fs_event_error"></a></h5>
<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
<a href="#all_fs_class-fsfswatcher" class="type">&#x3C;fs.FSWatcher></a> object is no longer usable in the event handler.</p>
<h5><code>watcher.close()</code><span><a class="mark" href="#all_fs_watcherclose" id="all_fs_watcherclose">#</a></span><a aria-hidden="true" class="legacy" id="fs_watcher_close"></a></h5>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<p>Stop watching for changes on the given <a href="#all_fs_class-fsfswatcher" class="type">&#x3C;fs.FSWatcher></a>. Once stopped, the
<a href="#all_fs_class-fsfswatcher" class="type">&#x3C;fs.FSWatcher></a> object is no longer usable.</p>
<h5><code>watcher.ref()</code><span><a class="mark" href="#all_fs_watcherref" id="all_fs_watcherref">#</a></span><a aria-hidden="true" class="legacy" id="fs_watcher_ref"></a></h5>
<div class="api_metadata">
<span>Added in: v14.3.0, v12.20.0</span>
</div>
<ul>
<li>Returns: <a href="#all_fs_class-fsfswatcher" class="type">&#x3C;fs.FSWatcher></a></li>
</ul>
<p>When called, requests that the Node.js event loop <em>not</em> exit so long as the
<a href="#all_fs_class-fsfswatcher" class="type">&#x3C;fs.FSWatcher></a> is active. Calling <code>watcher.ref()</code> multiple times will have
no effect.</p>
<p>By default, all <a href="#all_fs_class-fsfswatcher" class="type">&#x3C;fs.FSWatcher></a> objects are "ref'ed", making it normally
unnecessary to call <code>watcher.ref()</code> unless <code>watcher.unref()</code> had been
called previously.</p>
<h5><code>watcher.unref()</code><span><a class="mark" href="#all_fs_watcherunref" id="all_fs_watcherunref">#</a></span><a aria-hidden="true" class="legacy" id="fs_watcher_unref"></a></h5>
<div class="api_metadata">
<span>Added in: v14.3.0, v12.20.0</span>
</div>
<ul>
<li>Returns: <a href="#all_fs_class-fsfswatcher" class="type">&#x3C;fs.FSWatcher></a></li>
</ul>
<p>When called, the active <a href="#all_fs_class-fsfswatcher" class="type">&#x3C;fs.FSWatcher></a> 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 <a href="#all_fs_class-fsfswatcher" class="type">&#x3C;fs.FSWatcher></a> object's
callback is invoked. Calling <code>watcher.unref()</code> multiple times will have
no effect.</p>
<h4>Class: <code>fs.StatWatcher</code><span><a class="mark" href="#all_fs_class-fsstatwatcher" id="all_fs_class-fsstatwatcher">#</a></span><a aria-hidden="true" class="legacy" id="fs_class_fs_statwatcher"></a></h4>
<div class="api_metadata">
<span>Added in: v14.3.0, v12.20.0</span>
</div>
<ul>
<li>Extends <a href="#all_events_class-eventemitter" class="type">&#x3C;EventEmitter></a></li>
</ul>
<p>A successful call to <code>fs.watchFile()</code> method will return a new <a href="#all_fs_class-fsstatwatcher" class="type">&#x3C;fs.StatWatcher></a>
object.</p>
<h5><code>watcher.ref()</code><span><a class="mark" href="#all_fs_watcherref_1" id="all_fs_watcherref_1">#</a></span><a aria-hidden="true" class="legacy" id="fs_watcher_ref_1"></a></h5>
<div class="api_metadata">
<span>Added in: v14.3.0, v12.20.0</span>
</div>
<ul>
<li>Returns: <a href="#all_fs_class-fsstatwatcher" class="type">&#x3C;fs.StatWatcher></a></li>
</ul>
<p>When called, requests that the Node.js event loop <em>not</em> exit so long as the
<a href="#all_fs_class-fsstatwatcher" class="type">&#x3C;fs.StatWatcher></a> is active. Calling <code>watcher.ref()</code> multiple times will have
no effect.</p>
<p>By default, all <a href="#all_fs_class-fsstatwatcher" class="type">&#x3C;fs.StatWatcher></a> objects are "ref'ed", making it normally
unnecessary to call <code>watcher.ref()</code> unless <code>watcher.unref()</code> had been
called previously.</p>
<h5><code>watcher.unref()</code><span><a class="mark" href="#all_fs_watcherunref_1" id="all_fs_watcherunref_1">#</a></span><a aria-hidden="true" class="legacy" id="fs_watcher_unref_1"></a></h5>
<div class="api_metadata">
<span>Added in: v14.3.0, v12.20.0</span>
</div>
<ul>
<li>Returns: <a href="#all_fs_class-fsstatwatcher" class="type">&#x3C;fs.StatWatcher></a></li>
</ul>
<p>When called, the active <a href="#all_fs_class-fsstatwatcher" class="type">&#x3C;fs.StatWatcher></a> 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 <a href="#all_fs_class-fsstatwatcher" class="type">&#x3C;fs.StatWatcher></a> object's
callback is invoked. Calling <code>watcher.unref()</code> multiple times will have
no effect.</p>
<h4>Class: <code>fs.ReadStream</code><span><a class="mark" href="#all_fs_class-fsreadstream" id="all_fs_class-fsreadstream">#</a></span><a aria-hidden="true" class="legacy" id="fs_class_fs_readstream"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.93</span>
</div>
<ul>
<li>Extends: <a href="#all_stream_class-streamreadable" class="type">&#x3C;stream.Readable></a></li>
</ul>
<p>Instances of <a href="#all_fs_class-fsreadstream" class="type">&#x3C;fs.ReadStream></a> are created and returned using the
<a href="#all_fs_fscreatereadstreampath-options"><code>fs.createReadStream()</code></a> function.</p>
<h5>Event: <code>'close'</code><span><a class="mark" href="#all_fs_event-close_2" id="all_fs_event-close_2">#</a></span><a aria-hidden="true" class="legacy" id="fs_event_close_2"></a></h5>
<div class="api_metadata">
<span>Added in: v0.1.93</span>
</div>
<p>Emitted when the <a href="#all_fs_class-fsreadstream" class="type">&#x3C;fs.ReadStream></a>'s underlying file descriptor has been closed.</p>
<h5>Event: <code>'open'</code><span><a class="mark" href="#all_fs_event-open" id="all_fs_event-open">#</a></span><a aria-hidden="true" class="legacy" id="fs_event_open"></a></h5>
<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 <a href="#all_fs_class-fsreadstream" class="type">&#x3C;fs.ReadStream></a>.</li>
</ul>
<p>Emitted when the <a href="#all_fs_class-fsreadstream" class="type">&#x3C;fs.ReadStream></a>'s file descriptor has been opened.</p>
<h5>Event: <code>'ready'</code><span><a class="mark" href="#all_fs_event-ready" id="all_fs_event-ready">#</a></span><a aria-hidden="true" class="legacy" id="fs_event_ready"></a></h5>
<div class="api_metadata">
<span>Added in: v9.11.0</span>
</div>
<p>Emitted when the <a href="#all_fs_class-fsreadstream" class="type">&#x3C;fs.ReadStream></a> is ready to be used.</p>
<p>Fires immediately after <code>'open'</code>.</p>
<h5><code>readStream.bytesRead</code><span><a class="mark" href="#all_fs_readstreambytesread" id="all_fs_readstreambytesread">#</a></span><a aria-hidden="true" class="legacy" id="fs_readstream_bytesread"></a></h5>
<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>
<h5><code>readStream.path</code><span><a class="mark" href="#all_fs_readstreampath" id="all_fs_readstreampath">#</a></span><a aria-hidden="true" class="legacy" id="fs_readstream_path"></a></h5>
<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="#all_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 <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a>, then
<code>readStream.path</code> will be a <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a>. If <code>fd</code> is specified, then
<code>readStream.path</code> will be <code>undefined</code>.</p>
<h5><code>readStream.pending</code><span><a class="mark" href="#all_fs_readstreampending" id="all_fs_readstreampending">#</a></span><a aria-hidden="true" class="legacy" id="fs_readstream_pending"></a></h5>
<div class="api_metadata">
<span>Added in: v11.2.0, v10.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></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>
<h4>Class: <code>fs.Stats</code><span><a class="mark" href="#all_fs_class-fsstats" id="all_fs_class-fsstats">#</a></span><a aria-hidden="true" class="legacy" id="fs_class_fs_stats"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.13.0</td>
<td><p>Public constructor is deprecated.</p></td></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 <a href="#all_fs_class-fsstats" class="type">&#x3C;fs.Stats></a> object provides information about a file.</p>
<p>Objects returned from <a href="#all_fs_fsstatpath-options-callback"><code>fs.stat()</code></a>, <a href="#all_fs_fslstatpath-options-callback"><code>fs.lstat()</code></a>, <a href="#all_fs_fsfstatfd-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>.
<code>Stat</code> objects are not to be created directly using the <code>new</code> keyword.</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> <button class="copy-button">copy</button></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> <button class="copy-button">copy</button></pre>
<h5><code>stats.isBlockDevice()</code><span><a class="mark" href="#all_fs_statsisblockdevice" id="all_fs_statsisblockdevice">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_isblockdevice"></a></h5>
<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 <a href="#all_fs_class-fsstats" class="type">&#x3C;fs.Stats></a> object describes a block device.</p>
<h5><code>stats.isCharacterDevice()</code><span><a class="mark" href="#all_fs_statsischaracterdevice" id="all_fs_statsischaracterdevice">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_ischaracterdevice"></a></h5>
<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 <a href="#all_fs_class-fsstats" class="type">&#x3C;fs.Stats></a> object describes a character device.</p>
<h5><code>stats.isDirectory()</code><span><a class="mark" href="#all_fs_statsisdirectory" id="all_fs_statsisdirectory">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_isdirectory"></a></h5>
<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 <a href="#all_fs_class-fsstats" class="type">&#x3C;fs.Stats></a> object describes a file system directory.</p>
<p>If the <a href="#all_fs_class-fsstats" class="type">&#x3C;fs.Stats></a> object was obtained from calling <a href="#all_fs_fslstatpath-options-callback"><code>fs.lstat()</code></a> on a
symbolic link which resolves to a directory, this method will return <code>false</code>.
This is because <a href="#all_fs_fslstatpath-options-callback"><code>fs.lstat()</code></a> returns information
about a symbolic link itself and not the path it resolves to.</p>
<h5><code>stats.isFIFO()</code><span><a class="mark" href="#all_fs_statsisfifo" id="all_fs_statsisfifo">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_isfifo"></a></h5>
<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 <a href="#all_fs_class-fsstats" class="type">&#x3C;fs.Stats></a> object describes a first-in-first-out (FIFO)
pipe.</p>
<h5><code>stats.isFile()</code><span><a class="mark" href="#all_fs_statsisfile" id="all_fs_statsisfile">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_isfile"></a></h5>
<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 <a href="#all_fs_class-fsstats" class="type">&#x3C;fs.Stats></a> object describes a regular file.</p>
<h5><code>stats.isSocket()</code><span><a class="mark" href="#all_fs_statsissocket" id="all_fs_statsissocket">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_issocket"></a></h5>
<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 <a href="#all_fs_class-fsstats" class="type">&#x3C;fs.Stats></a> object describes a socket.</p>
<h5><code>stats.isSymbolicLink()</code><span><a class="mark" href="#all_fs_statsissymboliclink" id="all_fs_statsissymboliclink">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_issymboliclink"></a></h5>
<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 <a href="#all_fs_class-fsstats" class="type">&#x3C;fs.Stats></a> object describes a symbolic link.</p>
<p>This method is only valid when using <a href="#all_fs_fslstatpath-options-callback"><code>fs.lstat()</code></a>.</p>
<h5><code>stats.dev</code><span><a class="mark" href="#all_fs_statsdev" id="all_fs_statsdev">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_dev"></a></h5>
<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>
<h5><code>stats.ino</code><span><a class="mark" href="#all_fs_statsino" id="all_fs_statsino">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_ino"></a></h5>
<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>
<h5><code>stats.mode</code><span><a class="mark" href="#all_fs_statsmode" id="all_fs_statsmode">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_mode"></a></h5>
<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>
<h5><code>stats.nlink</code><span><a class="mark" href="#all_fs_statsnlink" id="all_fs_statsnlink">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_nlink"></a></h5>
<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>
<h5><code>stats.uid</code><span><a class="mark" href="#all_fs_statsuid" id="all_fs_statsuid">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_uid"></a></h5>
<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>
<h5><code>stats.gid</code><span><a class="mark" href="#all_fs_statsgid" id="all_fs_statsgid">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_gid"></a></h5>
<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>
<h5><code>stats.rdev</code><span><a class="mark" href="#all_fs_statsrdev" id="all_fs_statsrdev">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_rdev"></a></h5>
<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 represents a device.</p>
<h5><code>stats.size</code><span><a class="mark" href="#all_fs_statssize" id="all_fs_statssize">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_size"></a></h5>
<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>
<p>If the underlying file system does not support getting the size of the file,
this will be <code>0</code>.</p>
<h5><code>stats.blksize</code><span><a class="mark" href="#all_fs_statsblksize" id="all_fs_statsblksize">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_blksize"></a></h5>
<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>
<h5><code>stats.blocks</code><span><a class="mark" href="#all_fs_statsblocks" id="all_fs_statsblocks">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_blocks"></a></h5>
<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>
<h5><code>stats.atimeMs</code><span><a class="mark" href="#all_fs_statsatimems" id="all_fs_statsatimems">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_atimems"></a></h5>
<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>
<h5><code>stats.mtimeMs</code><span><a class="mark" href="#all_fs_statsmtimems" id="all_fs_statsmtimems">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_mtimems"></a></h5>
<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>
<h5><code>stats.ctimeMs</code><span><a class="mark" href="#all_fs_statsctimems" id="all_fs_statsctimems">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_ctimems"></a></h5>
<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>
<h5><code>stats.birthtimeMs</code><span><a class="mark" href="#all_fs_statsbirthtimems" id="all_fs_statsbirthtimems">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_birthtimems"></a></h5>
<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>
<h5><code>stats.atimeNs</code><span><a class="mark" href="#all_fs_statsatimens" id="all_fs_statsatimens">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_atimens"></a></h5>
<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>
<h5><code>stats.mtimeNs</code><span><a class="mark" href="#all_fs_statsmtimens" id="all_fs_statsmtimens">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_mtimens"></a></h5>
<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>
<h5><code>stats.ctimeNs</code><span><a class="mark" href="#all_fs_statsctimens" id="all_fs_statsctimens">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_ctimens"></a></h5>
<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>
<h5><code>stats.birthtimeNs</code><span><a class="mark" href="#all_fs_statsbirthtimens" id="all_fs_statsbirthtimens">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_birthtimens"></a></h5>
<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>
<h5><code>stats.atime</code><span><a class="mark" href="#all_fs_statsatime" id="all_fs_statsatime">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_atime"></a></h5>
<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>
<h5><code>stats.mtime</code><span><a class="mark" href="#all_fs_statsmtime" id="all_fs_statsmtime">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_mtime"></a></h5>
<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>
<h5><code>stats.ctime</code><span><a class="mark" href="#all_fs_statsctime" id="all_fs_statsctime">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_ctime"></a></h5>
<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>
<h5><code>stats.birthtime</code><span><a class="mark" href="#all_fs_statsbirthtime" id="all_fs_statsbirthtime">#</a></span><a aria-hidden="true" class="legacy" id="fs_stats_birthtime"></a></h5>
<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>
<h5>Stat time values<span><a class="mark" href="#all_fs_stat-time-values" id="all_fs_stat-time-values">#</a></span><a aria-hidden="true" class="legacy" id="fs_stat_time_values"></a></h5>
<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 file systems 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>
<h4>Class: <code>fs.StatFs</code><span><a class="mark" href="#all_fs_class-fsstatfs" id="all_fs_class-fsstatfs">#</a></span><a aria-hidden="true" class="legacy" id="fs_class_fs_statfs"></a></h4>
<div class="api_metadata">
<span>Added in: v19.6.0, v18.15.0</span>
</div>
<p>Provides information about a mounted file system.</p>
<p>Objects returned from <a href="#all_fs_fsstatfspath-options-callback"><code>fs.statfs()</code></a> and its synchronous counterpart are of
this type. If <code>bigint</code> in the <code>options</code> passed to those methods is <code>true</code>, the
numeric values will be <code>bigint</code> instead of <code>number</code>.</p>
<pre><code class="language-console">StatFs {
  type: 1397114950,
  bsize: 4096,
  blocks: 121938943,
  bfree: 61058895,
  bavail: 61058895,
  files: 999,
  ffree: 1000000
}</code> <button class="copy-button">copy</button></pre>
<p><code>bigint</code> version:</p>
<pre><code class="language-console">StatFs {
  type: 1397114950n,
  bsize: 4096n,
  blocks: 121938943n,
  bfree: 61058895n,
  bavail: 61058895n,
  files: 999n,
  ffree: 1000000n
}</code> <button class="copy-button">copy</button></pre>
<h5><code>statfs.bavail</code><span><a class="mark" href="#all_fs_statfsbavail" id="all_fs_statfsbavail">#</a></span><a aria-hidden="true" class="legacy" id="fs_statfs_bavail"></a></h5>
<div class="api_metadata">
<span>Added in: v19.6.0, v18.15.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>Free blocks available to unprivileged users.</p>
<h5><code>statfs.bfree</code><span><a class="mark" href="#all_fs_statfsbfree" id="all_fs_statfsbfree">#</a></span><a aria-hidden="true" class="legacy" id="fs_statfs_bfree"></a></h5>
<div class="api_metadata">
<span>Added in: v19.6.0, v18.15.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>Free blocks in file system.</p>
<h5><code>statfs.blocks</code><span><a class="mark" href="#all_fs_statfsblocks" id="all_fs_statfsblocks">#</a></span><a aria-hidden="true" class="legacy" id="fs_statfs_blocks"></a></h5>
<div class="api_metadata">
<span>Added in: v19.6.0, v18.15.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>Total data blocks in file system.</p>
<h5><code>statfs.bsize</code><span><a class="mark" href="#all_fs_statfsbsize" id="all_fs_statfsbsize">#</a></span><a aria-hidden="true" class="legacy" id="fs_statfs_bsize"></a></h5>
<div class="api_metadata">
<span>Added in: v19.6.0, v18.15.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>Optimal transfer block size.</p>
<h5><code>statfs.ffree</code><span><a class="mark" href="#all_fs_statfsffree" id="all_fs_statfsffree">#</a></span><a aria-hidden="true" class="legacy" id="fs_statfs_ffree"></a></h5>
<div class="api_metadata">
<span>Added in: v19.6.0, v18.15.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>Free file nodes in file system.</p>
<h5><code>statfs.files</code><span><a class="mark" href="#all_fs_statfsfiles" id="all_fs_statfsfiles">#</a></span><a aria-hidden="true" class="legacy" id="fs_statfs_files"></a></h5>
<div class="api_metadata">
<span>Added in: v19.6.0, v18.15.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>Total file nodes in file system.</p>
<h5><code>statfs.type</code><span><a class="mark" href="#all_fs_statfstype" id="all_fs_statfstype">#</a></span><a aria-hidden="true" class="legacy" id="fs_statfs_type"></a></h5>
<div class="api_metadata">
<span>Added in: v19.6.0, v18.15.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>Type of file system.</p>
<h4>Class: <code>fs.WriteStream</code><span><a class="mark" href="#all_fs_class-fswritestream" id="all_fs_class-fswritestream">#</a></span><a aria-hidden="true" class="legacy" id="fs_class_fs_writestream"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.93</span>
</div>
<ul>
<li>Extends <a href="#all_stream_class-streamwritable" class="type">&#x3C;stream.Writable></a></li>
</ul>
<p>Instances of <a href="#all_fs_class-fswritestream" class="type">&#x3C;fs.WriteStream></a> are created and returned using the
<a href="#all_fs_fscreatewritestreampath-options"><code>fs.createWriteStream()</code></a> function.</p>
<h5>Event: <code>'close'</code><span><a class="mark" href="#all_fs_event-close_3" id="all_fs_event-close_3">#</a></span><a aria-hidden="true" class="legacy" id="fs_event_close_3"></a></h5>
<div class="api_metadata">
<span>Added in: v0.1.93</span>
</div>
<p>Emitted when the <a href="#all_fs_class-fswritestream" class="type">&#x3C;fs.WriteStream></a>'s underlying file descriptor has been closed.</p>
<h5>Event: <code>'open'</code><span><a class="mark" href="#all_fs_event-open_1" id="all_fs_event-open_1">#</a></span><a aria-hidden="true" class="legacy" id="fs_event_open_1"></a></h5>
<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 <a href="#all_fs_class-fswritestream" class="type">&#x3C;fs.WriteStream></a>.</li>
</ul>
<p>Emitted when the <a href="#all_fs_class-fswritestream" class="type">&#x3C;fs.WriteStream></a>'s file is opened.</p>
<h5>Event: <code>'ready'</code><span><a class="mark" href="#all_fs_event-ready_1" id="all_fs_event-ready_1">#</a></span><a aria-hidden="true" class="legacy" id="fs_event_ready_1"></a></h5>
<div class="api_metadata">
<span>Added in: v9.11.0</span>
</div>
<p>Emitted when the <a href="#all_fs_class-fswritestream" class="type">&#x3C;fs.WriteStream></a> is ready to be used.</p>
<p>Fires immediately after <code>'open'</code>.</p>
<h5><code>writeStream.bytesWritten</code><span><a class="mark" href="#all_fs_writestreambyteswritten" id="all_fs_writestreambyteswritten">#</a></span><a aria-hidden="true" class="legacy" id="fs_writestream_byteswritten"></a></h5>
<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>
<h5><code>writeStream.close([callback])</code><span><a class="mark" href="#all_fs_writestreamclosecallback" id="all_fs_writestreamclosecallback">#</a></span><a aria-hidden="true" class="legacy" id="fs_writestream_close_callback"></a></h5>
<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>
<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>Closes <code>writeStream</code>. Optionally accepts a
callback that will be executed once the <code>writeStream</code>
is closed.</p>
<h5><code>writeStream.path</code><span><a class="mark" href="#all_fs_writestreampath" id="all_fs_writestreampath">#</a></span><a aria-hidden="true" class="legacy" id="fs_writestream_path"></a></h5>
<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="#all_fs_fscreatewritestreampath-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 <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a>, then
<code>writeStream.path</code> will be a <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a>.</p>
<h5><code>writeStream.pending</code><span><a class="mark" href="#all_fs_writestreampending" id="all_fs_writestreampending">#</a></span><a aria-hidden="true" class="legacy" id="fs_writestream_pending"></a></h5>
<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>
<h4><code>fs.constants</code><span><a class="mark" href="#all_fs_fsconstants" id="all_fs_fsconstants">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_constants"></a></h4>
<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.</p>
<h5>FS constants<span><a class="mark" href="#all_fs_fs-constants" id="all_fs_fs-constants">#</a></span><a aria-hidden="true" class="legacy" id="fs_fs_constants_1"></a></h5>
<p>The following constants are exported by <code>fs.constants</code> and <code>fsPromises.constants</code>.</p>
<p>Not every constant will be available on every operating system;
this is especially important for Windows, where many of the POSIX specific
definitions are not available.
For portable applications it is recommended to check for their presence
before use.</p>
<p>To use more than one constant, use the bitwise OR <code>|</code> operator.</p>
<p>Example:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { open, constants } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-keyword">const</span> {
  <span class="hljs-variable constant_">O_RDWR</span>,
  <span class="hljs-variable constant_">O_CREAT</span>,
  <span class="hljs-variable constant_">O_EXCL</span>,
} = constants;

<span class="hljs-title function_">open</span>(<span class="hljs-string">'/path/to/my/file'</span>, <span class="hljs-variable constant_">O_RDWR</span> | <span class="hljs-variable constant_">O_CREAT</span> | <span class="hljs-variable constant_">O_EXCL</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
  <span class="hljs-comment">// ...</span>
});</code> <button class="copy-button">copy</button></pre>
<h6>File access constants<span><a class="mark" href="#all_fs_file-access-constants" id="all_fs_file-access-constants">#</a></span><a aria-hidden="true" class="legacy" id="fs_file_access_constants"></a></h6>
<p>The following constants are meant for use as the <code>mode</code> parameter passed to
<a href="#all_fs_fspromisesaccesspath-mode"><code>fsPromises.access()</code></a>, <a href="#all_fs_fsaccesspath-mode-callback"><code>fs.access()</code></a>, and <a href="#all_fs_fsaccesssyncpath-mode"><code>fs.accessSync()</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>
<p>The definitions are also available on Windows.</p>
<h6>File copy constants<span><a class="mark" href="#all_fs_file-copy-constants" id="all_fs_file-copy-constants">#</a></span><a aria-hidden="true" class="legacy" id="fs_file_copy_constants"></a></h6>
<p>The following constants are meant for use with <a href="#all_fs_fscopyfilesrc-dest-mode-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>
<p>The definitions are also available on Windows.</p>
<h6>File open constants<span><a class="mark" href="#all_fs_file-open-constants" id="all_fs_file-open-constants">#</a></span><a aria-hidden="true" class="legacy" id="fs_file_open_constants"></a></h6>
<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>
<p>On Windows, only <code>O_APPEND</code>, <code>O_CREAT</code>, <code>O_EXCL</code>, <code>O_RDONLY</code>, <code>O_RDWR</code>,
<code>O_TRUNC</code>, <code>O_WRONLY</code>, and <code>UV_FS_O_FILEMAP</code> are available.</p>
<h6>File type constants<span><a class="mark" href="#all_fs_file-type-constants" id="all_fs_file-type-constants">#</a></span><a aria-hidden="true" class="legacy" id="fs_file_type_constants"></a></h6>
<p>The following constants are meant for use with the <a href="#all_fs_class-fsstats" class="type">&#x3C;fs.Stats></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>
<p>On Windows, only <code>S_IFCHR</code>, <code>S_IFDIR</code>, <code>S_IFLNK</code>, <code>S_IFMT</code>, and <code>S_IFREG</code>,
are available.</p>
<h6>File mode constants<span><a class="mark" href="#all_fs_file-mode-constants" id="all_fs_file-mode-constants">#</a></span><a aria-hidden="true" class="legacy" id="fs_file_mode_constants"></a></h6>
<p>The following constants are meant for use with the <a href="#all_fs_class-fsstats" class="type">&#x3C;fs.Stats></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>
<p>On Windows, only <code>S_IRUSR</code> and <code>S_IWUSR</code> are available.</p>
</section><section><h3>Notes<span><a class="mark" href="#all_fs_notes" id="all_fs_notes">#</a></span><a aria-hidden="true" class="legacy" id="fs_notes"></a></h3>
<h4>Ordering of callback and promise-based operations<span><a class="mark" href="#all_fs_ordering-of-callback-and-promise-based-operations" id="all_fs_ordering-of-callback-and-promise-based-operations">#</a></span><a aria-hidden="true" class="legacy" id="fs_ordering_of_callback_and_promise_based_operations"></a></h4>
<p>Because they are executed asynchronously by the underlying thread pool,
there is no guaranteed ordering when using either the callback or
promise-based methods.</p>
<p>For example, the following is prone to error because the <code>fs.stat()</code>
operation might complete before the <code>fs.rename()</code> operation:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);

fs.<span class="hljs-title function_">rename</span>(<span class="hljs-string">'/tmp/hello'</span>, <span class="hljs-string">'/tmp/world'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'renamed complete'</span>);
});
fs.<span class="hljs-title function_">stat</span>(<span class="hljs-string">'/tmp/world'</span>, <span class="hljs-function">(<span class="hljs-params">err, stats</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`stats: <span class="hljs-subst">${<span class="hljs-built_in">JSON</span>.stringify(stats)}</span>`</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>It is important to correctly order the operations by awaiting the results
of one before invoking the other:</p>

<pre class="with-53-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { rename, stat } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;

<span class="hljs-keyword">const</span> oldPath = <span class="hljs-string">'/tmp/hello'</span>;
<span class="hljs-keyword">const</span> newPath = <span class="hljs-string">'/tmp/world'</span>;

<span class="hljs-keyword">try</span> {
  <span class="hljs-keyword">await</span> <span class="hljs-title function_">rename</span>(oldPath, newPath);
  <span class="hljs-keyword">const</span> stats = <span class="hljs-keyword">await</span> <span class="hljs-title function_">stat</span>(newPath);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`stats: <span class="hljs-subst">${<span class="hljs-built_in">JSON</span>.stringify(stats)}</span>`</span>);
} <span class="hljs-keyword">catch</span> (error) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'there was an error:'</span>, error.<span class="hljs-property">message</span>);
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { rename, stat } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs/promises'</span>);

(<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>(<span class="hljs-params">oldPath, newPath</span>) {
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">await</span> <span class="hljs-title function_">rename</span>(oldPath, newPath);
    <span class="hljs-keyword">const</span> stats = <span class="hljs-keyword">await</span> <span class="hljs-title function_">stat</span>(newPath);
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`stats: <span class="hljs-subst">${<span class="hljs-built_in">JSON</span>.stringify(stats)}</span>`</span>);
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'there was an error:'</span>, error.<span class="hljs-property">message</span>);
  }
})(<span class="hljs-string">'/tmp/hello'</span>, <span class="hljs-string">'/tmp/world'</span>);</code><button class="copy-button">copy</button></pre>
<p>Or, when using the callback APIs, move the <code>fs.stat()</code> call into the callback
of the <code>fs.rename()</code> operation:</p>

<pre class="with-53-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { rename, stat } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-title function_">rename</span>(<span class="hljs-string">'/tmp/hello'</span>, <span class="hljs-string">'/tmp/world'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-title function_">stat</span>(<span class="hljs-string">'/tmp/world'</span>, <span class="hljs-function">(<span class="hljs-params">err, stats</span>) =></span> {
    <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`stats: <span class="hljs-subst">${<span class="hljs-built_in">JSON</span>.stringify(stats)}</span>`</span>);
  });
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { rename, stat } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs/promises'</span>);

<span class="hljs-title function_">rename</span>(<span class="hljs-string">'/tmp/hello'</span>, <span class="hljs-string">'/tmp/world'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-title function_">stat</span>(<span class="hljs-string">'/tmp/world'</span>, <span class="hljs-function">(<span class="hljs-params">err, stats</span>) =></span> {
    <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`stats: <span class="hljs-subst">${<span class="hljs-built_in">JSON</span>.stringify(stats)}</span>`</span>);
  });
});</code><button class="copy-button">copy</button></pre>
<h4>File paths<span><a class="mark" href="#all_fs_file-paths" id="all_fs_file-paths">#</a></span><a aria-hidden="true" class="legacy" id="fs_file_paths"></a></h4>
<p>Most <code>fs</code> operations accept file paths that may be specified in the form of
a string, a <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a>, or a <a href="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></a> object using the <code>file:</code> protocol.</p>
<h5>String paths<span><a class="mark" href="#all_fs_string-paths" id="all_fs_string-paths">#</a></span><a aria-hidden="true" class="legacy" id="fs_string_paths"></a></h5>
<p>String 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 determined by calling <code>process.cwd()</code>.</p>
<p>Example using an absolute path on POSIX:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { open } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;

<span class="hljs-keyword">let</span> fd;
<span class="hljs-keyword">try</span> {
  fd = <span class="hljs-keyword">await</span> <span class="hljs-title function_">open</span>(<span class="hljs-string">'/open/some/file.txt'</span>, <span class="hljs-string">'r'</span>);
  <span class="hljs-comment">// Do something with the file</span>
} <span class="hljs-keyword">finally</span> {
  <span class="hljs-keyword">await</span> fd?.<span class="hljs-title function_">close</span>();
}</code> <button class="copy-button">copy</button></pre>
<p>Example using a relative path on POSIX (relative to <code>process.cwd()</code>):</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { open } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;

<span class="hljs-keyword">let</span> fd;
<span class="hljs-keyword">try</span> {
  fd = <span class="hljs-keyword">await</span> <span class="hljs-title function_">open</span>(<span class="hljs-string">'file.txt'</span>, <span class="hljs-string">'r'</span>);
  <span class="hljs-comment">// Do something with the file</span>
} <span class="hljs-keyword">finally</span> {
  <span class="hljs-keyword">await</span> fd?.<span class="hljs-title function_">close</span>();
}</code> <button class="copy-button">copy</button></pre>
<h5>File URL paths<span><a class="mark" href="#all_fs_file-url-paths" id="all_fs_file-url-paths">#</a></span><a aria-hidden="true" class="legacy" id="fs_file_url_paths"></a></h5>
<div class="api_metadata">
<span>Added in: v7.6.0</span>
</div>
<p>For most <code>node:fs</code> module functions, the <code>path</code> or <code>filename</code> argument may be
passed as a <a href="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></a> object using the <code>file:</code> protocol.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { readFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-title function_">readFileSync</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file:///tmp/hello'</span>));</code> <button class="copy-button">copy</button></pre>
<p><code>file:</code> URLs are always absolute paths.</p>
<h6>Platform-specific considerations<span><a class="mark" href="#all_fs_platform-specific-considerations" id="all_fs_platform-specific-considerations">#</a></span><a aria-hidden="true" class="legacy" id="fs_platform_specific_considerations"></a></h6>
<p>On Windows, <code>file:</code> <a href="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></a>s with a host name convert to UNC paths, while <code>file:</code>
<a href="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></a>s with drive letters convert to local absolute paths. <code>file:</code> <a href="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></a>s
with no host name and no drive letter will result in an error:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { readFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-comment">// On Windows :</span>

<span class="hljs-comment">// - WHATWG file URLs with hostname convert to UNC path</span>
<span class="hljs-comment">// file://hostname/p/a/t/h/file => \\hostname\p\a\t\h\file</span>
<span class="hljs-title function_">readFileSync</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file://hostname/p/a/t/h/file'</span>));

<span class="hljs-comment">// - WHATWG file URLs with drive letters convert to absolute path</span>
<span class="hljs-comment">// file:///C:/tmp/hello => C:\tmp\hello</span>
<span class="hljs-title function_">readFileSync</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file:///C:/tmp/hello'</span>));

<span class="hljs-comment">// - WHATWG file URLs without hostname must have a drive letters</span>
<span class="hljs-title function_">readFileSync</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file:///notdriveletter/p/a/t/h/file'</span>));
<span class="hljs-title function_">readFileSync</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file:///c/p/a/t/h/file'</span>));
<span class="hljs-comment">// TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must be absolute</span></code> <button class="copy-button">copy</button></pre>
<p><code>file:</code> <a href="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></a>s with drive letters must use <code>:</code> as a separator just after
the drive letter. Using another separator will result in an error.</p>
<p>On all other platforms, <code>file:</code> <a href="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></a>s with a host name are unsupported and
will result in an error:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { readFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-comment">// On other platforms:</span>

<span class="hljs-comment">// - WHATWG file URLs with hostname are unsupported</span>
<span class="hljs-comment">// file://hostname/p/a/t/h/file => throw!</span>
<span class="hljs-title function_">readFileSync</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file://hostname/p/a/t/h/file'</span>));
<span class="hljs-comment">// TypeError [ERR_INVALID_FILE_URL_PATH]: must be absolute</span>

<span class="hljs-comment">// - WHATWG file URLs convert to absolute path</span>
<span class="hljs-comment">// file:///tmp/hello => /tmp/hello</span>
<span class="hljs-title function_">readFileSync</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file:///tmp/hello'</span>));</code> <button class="copy-button">copy</button></pre>
<p>A <code>file:</code> <a href="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></a> having encoded slash characters will result in an error on all
platforms:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { readFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-comment">// On Windows</span>
<span class="hljs-title function_">readFileSync</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file:///C:/p/a/t/h/%2F'</span>));
<span class="hljs-title function_">readFileSync</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file:///C:/p/a/t/h/%2f'</span>));
<span class="hljs-comment">/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded
\ or / characters */</span>

<span class="hljs-comment">// On POSIX</span>
<span class="hljs-title function_">readFileSync</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file:///p/a/t/h/%2F'</span>));
<span class="hljs-title function_">readFileSync</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file:///p/a/t/h/%2f'</span>));
<span class="hljs-comment">/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded
/ characters */</span></code> <button class="copy-button">copy</button></pre>
<p>On Windows, <code>file:</code> <a href="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></a>s having encoded backslash will result in an error:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { readFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-comment">// On Windows</span>
<span class="hljs-title function_">readFileSync</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file:///C:/path/%5C'</span>));
<span class="hljs-title function_">readFileSync</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file:///C:/path/%5c'</span>));
<span class="hljs-comment">/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded
\ or / characters */</span></code> <button class="copy-button">copy</button></pre>
<h5>Buffer paths<span><a class="mark" href="#all_fs_buffer-paths" id="all_fs_buffer-paths">#</a></span><a aria-hidden="true" class="legacy" id="fs_buffer_paths"></a></h5>
<p>Paths specified using a <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></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, <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> paths may
be relative or absolute:</p>
<p>Example using an absolute path on POSIX:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { open } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">let</span> fd;
<span class="hljs-keyword">try</span> {
  fd = <span class="hljs-keyword">await</span> <span class="hljs-title function_">open</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'/open/some/file.txt'</span>), <span class="hljs-string">'r'</span>);
  <span class="hljs-comment">// Do something with the file</span>
} <span class="hljs-keyword">finally</span> {
  <span class="hljs-keyword">await</span> fd?.<span class="hljs-title function_">close</span>();
}</code> <button class="copy-button">copy</button></pre>
<h5>Per-drive working directories on Windows<span><a class="mark" href="#all_fs_per-drive-working-directories-on-windows" id="all_fs_per-drive-working-directories-on-windows">#</a></span><a aria-hidden="true" class="legacy" id="fs_per_drive_working_directories_on_windows"></a></h5>
<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>
<h4>File descriptors<span><a class="mark" href="#all_fs_file-descriptors_1" id="all_fs_file-descriptors_1">#</a></span><a aria-hidden="true" class="legacy" id="fs_file_descriptors_1"></a></h4>
<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
differences between operating systems and assigns all open files a numeric file
descriptor.</p>
<p>The callback-based <code>fs.open()</code>, and synchronous <code>fs.openSync()</code> methods open a
file and 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>
<p>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>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { open, close, fstat } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-keyword">function</span> <span class="hljs-title function_">closeFd</span>(<span class="hljs-params">fd</span>) {
  <span class="hljs-title function_">close</span>(fd, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
    <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  });
}

<span class="hljs-title function_">open</span>(<span class="hljs-string">'/open/some/file.txt'</span>, <span class="hljs-string">'r'</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-keyword">try</span> {
    <span class="hljs-title function_">fstat</span>(fd, <span class="hljs-function">(<span class="hljs-params">err, stat</span>) =></span> {
      <span class="hljs-keyword">if</span> (err) {
        <span class="hljs-title function_">closeFd</span>(fd);
        <span class="hljs-keyword">throw</span> err;
      }

      <span class="hljs-comment">// use stat</span>

      <span class="hljs-title function_">closeFd</span>(fd);
    });
  } <span class="hljs-keyword">catch</span> (err) {
    <span class="hljs-title function_">closeFd</span>(fd);
    <span class="hljs-keyword">throw</span> err;
  }
});</code> <button class="copy-button">copy</button></pre>
<p>The promise-based APIs use a <a href="#all_fs_class-filehandle" class="type">&#x3C;FileHandle></a> object in place of the numeric
file descriptor. These objects are better managed by the system to ensure
that resources are not leaked. However, it is still required that they are
closed when operations are completed:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { open } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;

<span class="hljs-keyword">let</span> file;
<span class="hljs-keyword">try</span> {
  file = <span class="hljs-keyword">await</span> <span class="hljs-title function_">open</span>(<span class="hljs-string">'/open/some/file.txt'</span>, <span class="hljs-string">'r'</span>);
  <span class="hljs-keyword">const</span> stat = <span class="hljs-keyword">await</span> file.<span class="hljs-title function_">stat</span>();
  <span class="hljs-comment">// use stat</span>
} <span class="hljs-keyword">finally</span> {
  <span class="hljs-keyword">await</span> file.<span class="hljs-title function_">close</span>();
}</code> <button class="copy-button">copy</button></pre>
<h4>Threadpool usage<span><a class="mark" href="#all_fs_threadpool-usage" id="all_fs_threadpool-usage">#</a></span><a aria-hidden="true" class="legacy" id="fs_threadpool_usage"></a></h4>
<p>All callback and promise-based file system APIs (with the exception of
<code>fs.FSWatcher()</code>) use libuv's threadpool. This can have surprising and negative
performance implications for some applications. See the
<a href="#all_cli_uv_threadpool_sizesize"><code>UV_THREADPOOL_SIZE</code></a> documentation for more information.</p>
<h4>File system flags<span><a class="mark" href="#all_fs_file-system-flags" id="all_fs_file-system-flags">#</a></span><a aria-hidden="true" class="legacy" id="fs_file_system_flags"></a></h4>
<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>'rs'</code>: Open file for reading in synchronous mode.
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>) causes the operation to
return an error if the path already exists. On POSIX, if the path is a symbolic
link, using <code>O_EXCL</code> returns an error even if the link is to a path that does
not exist. The exclusive flag might 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 the <code>flag</code> option to be
set to <code>'r+'</code> rather than the default <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"><span class="hljs-comment">// macOS and Linux</span>
fs.<span class="hljs-title function_">open</span>(<span class="hljs-string">'&#x3C;directory>'</span>, <span class="hljs-string">'a+'</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
  <span class="hljs-comment">// => [Error: EISDIR: illegal operation on a directory, open &#x3C;directory>]</span>
});

<span class="hljs-comment">// Windows and FreeBSD</span>
fs.<span class="hljs-title function_">open</span>(<span class="hljs-string">'&#x3C;directory>'</span>, <span class="hljs-string">'a+'</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
  <span class="hljs-comment">// => null, &#x3C;fd></span>
});</code> <button class="copy-button">copy</button></pre>
<p>On Windows, opening an existing hidden file using the <code>'w'</code> flag (either
through <code>fs.open()</code>, <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></section>
        </section>
<section><h2>Global objects<span><a class="mark" href="#all_globals_global-objects" id="all_globals_global-objects">#</a></span><a aria-hidden="true" class="legacy" id="globals_global_objects"></a></h2>


<p>These objects are available in all modules.</p>
<p>The following variables may appear to be global but are not. They exist only in
the scope of <a href="modules.html">CommonJS modules</a>:</p>
<ul>
<li><a href="#all_modules___dirname"><code>__dirname</code></a></li>
<li><a href="#all_modules___filename"><code>__filename</code></a></li>
<li><a href="#all_modules_exports"><code>exports</code></a></li>
<li><a href="#all_modules_module"><code>module</code></a></li>
<li><a href="#all_modules_requireid"><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>
<section><h3>Class: <code>AbortController</code><span><a class="mark" href="#all_globals_class-abortcontroller" id="all_globals_class-abortcontroller">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_abortcontroller"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.4.0</td>
<td><p>No longer experimental.</p></td></tr>
<tr><td>v15.0.0, v14.17.0</td>
<td><p><span>Added in: v15.0.0, v14.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>

<p>A utility class used to signal cancelation in selected <code>Promise</code>-based APIs.
The API is based on the Web API <a href="https://developer.mozilla.org/en-US/docs/Web/API/AbortController"><code>AbortController</code></a>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> ac = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();

ac.<span class="hljs-property">signal</span>.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">'abort'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Aborted!'</span>),
                           { <span class="hljs-attr">once</span>: <span class="hljs-literal">true</span> });

ac.<span class="hljs-title function_">abort</span>();

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(ac.<span class="hljs-property">signal</span>.<span class="hljs-property">aborted</span>);  <span class="hljs-comment">// Prints true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>abortController.abort([reason])</code><span><a class="mark" href="#all_globals_abortcontrollerabortreason" id="all_globals_abortcontrollerabortreason">#</a></span><a aria-hidden="true" class="legacy" id="globals_abortcontroller_abort_reason"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.2.0, v16.14.0</td>
<td><p>Added the new optional reason argument.</p></td></tr>
<tr><td>v15.0.0, v14.17.0</td>
<td><p><span>Added in: v15.0.0, v14.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>reason</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> An optional reason, retrievable on the <code>AbortSignal</code>'s
<code>reason</code> property.</li>
</ul>
<p>Triggers the abort signal, causing the <code>abortController.signal</code> to emit
the <code>'abort'</code> event.</p>
<h4><code>abortController.signal</code><span><a class="mark" href="#all_globals_abortcontrollersignal" id="all_globals_abortcontrollersignal">#</a></span><a aria-hidden="true" class="legacy" id="globals_abortcontroller_signal"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0, v14.17.0</span>
</div>
<ul>
<li>Type: <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a></li>
</ul>
<h4>Class: <code>AbortSignal</code><span><a class="mark" href="#all_globals_class-abortsignal" id="all_globals_class-abortsignal">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_abortsignal"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0, v14.17.0</span>
</div>
<ul>
<li>Extends: <a href="#all_events_class-eventtarget" class="type">&#x3C;EventTarget></a></li>
</ul>
<p>The <code>AbortSignal</code> is used to notify observers when the
<code>abortController.abort()</code> method is called.</p>
<h5>Static method: <code>AbortSignal.abort([reason])</code><span><a class="mark" href="#all_globals_static-method-abortsignalabortreason" id="all_globals_static-method-abortsignalabortreason">#</a></span><a aria-hidden="true" class="legacy" id="globals_static_method_abortsignal_abort_reason"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.2.0, v16.14.0</td>
<td><p>Added the new optional reason argument.</p></td></tr>
<tr><td>v15.12.0, v14.17.0</td>
<td><p><span>Added in: v15.12.0, v14.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>reason</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="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a></li>
</ul>
<p>Returns a new already aborted <code>AbortSignal</code>.</p>
<h5>Static method: <code>AbortSignal.timeout(delay)</code><span><a class="mark" href="#all_globals_static-method-abortsignaltimeoutdelay" id="all_globals_static-method-abortsignaltimeoutdelay">#</a></span><a aria-hidden="true" class="legacy" id="globals_static_method_abortsignal_timeout_delay"></a></h5>
<div class="api_metadata">
<span>Added in: v17.3.0, v16.14.0</span>
</div>
<ul>
<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 triggering
the AbortSignal.</li>
</ul>
<p>Returns a new <code>AbortSignal</code> which will be aborted in <code>delay</code> milliseconds.</p>
<h5>Static method: <code>AbortSignal.any(signals)</code><span><a class="mark" href="#all_globals_static-method-abortsignalanysignals" id="all_globals_static-method-abortsignalanysignals">#</a></span><a aria-hidden="true" class="legacy" id="globals_static_method_abortsignal_any_signals"></a></h5>
<div class="api_metadata">
<span>Added in: v20.3.0</span>
</div>
<ul>
<li><code>signals</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal[]></a> The <code>AbortSignal</code>s of which to compose a new <code>AbortSignal</code>.</li>
</ul>
<p>Returns a new <code>AbortSignal</code> which will be aborted if any of the provided
signals are aborted. Its <a href="#all_globals_abortsignalreason"><code>abortSignal.reason</code></a> will be set to whichever
one of the <code>signals</code> caused it to be aborted.</p>
<h5>Event: <code>'abort'</code><span><a class="mark" href="#all_globals_event-abort" id="all_globals_event-abort">#</a></span><a aria-hidden="true" class="legacy" id="globals_event_abort"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0, v14.17.0</span>
</div>
<p>The <code>'abort'</code> event is emitted when the <code>abortController.abort()</code> method
is called. The callback is invoked with a single object argument with a
single <code>type</code> property set to <code>'abort'</code>:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> ac = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();

<span class="hljs-comment">// Use either the onabort property...</span>
ac.<span class="hljs-property">signal</span>.<span class="hljs-property">onabort</span> = <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'aborted!'</span>);

<span class="hljs-comment">// Or the EventTarget API...</span>
ac.<span class="hljs-property">signal</span>.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">'abort'</span>, <span class="hljs-function">(<span class="hljs-params">event</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(event.<span class="hljs-property">type</span>);  <span class="hljs-comment">// Prints 'abort'</span>
}, { <span class="hljs-attr">once</span>: <span class="hljs-literal">true</span> });

ac.<span class="hljs-title function_">abort</span>();</code> <button class="copy-button">copy</button></pre>
<p>The <code>AbortController</code> with which the <code>AbortSignal</code> is associated will only
ever trigger the <code>'abort'</code> event once. We recommended that code check
that the <code>abortSignal.aborted</code> attribute is <code>false</code> before adding an <code>'abort'</code>
event listener.</p>
<p>Any event listeners attached to the <code>AbortSignal</code> should use the
<code>{ once: true }</code> option (or, if using the <code>EventEmitter</code> APIs to attach a
listener, use the <code>once()</code> method) to ensure that the event listener is
removed as soon as the <code>'abort'</code> event is handled. Failure to do so may
result in memory leaks.</p>
<h5><code>abortSignal.aborted</code><span><a class="mark" href="#all_globals_abortsignalaborted" id="all_globals_abortsignalaborted">#</a></span><a aria-hidden="true" class="legacy" id="globals_abortsignal_aborted"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0, v14.17.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> True after the <code>AbortController</code> has been aborted.</li>
</ul>
<h5><code>abortSignal.onabort</code><span><a class="mark" href="#all_globals_abortsignalonabort" id="all_globals_abortsignalonabort">#</a></span><a aria-hidden="true" class="legacy" id="globals_abortsignal_onabort"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0, v14.17.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a></li>
</ul>
<p>An optional callback function that may be set by user code to be notified
when the <code>abortController.abort()</code> function has been called.</p>
<h5><code>abortSignal.reason</code><span><a class="mark" href="#all_globals_abortsignalreason" id="all_globals_abortsignalreason">#</a></span><a aria-hidden="true" class="legacy" id="globals_abortsignal_reason"></a></h5>
<div class="api_metadata">
<span>Added in: v17.2.0, v16.14.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
</ul>
<p>An optional reason specified when the <code>AbortSignal</code> was triggered.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> ac = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
ac.<span class="hljs-title function_">abort</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'boom!'</span>));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(ac.<span class="hljs-property">signal</span>.<span class="hljs-property">reason</span>);  <span class="hljs-comment">// Error: boom!</span></code> <button class="copy-button">copy</button></pre>
<h5><code>abortSignal.throwIfAborted()</code><span><a class="mark" href="#all_globals_abortsignalthrowifaborted" id="all_globals_abortsignalthrowifaborted">#</a></span><a aria-hidden="true" class="legacy" id="globals_abortsignal_throwifaborted"></a></h5>
<div class="api_metadata">
<span>Added in: v17.3.0, v16.17.0</span>
</div>
<p>If <code>abortSignal.aborted</code> is <code>true</code>, throws <code>abortSignal.reason</code>.</p>
</section><section><h3>Class: <code>Blob</code><span><a class="mark" href="#all_globals_class-blob" id="all_globals_class-blob">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_blob"></a></h3>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>

<p>See <a href="#all_buffer_class-blob" class="type">&#x3C;Blob></a>.</p>
</section><section><h3>Class: <code>Buffer</code><span><a class="mark" href="#all_globals_class-buffer" id="all_globals_class-buffer">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_buffer"></a></h3>
<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>
</section><section><h3>Class: <code>ByteLengthQueuingStrategy</code><span><a class="mark" href="#all_globals_class-bytelengthqueuingstrategy" id="all_globals_class-bytelengthqueuingstrategy">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_bytelengthqueuingstrategy"></a></h3>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental.</div><p></p>
<p>A browser-compatible implementation of <a href="#all_webstreams_class-bytelengthqueuingstrategy"><code>ByteLengthQueuingStrategy</code></a>.</p>
</section><section><h3><code>__dirname</code><span><a class="mark" href="#all_globals___dirname" id="all_globals___dirname">#</a></span><a aria-hidden="true" class="legacy" id="globals_dirname"></a></h3>
<p>This variable may appear to be global but is not. See <a href="#all_modules___dirname"><code>__dirname</code></a>.</p>
</section><section><h3><code>__filename</code><span><a class="mark" href="#all_globals___filename" id="all_globals___filename">#</a></span><a aria-hidden="true" class="legacy" id="globals_filename"></a></h3>
<p>This variable may appear to be global but is not. See <a href="#all_modules___filename"><code>__filename</code></a>.</p>
</section><section><h3><code>atob(data)</code><span><a class="mark" href="#all_globals_atobdata" id="all_globals_atobdata">#</a></span><a aria-hidden="true" class="legacy" id="globals_atob_data"></a></h3>
<div class="api_metadata">
<span>Added in: v16.0.0</span>
</div>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy. Use <code>Buffer.from(data, 'base64')</code> instead.</div><p></p>
<p>Global alias for <a href="#all_buffer_bufferatobdata"><code>buffer.atob()</code></a>.</p>
</section><section><h3><code>BroadcastChannel</code><span><a class="mark" href="#all_globals_broadcastchannel" id="all_globals_broadcastchannel">#</a></span><a aria-hidden="true" class="legacy" id="globals_broadcastchannel"></a></h3>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<p>See <a href="#all_worker_threads_class-broadcastchannel-extends-eventtarget" class="type">&#x3C;BroadcastChannel></a>.</p>
</section><section><h3><code>btoa(data)</code><span><a class="mark" href="#all_globals_btoadata" id="all_globals_btoadata">#</a></span><a aria-hidden="true" class="legacy" id="globals_btoa_data"></a></h3>
<div class="api_metadata">
<span>Added in: v16.0.0</span>
</div>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy. Use <code>buf.toString('base64')</code> instead.</div><p></p>
<p>Global alias for <a href="#all_buffer_bufferbtoadata"><code>buffer.btoa()</code></a>.</p>
</section><section><h3><code>clearImmediate(immediateObject)</code><span><a class="mark" href="#all_globals_clearimmediateimmediateobject" id="all_globals_clearimmediateimmediateobject">#</a></span><a aria-hidden="true" class="legacy" id="globals_clearimmediate_immediateobject"></a></h3>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div>

<p><a href="#all_timers_clearimmediateimmediate"><code>clearImmediate</code></a> is described in the <a href="timers.html">timers</a> section.</p>
</section><section><h3><code>clearInterval(intervalObject)</code><span><a class="mark" href="#all_globals_clearintervalintervalobject" id="all_globals_clearintervalintervalobject">#</a></span><a aria-hidden="true" class="legacy" id="globals_clearinterval_intervalobject"></a></h3>
<div class="api_metadata">
<span>Added in: v0.0.1</span>
</div>

<p><a href="#all_timers_clearintervaltimeout"><code>clearInterval</code></a> is described in the <a href="timers.html">timers</a> section.</p>
</section><section><h3><code>clearTimeout(timeoutObject)</code><span><a class="mark" href="#all_globals_cleartimeouttimeoutobject" id="all_globals_cleartimeouttimeoutobject">#</a></span><a aria-hidden="true" class="legacy" id="globals_cleartimeout_timeoutobject"></a></h3>
<div class="api_metadata">
<span>Added in: v0.0.1</span>
</div>

<p><a href="#all_timers_cleartimeouttimeout"><code>clearTimeout</code></a> is described in the <a href="timers.html">timers</a> section.</p>
</section><section><h3>Class: <code>CompressionStream</code><span><a class="mark" href="#all_globals_class-compressionstream" id="all_globals_class-compressionstream">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_compressionstream"></a></h3>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental.</div><p></p>
<p>A browser-compatible implementation of <a href="#all_webstreams_class-compressionstream"><code>CompressionStream</code></a>.</p>
</section><section><h3><code>console</code><span><a class="mark" href="#all_globals_console" id="all_globals_console">#</a></span><a aria-hidden="true" class="legacy" id="globals_console"></a></h3>
<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>
</section><section><h3>Class: <code>CountQueuingStrategy</code><span><a class="mark" href="#all_globals_class-countqueuingstrategy" id="all_globals_class-countqueuingstrategy">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_countqueuingstrategy"></a></h3>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental.</div><p></p>
<p>A browser-compatible implementation of <a href="#all_webstreams_class-countqueuingstrategy"><code>CountQueuingStrategy</code></a>.</p>
</section><section><h3><code>Crypto</code><span><a class="mark" href="#all_globals_crypto" id="all_globals_crypto">#</a></span><a aria-hidden="true" class="legacy" id="globals_crypto"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>No longer behind <code>--experimental-global-webcrypto</code> CLI flag.</p></td></tr>
<tr><td>v17.6.0, v16.15.0</td>
<td><p><span>Added in: v17.6.0, v16.15.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental. Disable this API with the
<a href="#all_cli_--no-experimental-global-webcrypto"><code>--no-experimental-global-webcrypto</code></a> CLI flag.</div><p></p>
<p>A browser-compatible implementation of <a href="#all_webcrypto_class-crypto" class="type">&#x3C;Crypto></a>. This global is available
only if the Node.js binary was compiled with including support for the
<code>node:crypto</code> module.</p>
</section><section><h3><code>crypto</code><span><a class="mark" href="#all_globals_crypto_1" id="all_globals_crypto_1">#</a></span><a aria-hidden="true" class="legacy" id="globals_crypto_1"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>No longer behind <code>--experimental-global-webcrypto</code> CLI flag.</p></td></tr>
<tr><td>v17.6.0, v16.15.0</td>
<td><p><span>Added in: v17.6.0, v16.15.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental. Disable this API with the
<a href="#all_cli_--no-experimental-global-webcrypto"><code>--no-experimental-global-webcrypto</code></a> CLI flag.</div><p></p>
<p>A browser-compatible implementation of the <a href="webcrypto.html">Web Crypto API</a>.</p>
</section><section><h3><code>CryptoKey</code><span><a class="mark" href="#all_globals_cryptokey" id="all_globals_cryptokey">#</a></span><a aria-hidden="true" class="legacy" id="globals_cryptokey"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>No longer behind <code>--experimental-global-webcrypto</code> CLI flag.</p></td></tr>
<tr><td>v17.6.0, v16.15.0</td>
<td><p><span>Added in: v17.6.0, v16.15.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental. Disable this API with the
<a href="#all_cli_--no-experimental-global-webcrypto"><code>--no-experimental-global-webcrypto</code></a> CLI flag.</div><p></p>
<p>A browser-compatible implementation of <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></a>. This global is available
only if the Node.js binary was compiled with including support for the
<code>node:crypto</code> module.</p>
</section><section><h3><code>CustomEvent</code><span><a class="mark" href="#all_globals_customevent" id="all_globals_customevent">#</a></span><a aria-hidden="true" class="legacy" id="globals_customevent"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>No longer behind <code>--experimental-global-customevent</code> CLI flag.</p></td></tr>
<tr><td>v18.7.0, v16.17.0</td>
<td><p><span>Added in: v18.7.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental. Disable this API with the
<a href="#all_cli_--no-experimental-global-customevent"><code>--no-experimental-global-customevent</code></a> CLI flag.</div><p></p>

<p>A browser-compatible implementation of the <a href="https://dom.spec.whatwg.org/#customevent"><code>CustomEvent</code> Web API</a>.</p>
</section><section><h3>Class: <code>DecompressionStream</code><span><a class="mark" href="#all_globals_class-decompressionstream" id="all_globals_class-decompressionstream">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_decompressionstream"></a></h3>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental.</div><p></p>
<p>A browser-compatible implementation of <a href="#all_webstreams_class-decompressionstream"><code>DecompressionStream</code></a>.</p>
</section><section><h3><code>Event</code><span><a class="mark" href="#all_globals_event" id="all_globals_event">#</a></span><a aria-hidden="true" class="legacy" id="globals_event"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.4.0</td>
<td><p>No longer experimental.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p><span>Added in: v15.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>

<p>A browser-compatible implementation of the <code>Event</code> class. See
<a href="#all_events_eventtarget-and-event-api"><code>EventTarget</code> and <code>Event</code> API</a> for more details.</p>
</section><section><h3><code>EventSource</code><span><a class="mark" href="#all_globals_eventsource" id="all_globals_eventsource">#</a></span><a aria-hidden="true" class="legacy" id="globals_eventsource"></a></h3>
<div class="api_metadata">
<span>Added in: v20.18.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental. Enable this API with the <a href="#all_cli_--experimental-eventsource"><code>--experimental-eventsource</code></a>
CLI flag.</div><p></p>
<p>A browser-compatible implementation of the <a href="https://developer.mozilla.org/en-US/docs/Web/API/EventSource"><code>EventSource</code></a> class.</p>
</section><section><h3><code>EventTarget</code><span><a class="mark" href="#all_globals_eventtarget" id="all_globals_eventtarget">#</a></span><a aria-hidden="true" class="legacy" id="globals_eventtarget"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.4.0</td>
<td><p>No longer experimental.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p><span>Added in: v15.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>

<p>A browser-compatible implementation of the <code>EventTarget</code> class. See
<a href="#all_events_eventtarget-and-event-api"><code>EventTarget</code> and <code>Event</code> API</a> for more details.</p>
</section><section><h3><code>exports</code><span><a class="mark" href="#all_globals_exports" id="all_globals_exports">#</a></span><a aria-hidden="true" class="legacy" id="globals_exports"></a></h3>
<p>This variable may appear to be global but is not. See <a href="#all_modules_exports"><code>exports</code></a>.</p>
</section><section><h3><code>fetch</code><span><a class="mark" href="#all_globals_fetch" id="all_globals_fetch">#</a></span><a aria-hidden="true" class="legacy" id="globals_fetch"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>No longer behind <code>--experimental-fetch</code> CLI flag.</p></td></tr>
<tr><td>v17.5.0, v16.15.0</td>
<td><p><span>Added in: v17.5.0, v16.15.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental. Disable this API with the <a href="#all_cli_--no-experimental-fetch"><code>--no-experimental-fetch</code></a>
CLI flag.</div><p></p>
<p>A browser-compatible implementation of the <a href="https://developer.mozilla.org/en-US/docs/Web/API/fetch"><code>fetch()</code></a> function.</p>
</section><section><h3>Class: <code>File</code><span><a class="mark" href="#all_globals_class-file" id="all_globals_class-file">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_file"></a></h3>
<div class="api_metadata">
<span>Added in: v20.0.0</span>
</div>

<p>See <a href="#all_buffer_class-file" class="type">&#x3C;File></a>.</p>
</section><section><h3>Class <code>FormData</code><span><a class="mark" href="#all_globals_class-formdata" id="all_globals_class-formdata">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_formdata"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>No longer behind <code>--experimental-fetch</code> CLI flag.</p></td></tr>
<tr><td>v17.6.0, v16.15.0</td>
<td><p><span>Added in: v17.6.0, v16.15.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental. Disable this API with the <a href="#all_cli_--no-experimental-fetch"><code>--no-experimental-fetch</code></a>
CLI flag.</div><p></p>
<p>A browser-compatible implementation of <a href="https://developer.mozilla.org/en-US/docs/Web/API/FormData" class="type">&#x3C;FormData></a>.</p>
</section><section><h3><code>global</code><span><a class="mark" href="#all_globals_global" id="all_globals_global">#</a></span><a aria-hidden="true" class="legacy" id="globals_global"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.27</span>
</div>

<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy. Use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis"><code>globalThis</code></a> instead.</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> The global namespace object.</li>
</ul>
<p>In browsers, the top-level scope has traditionally been the global scope. This
means that <code>var something</code> will define a new global variable, except within
ECMAScript modules. 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, regardless of whether it is a <a href="modules.html">CommonJS module</a> or an
<a href="esm.html">ECMAScript module</a>.</p>
</section><section><h3>Class <code>Headers</code><span><a class="mark" href="#all_globals_class-headers" id="all_globals_class-headers">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_headers"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>No longer behind <code>--experimental-fetch</code> CLI flag.</p></td></tr>
<tr><td>v17.5.0, v16.15.0</td>
<td><p><span>Added in: v17.5.0, v16.15.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental. Disable this API with the <a href="#all_cli_--no-experimental-fetch"><code>--no-experimental-fetch</code></a>
CLI flag.</div><p></p>
<p>A browser-compatible implementation of <a href="https://developer.mozilla.org/en-US/docs/Web/API/Headers" class="type">&#x3C;Headers></a>.</p>
</section><section><h3><code>MessageChannel</code><span><a class="mark" href="#all_globals_messagechannel" id="all_globals_messagechannel">#</a></span><a aria-hidden="true" class="legacy" id="globals_messagechannel"></a></h3>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>

<p>The <code>MessageChannel</code> class. See <a href="#all_worker_threads_class-messagechannel"><code>MessageChannel</code></a> for more details.</p>
</section><section><h3><code>MessageEvent</code><span><a class="mark" href="#all_globals_messageevent" id="all_globals_messageevent">#</a></span><a aria-hidden="true" class="legacy" id="globals_messageevent"></a></h3>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>

<p>The <code>MessageEvent</code> class. See <a href="https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent/MessageEvent"><code>MessageEvent</code></a> for more details.</p>
</section><section><h3><code>MessagePort</code><span><a class="mark" href="#all_globals_messageport" id="all_globals_messageport">#</a></span><a aria-hidden="true" class="legacy" id="globals_messageport"></a></h3>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>

<p>The <code>MessagePort</code> class. See <a href="#all_worker_threads_class-messageport"><code>MessagePort</code></a> for more details.</p>
</section><section><h3><code>module</code><span><a class="mark" href="#all_globals_module" id="all_globals_module">#</a></span><a aria-hidden="true" class="legacy" id="globals_module"></a></h3>
<p>This variable may appear to be global but is not. See <a href="#all_modules_module"><code>module</code></a>.</p>
</section><section><h3><code>PerformanceEntry</code><span><a class="mark" href="#all_globals_performanceentry" id="all_globals_performanceentry">#</a></span><a aria-hidden="true" class="legacy" id="globals_performanceentry"></a></h3>
<div class="api_metadata">
<span>Added in: v19.0.0</span>
</div>

<p>The <code>PerformanceEntry</code> class. See <a href="#all_perf_hooks_class-performanceentry"><code>PerformanceEntry</code></a> for more details.</p>
</section><section><h3><code>PerformanceMark</code><span><a class="mark" href="#all_globals_performancemark" id="all_globals_performancemark">#</a></span><a aria-hidden="true" class="legacy" id="globals_performancemark"></a></h3>
<div class="api_metadata">
<span>Added in: v19.0.0</span>
</div>

<p>The <code>PerformanceMark</code> class. See <a href="#all_perf_hooks_class-performancemark"><code>PerformanceMark</code></a> for more details.</p>
</section><section><h3><code>PerformanceMeasure</code><span><a class="mark" href="#all_globals_performancemeasure" id="all_globals_performancemeasure">#</a></span><a aria-hidden="true" class="legacy" id="globals_performancemeasure"></a></h3>
<div class="api_metadata">
<span>Added in: v19.0.0</span>
</div>

<p>The <code>PerformanceMeasure</code> class. See <a href="#all_perf_hooks_class-performancemeasure"><code>PerformanceMeasure</code></a> for more details.</p>
</section><section><h3><code>PerformanceObserver</code><span><a class="mark" href="#all_globals_performanceobserver" id="all_globals_performanceobserver">#</a></span><a aria-hidden="true" class="legacy" id="globals_performanceobserver"></a></h3>
<div class="api_metadata">
<span>Added in: v19.0.0</span>
</div>

<p>The <code>PerformanceObserver</code> class. See <a href="#all_perf_hooks_class-performanceobserver"><code>PerformanceObserver</code></a> for more details.</p>
</section><section><h3><code>PerformanceObserverEntryList</code><span><a class="mark" href="#all_globals_performanceobserverentrylist" id="all_globals_performanceobserverentrylist">#</a></span><a aria-hidden="true" class="legacy" id="globals_performanceobserverentrylist"></a></h3>
<div class="api_metadata">
<span>Added in: v19.0.0</span>
</div>

<p>The <code>PerformanceObserverEntryList</code> class. See
<a href="#all_perf_hooks_class-performanceobserverentrylist"><code>PerformanceObserverEntryList</code></a> for more details.</p>
</section><section><h3><code>PerformanceResourceTiming</code><span><a class="mark" href="#all_globals_performanceresourcetiming" id="all_globals_performanceresourcetiming">#</a></span><a aria-hidden="true" class="legacy" id="globals_performanceresourcetiming"></a></h3>
<div class="api_metadata">
<span>Added in: v19.0.0</span>
</div>

<p>The <code>PerformanceResourceTiming</code> class. See <a href="#all_perf_hooks_class-performanceresourcetiming"><code>PerformanceResourceTiming</code></a> for
more details.</p>
</section><section><h3><code>performance</code><span><a class="mark" href="#all_globals_performance" id="all_globals_performance">#</a></span><a aria-hidden="true" class="legacy" id="globals_performance"></a></h3>
<div class="api_metadata">
<span>Added in: v16.0.0</span>
</div>
<p>The <a href="#all_perf_hooks_perf_hooksperformance"><code>perf_hooks.performance</code></a> object.</p>
</section><section><h3><code>process</code><span><a class="mark" href="#all_globals_process" id="all_globals_process">#</a></span><a aria-hidden="true" class="legacy" id="globals_process"></a></h3>
<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="#all_process_process"><code>process</code> object</a> section.</p>
</section><section><h3><code>queueMicrotask(callback)</code><span><a class="mark" href="#all_globals_queuemicrotaskcallback" id="all_globals_queuemicrotaskcallback">#</a></span><a aria-hidden="true" class="legacy" id="globals_queuemicrotask_callback"></a></h3>
<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="#all_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="#all_process_processnexttickcallback-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"><span class="hljs-comment">// Here, `queueMicrotask()` is used to ensure the 'load' event is always</span>
<span class="hljs-comment">// emitted asynchronously, and therefore consistently. Using</span>
<span class="hljs-comment">// `process.nextTick()` here would result in the 'load' event always emitting</span>
<span class="hljs-comment">// before any other promise jobs.</span>

<span class="hljs-title class_">DataHandler</span>.<span class="hljs-property"><span class="hljs-keyword">prototype</span></span>.<span class="hljs-property">load</span> = <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">load</span>(<span class="hljs-params">key</span>) {
  <span class="hljs-keyword">const</span> hit = <span class="hljs-variable language_">this</span>.<span class="hljs-property">_cache</span>.<span class="hljs-title function_">get</span>(key);
  <span class="hljs-keyword">if</span> (hit !== <span class="hljs-literal">undefined</span>) {
    <span class="hljs-title function_">queueMicrotask</span>(<span class="hljs-function">() =></span> {
      <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'load'</span>, hit);
    });
    <span class="hljs-keyword">return</span>;
  }

  <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> <span class="hljs-title function_">fetchData</span>(key);
  <span class="hljs-variable language_">this</span>.<span class="hljs-property">_cache</span>.<span class="hljs-title function_">set</span>(key, data);
  <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'load'</span>, data);
};</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>ReadableByteStreamController</code><span><a class="mark" href="#all_globals_class-readablebytestreamcontroller" id="all_globals_class-readablebytestreamcontroller">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_readablebytestreamcontroller"></a></h3>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental.</div><p></p>
<p>A browser-compatible implementation of <a href="#all_webstreams_class-readablebytestreamcontroller"><code>ReadableByteStreamController</code></a>.</p>
</section><section><h3>Class: <code>ReadableStream</code><span><a class="mark" href="#all_globals_class-readablestream" id="all_globals_class-readablestream">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_readablestream"></a></h3>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental.</div><p></p>
<p>A browser-compatible implementation of <a href="#all_webstreams_class-readablestream"><code>ReadableStream</code></a>.</p>
</section><section><h3>Class: <code>ReadableStreamBYOBReader</code><span><a class="mark" href="#all_globals_class-readablestreambyobreader" id="all_globals_class-readablestreambyobreader">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_readablestreambyobreader"></a></h3>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental.</div><p></p>
<p>A browser-compatible implementation of <a href="#all_webstreams_class-readablestreambyobreader"><code>ReadableStreamBYOBReader</code></a>.</p>
</section><section><h3>Class: <code>ReadableStreamBYOBRequest</code><span><a class="mark" href="#all_globals_class-readablestreambyobrequest" id="all_globals_class-readablestreambyobrequest">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_readablestreambyobrequest"></a></h3>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental.</div><p></p>
<p>A browser-compatible implementation of <a href="#all_webstreams_class-readablestreambyobrequest"><code>ReadableStreamBYOBRequest</code></a>.</p>
</section><section><h3>Class: <code>ReadableStreamDefaultController</code><span><a class="mark" href="#all_globals_class-readablestreamdefaultcontroller" id="all_globals_class-readablestreamdefaultcontroller">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_readablestreamdefaultcontroller"></a></h3>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental.</div><p></p>
<p>A browser-compatible implementation of <a href="#all_webstreams_class-readablestreamdefaultcontroller"><code>ReadableStreamDefaultController</code></a>.</p>
</section><section><h3>Class: <code>ReadableStreamDefaultReader</code><span><a class="mark" href="#all_globals_class-readablestreamdefaultreader" id="all_globals_class-readablestreamdefaultreader">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_readablestreamdefaultreader"></a></h3>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental.</div><p></p>
<p>A browser-compatible implementation of <a href="#all_webstreams_class-readablestreamdefaultreader"><code>ReadableStreamDefaultReader</code></a>.</p>
</section><section><h3><code>require()</code><span><a class="mark" href="#all_globals_require" id="all_globals_require">#</a></span><a aria-hidden="true" class="legacy" id="globals_require"></a></h3>
<p>This variable may appear to be global but is not. See <a href="#all_modules_requireid"><code>require()</code></a>.</p>
</section><section><h3><code>Response</code><span><a class="mark" href="#all_globals_response" id="all_globals_response">#</a></span><a aria-hidden="true" class="legacy" id="globals_response"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>No longer behind <code>--experimental-fetch</code> CLI flag.</p></td></tr>
<tr><td>v17.5.0, v16.15.0</td>
<td><p><span>Added in: v17.5.0, v16.15.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental. Disable this API with the <a href="#all_cli_--no-experimental-fetch"><code>--no-experimental-fetch</code></a>
CLI flag.</div><p></p>
<p>A browser-compatible implementation of <a href="https://developer.mozilla.org/en-US/docs/Web/API/Response" class="type">&#x3C;Response></a>.</p>
</section><section><h3><code>Request</code><span><a class="mark" href="#all_globals_request" id="all_globals_request">#</a></span><a aria-hidden="true" class="legacy" id="globals_request"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>No longer behind <code>--experimental-fetch</code> CLI flag.</p></td></tr>
<tr><td>v17.5.0, v16.15.0</td>
<td><p><span>Added in: v17.5.0, v16.15.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental. Disable this API with the <a href="#all_cli_--no-experimental-fetch"><code>--no-experimental-fetch</code></a>
CLI flag.</div><p></p>
<p>A browser-compatible implementation of <a href="https://developer.mozilla.org/en-US/docs/Web/API/Request" class="type">&#x3C;Request></a>.</p>
</section><section><h3><code>setImmediate(callback[, ...args])</code><span><a class="mark" href="#all_globals_setimmediatecallback-args" id="all_globals_setimmediatecallback-args">#</a></span><a aria-hidden="true" class="legacy" id="globals_setimmediate_callback_args"></a></h3>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div>

<p><a href="#all_timers_setimmediatecallback-args"><code>setImmediate</code></a> is described in the <a href="timers.html">timers</a> section.</p>
</section><section><h3><code>setInterval(callback, delay[, ...args])</code><span><a class="mark" href="#all_globals_setintervalcallback-delay-args" id="all_globals_setintervalcallback-delay-args">#</a></span><a aria-hidden="true" class="legacy" id="globals_setinterval_callback_delay_args"></a></h3>
<div class="api_metadata">
<span>Added in: v0.0.1</span>
</div>

<p><a href="#all_timers_setintervalcallback-delay-args"><code>setInterval</code></a> is described in the <a href="timers.html">timers</a> section.</p>
</section><section><h3><code>setTimeout(callback, delay[, ...args])</code><span><a class="mark" href="#all_globals_settimeoutcallback-delay-args" id="all_globals_settimeoutcallback-delay-args">#</a></span><a aria-hidden="true" class="legacy" id="globals_settimeout_callback_delay_args"></a></h3>
<div class="api_metadata">
<span>Added in: v0.0.1</span>
</div>

<p><a href="#all_timers_settimeoutcallback-delay-args"><code>setTimeout</code></a> is described in the <a href="timers.html">timers</a> section.</p>
</section><section><h3><code>structuredClone(value[, options])</code><span><a class="mark" href="#all_globals_structuredclonevalue-options" id="all_globals_structuredclonevalue-options">#</a></span><a aria-hidden="true" class="legacy" id="globals_structuredclone_value_options"></a></h3>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>

<p>The WHATWG <a href="https://developer.mozilla.org/en-US/docs/Web/API/structuredClone"><code>structuredClone</code></a> method.</p>
</section><section><h3><code>SubtleCrypto</code><span><a class="mark" href="#all_globals_subtlecrypto" id="all_globals_subtlecrypto">#</a></span><a aria-hidden="true" class="legacy" id="globals_subtlecrypto"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>No longer behind <code>--experimental-global-webcrypto</code> CLI flag.</p></td></tr>
<tr><td>v17.6.0, v16.15.0</td>
<td><p><span>Added in: v17.6.0, v16.15.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental. Disable this API with the
<a href="#all_cli_--no-experimental-global-webcrypto"><code>--no-experimental-global-webcrypto</code></a> CLI flag.</div><p></p>
<p>A browser-compatible implementation of <a href="#all_webcrypto_class-subtlecrypto" class="type">&#x3C;SubtleCrypto></a>. This global is available
only if the Node.js binary was compiled with including support for the
<code>node:crypto</code> module.</p>
</section><section><h3><code>DOMException</code><span><a class="mark" href="#all_globals_domexception" id="all_globals_domexception">#</a></span><a aria-hidden="true" class="legacy" id="globals_domexception"></a></h3>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>

<p>The WHATWG <code>DOMException</code> class. See <a href="https://developer.mozilla.org/en-US/docs/Web/API/DOMException"><code>DOMException</code></a> for more details.</p>
</section><section><h3><code>TextDecoder</code><span><a class="mark" href="#all_globals_textdecoder" id="all_globals_textdecoder">#</a></span><a aria-hidden="true" class="legacy" id="globals_textdecoder"></a></h3>
<div class="api_metadata">
<span>Added in: v11.0.0</span>
</div>

<p>The WHATWG <code>TextDecoder</code> class. See the <a href="#all_util_class-utiltextdecoder"><code>TextDecoder</code></a> section.</p>
</section><section><h3>Class: <code>TextDecoderStream</code><span><a class="mark" href="#all_globals_class-textdecoderstream" id="all_globals_class-textdecoderstream">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_textdecoderstream"></a></h3>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental.</div><p></p>
<p>A browser-compatible implementation of <a href="#all_webstreams_class-textdecoderstream"><code>TextDecoderStream</code></a>.</p>
</section><section><h3><code>TextEncoder</code><span><a class="mark" href="#all_globals_textencoder" id="all_globals_textencoder">#</a></span><a aria-hidden="true" class="legacy" id="globals_textencoder"></a></h3>
<div class="api_metadata">
<span>Added in: v11.0.0</span>
</div>

<p>The WHATWG <code>TextEncoder</code> class. See the <a href="#all_util_class-utiltextencoder"><code>TextEncoder</code></a> section.</p>
</section><section><h3>Class: <code>TextEncoderStream</code><span><a class="mark" href="#all_globals_class-textencoderstream" id="all_globals_class-textencoderstream">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_textencoderstream"></a></h3>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental.</div><p></p>
<p>A browser-compatible implementation of <a href="#all_webstreams_class-textencoderstream"><code>TextEncoderStream</code></a>.</p>
</section><section><h3>Class: <code>TransformStream</code><span><a class="mark" href="#all_globals_class-transformstream" id="all_globals_class-transformstream">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_transformstream"></a></h3>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental.</div><p></p>
<p>A browser-compatible implementation of <a href="#all_webstreams_class-transformstream"><code>TransformStream</code></a>.</p>
</section><section><h3>Class: <code>TransformStreamDefaultController</code><span><a class="mark" href="#all_globals_class-transformstreamdefaultcontroller" id="all_globals_class-transformstreamdefaultcontroller">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_transformstreamdefaultcontroller"></a></h3>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental.</div><p></p>
<p>A browser-compatible implementation of <a href="#all_webstreams_class-transformstreamdefaultcontroller"><code>TransformStreamDefaultController</code></a>.</p>
</section><section><h3><code>URL</code><span><a class="mark" href="#all_globals_url" id="all_globals_url">#</a></span><a aria-hidden="true" class="legacy" id="globals_url"></a></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>

<p>The WHATWG <code>URL</code> class. See the <a href="#all_url_class-url"><code>URL</code></a> section.</p>
</section><section><h3><code>URLSearchParams</code><span><a class="mark" href="#all_globals_urlsearchparams" id="all_globals_urlsearchparams">#</a></span><a aria-hidden="true" class="legacy" id="globals_urlsearchparams"></a></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>

<p>The WHATWG <code>URLSearchParams</code> class. See the <a href="#all_url_class-urlsearchparams"><code>URLSearchParams</code></a> section.</p>
</section><section><h3><code>WebAssembly</code><span><a class="mark" href="#all_globals_webassembly" id="all_globals_webassembly">#</a></span><a aria-hidden="true" class="legacy" id="globals_webassembly"></a></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></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>
</section><section><h3><code>WebSocket</code><span><a class="mark" href="#all_globals_websocket" id="all_globals_websocket">#</a></span><a aria-hidden="true" class="legacy" id="globals_websocket"></a></h3>
<div class="api_metadata">
<span>Added in: v20.10.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental.</div><p></p>
<p>A browser-compatible implementation of <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSocket"><code>WebSocket</code></a>. Enable this API
with the <a href="#all_cli_--experimental-websocket"><code>--experimental-websocket</code></a> CLI flag.</p>
</section><section><h3>Class: <code>WritableStream</code><span><a class="mark" href="#all_globals_class-writablestream" id="all_globals_class-writablestream">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_writablestream"></a></h3>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental.</div><p></p>
<p>A browser-compatible implementation of <a href="#all_webstreams_class-writablestream"><code>WritableStream</code></a>.</p>
</section><section><h3>Class: <code>WritableStreamDefaultController</code><span><a class="mark" href="#all_globals_class-writablestreamdefaultcontroller" id="all_globals_class-writablestreamdefaultcontroller">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_writablestreamdefaultcontroller"></a></h3>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental.</div><p></p>
<p>A browser-compatible implementation of <a href="#all_webstreams_class-writablestreamdefaultcontroller"><code>WritableStreamDefaultController</code></a>.</p>
</section><section><h3>Class: <code>WritableStreamDefaultWriter</code><span><a class="mark" href="#all_globals_class-writablestreamdefaultwriter" id="all_globals_class-writablestreamdefaultwriter">#</a></span><a aria-hidden="true" class="legacy" id="globals_class_writablestreamdefaultwriter"></a></h3>
<div class="api_metadata">
<span>Added in: v18.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental.</div><p></p>
<p>A browser-compatible implementation of <a href="#all_webstreams_class-writablestreamdefaultwriter"><code>WritableStreamDefaultWriter</code></a>.</p></section>
        </section>
<section><h2>HTTP<span><a class="mark" href="#all_http_http" id="all_http_http">#</a></span><a aria-hidden="true" class="legacy" id="http_http"></a></h2>

<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/http.js">lib/http.js</a></p>
<p>This module, containing both a client and server, can be imported via
<code>require('node:http')</code> (CommonJS) or <code>import * as http from 'node:http'</code> (ES module).</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>
<pre><code class="language-json"><span class="hljs-punctuation">{</span> <span class="hljs-attr">"content-length"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"123"</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"content-type"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"text/plain"</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"connection"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"keep-alive"</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"host"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"example.com"</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"accept"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"*/*"</span> <span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></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="#all_http_messageheaders"><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 @stylistic/js/semi -->
<pre><code class="language-js">[ <span class="hljs-string">'ConTent-Length'</span>, <span class="hljs-string">'123456'</span>,
  <span class="hljs-string">'content-LENGTH'</span>, <span class="hljs-string">'123'</span>,
  <span class="hljs-string">'content-type'</span>, <span class="hljs-string">'text/plain'</span>,
  <span class="hljs-string">'CONNECTION'</span>, <span class="hljs-string">'keep-alive'</span>,
  <span class="hljs-string">'Host'</span>, <span class="hljs-string">'example.com'</span>,
  <span class="hljs-string">'accepT'</span>, <span class="hljs-string">'*/*'</span> ]</code> <button class="copy-button">copy</button></pre>
<section><h3>Class: <code>http.Agent</code><span><a class="mark" href="#all_http_class-httpagent" id="all_http_class-httpagent">#</a></span><a aria-hidden="true" class="legacy" id="http_class_http_agent"></a></h3>
<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="#all_http_new-agentoptions">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="#all_net_socketunref"><code>socket.unref()</code></a>).</p>
<p>It is good practice, to <a href="#all_http_agentdestroy"><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.<span class="hljs-title function_">get</span>(options, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
  <span class="hljs-comment">// Do stuff</span>
}).<span class="hljs-title function_">on</span>(<span class="hljs-string">'socket'</span>, <span class="hljs-function">(<span class="hljs-params">socket</span>) =></span> {
  socket.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'agentRemove'</span>);
});</code> <button class="copy-button">copy</button></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.<span class="hljs-title function_">get</span>({
  <span class="hljs-attr">hostname</span>: <span class="hljs-string">'localhost'</span>,
  <span class="hljs-attr">port</span>: <span class="hljs-number">80</span>,
  <span class="hljs-attr">path</span>: <span class="hljs-string">'/'</span>,
  <span class="hljs-attr">agent</span>: <span class="hljs-literal">false</span>,  <span class="hljs-comment">// Create a new agent just for this one request</span>
}, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
  <span class="hljs-comment">// Do stuff with response</span>
});</code> <button class="copy-button">copy</button></pre>
<h4><code>new Agent([options])</code><span><a class="mark" href="#all_http_new-agentoptions" id="all_http_new-agentoptions">#</a></span><a aria-hidden="true" class="legacy" id="http_new_agent_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.6.0, v14.17.0</td>
<td><p>Change the default scheduling from 'fifo' to 'lifo'.</p></td></tr>
<tr><td>v14.5.0, v12.20.0</td>
<td><p>Add <code>scheduling</code> option to specify the free socket scheduling strategy.</p></td></tr>
<tr><td>v14.5.0, v12.19.0</td>
<td><p>Add <code>maxTotalSockets</code> option to agent constructor.</p></td></tr>
<tr><td>v0.3.4</td>
<td><p><span>Added in: v0.3.4</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> Set of configurable options to set on the agent.
Can have the following fields:
<ul>
<li><code>keepAlive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#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="#all_net_socketsetkeepaliveenable-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.
If the same host opens multiple concurrent connections, each request
will use new socket until the <code>maxSockets</code> value is reached.
If the host attempts to open more connections than <code>maxSockets</code>,
the additional requests will enter into a pending request queue, and
will enter active connection state when an existing connection terminates.
This makes sure there are at most <code>maxSockets</code> active connections at
any point in time, from a given host.
<strong>Default:</strong> <code>Infinity</code>.</li>
<li><code>maxTotalSockets</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 allowed for
all hosts in total. 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 per host 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>scheduling</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Scheduling strategy to apply when picking
the next free socket to use. It can be <code>'fifo'</code> or <code>'lifo'</code>.
The main difference between the two scheduling strategies is that <code>'lifo'</code>
selects the most recently used socket, while <code>'fifo'</code> selects
the least recently used socket.
In case of a low rate of request per second, the <code>'lifo'</code> scheduling
will lower the risk of picking a socket that might have been closed
by the server due to inactivity.
In case of a high rate of request per second,
the <code>'fifo'</code> scheduling will maximize the number of open sockets,
while the <code>'lifo'</code> scheduling will keep it as low as possible.
<strong>Default:</strong> <code>'lifo'</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="#all_net_socketconnectoptions-connectlistener"><code>socket.connect()</code></a> are also supported.</p>
<p>To configure any of them, a custom <a href="#all_http_class-httpagent"><code>http.Agent</code></a> instance must be created.</p>

<pre class="with-59-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Agent</span>, request } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;
<span class="hljs-keyword">const</span> keepAliveAgent = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Agent</span>({ <span class="hljs-attr">keepAlive</span>: <span class="hljs-literal">true</span> });
options.<span class="hljs-property">agent</span> = keepAliveAgent;
<span class="hljs-title function_">request</span>(options, onResponseCallback);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);
<span class="hljs-keyword">const</span> keepAliveAgent = <span class="hljs-keyword">new</span> http.<span class="hljs-title class_">Agent</span>({ <span class="hljs-attr">keepAlive</span>: <span class="hljs-literal">true</span> });
options.<span class="hljs-property">agent</span> = keepAliveAgent;
http.<span class="hljs-title function_">request</span>(options, onResponseCallback);</code><button class="copy-button">copy</button></pre>
<h4><code>agent.createConnection(options[, callback])</code><span><a class="mark" href="#all_http_agentcreateconnectionoptions-callback" id="all_http_agentcreateconnectionoptions-callback">#</a></span><a aria-hidden="true" class="legacy" id="http_agent_createconnection_options_callback"></a></h4>
<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="#all_net_netcreateconnectionoptions-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="#all_stream_class-streamduplex" 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="#all_net_netcreateconnectionoptions-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="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a> class,
a subclass of <a href="#all_stream_class-streamduplex" class="type">&#x3C;stream.Duplex></a>, unless the user specifies a socket
type other than <a href="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a>.</p>
<p><code>callback</code> has a signature of <code>(err, stream)</code>.</p>
<h4><code>agent.keepSocketAlive(socket)</code><span><a class="mark" href="#all_http_agentkeepsocketalivesocket" id="all_http_agentkeepsocketalivesocket">#</a></span><a aria-hidden="true" class="legacy" id="http_agent_keepsocketalive_socket"></a></h4>
<div class="api_metadata">
<span>Added in: v8.1.0</span>
</div>
<ul>
<li><code>socket</code> <a href="#all_stream_class-streamduplex" 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.<span class="hljs-title function_">setKeepAlive</span>(<span class="hljs-literal">true</span>, <span class="hljs-variable language_">this</span>.<span class="hljs-property">keepAliveMsecs</span>);
socket.<span class="hljs-title function_">unref</span>();
<span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;</code> <button class="copy-button">copy</button></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="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a>, a subclass of
<a href="#all_stream_class-streamduplex" class="type">&#x3C;stream.Duplex></a>.</p>
<h4><code>agent.reuseSocket(socket, request)</code><span><a class="mark" href="#all_http_agentreusesocketsocket-request" id="all_http_agentreusesocketsocket-request">#</a></span><a aria-hidden="true" class="legacy" id="http_agent_reusesocket_socket_request"></a></h4>
<div class="api_metadata">
<span>Added in: v8.1.0</span>
</div>
<ul>
<li><code>socket</code> <a href="#all_stream_class-streamduplex" class="type">&#x3C;stream.Duplex></a></li>
<li><code>request</code> <a href="#all_http_class-httpclientrequest" 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.<span class="hljs-title function_">ref</span>();</code> <button class="copy-button">copy</button></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="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a>, a subclass of
<a href="#all_stream_class-streamduplex" class="type">&#x3C;stream.Duplex></a>.</p>
<h4><code>agent.destroy()</code><span><a class="mark" href="#all_http_agentdestroy" id="all_http_agentdestroy">#</a></span><a aria-hidden="true" class="legacy" id="http_agent_destroy"></a></h4>
<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 is no longer needed. Otherwise,
sockets might stay open for quite a long time before the server
terminates them.</p>
<h4><code>agent.freeSockets</code><span><a class="mark" href="#all_http_agentfreesockets" id="all_http_agentfreesockets">#</a></span><a aria-hidden="true" class="legacy" id="http_agent_freesockets"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0</td>
<td><p>The property now has a <code>null</code> prototype.</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><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>
<h4><code>agent.getName([options])</code><span><a class="mark" href="#all_http_agentgetnameoptions" id="all_http_agentgetnameoptions">#</a></span><a aria-hidden="true" class="legacy" id="http_agent_getname_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.7.0, v16.15.0</td>
<td><p>The <code>options</code> parameter is now optional.</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>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
<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>
<h4><code>agent.maxFreeSockets</code><span><a class="mark" href="#all_http_agentmaxfreesockets" id="all_http_agentmaxfreesockets">#</a></span><a aria-hidden="true" class="legacy" id="http_agent_maxfreesockets"></a></h4>
<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>
<h4><code>agent.maxSockets</code><span><a class="mark" href="#all_http_agentmaxsockets" id="all_http_agentmaxsockets">#</a></span><a aria-hidden="true" class="legacy" id="http_agent_maxsockets"></a></h4>
<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="#all_http_agentgetnameoptions"><code>agent.getName()</code></a>.</p>
<h4><code>agent.maxTotalSockets</code><span><a class="mark" href="#all_http_agentmaxtotalsockets" id="all_http_agentmaxtotalsockets">#</a></span><a aria-hidden="true" class="legacy" id="http_agent_maxtotalsockets"></a></h4>
<div class="api_metadata">
<span>Added in: v14.5.0, v12.19.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>By default set to <code>Infinity</code>. Determines how many concurrent sockets the agent
can have open. Unlike <code>maxSockets</code>, this parameter applies across all origins.</p>
<h4><code>agent.requests</code><span><a class="mark" href="#all_http_agentrequests" id="all_http_agentrequests">#</a></span><a aria-hidden="true" class="legacy" id="http_agent_requests"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0</td>
<td><p>The property now has a <code>null</code> prototype.</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><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>
<h4><code>agent.sockets</code><span><a class="mark" href="#all_http_agentsockets" id="all_http_agentsockets">#</a></span><a aria-hidden="true" class="legacy" id="http_agent_sockets"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0</td>
<td><p>The property now has a <code>null</code> prototype.</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><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>
</section><section><h3>Class: <code>http.ClientRequest</code><span><a class="mark" href="#all_http_class-httpclientrequest" id="all_http_class-httpclientrequest">#</a></span><a aria-hidden="true" class="legacy" id="http_class_http_clientrequest"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.17</span>
</div>
<ul>
<li>Extends: <a href="#all_http_class-httpoutgoingmessage" class="type">&#x3C;http.OutgoingMessage></a></li>
</ul>
<p>This object is created internally and returned from <a href="#all_http_httprequestoptions-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="#all_http_requestsetheadername-value"><code>setHeader(name, value)</code></a>,
<a href="#all_http_requestgetheadername"><code>getHeader(name)</code></a>, <a href="#all_http_requestremoveheadername"><code>removeHeader(name)</code></a> API. The actual header will
be sent along with the first data chunk or when calling <a href="#all_http_requestenddata-encoding-callback"><code>request.end()</code></a>.</p>
<p>To get the response, add a listener for <a href="#all_http_event-response"><code>'response'</code></a> to the request object.
<a href="#all_http_event-response"><code>'response'</code></a> will be emitted from the request object when the response
headers have been received. The <a href="#all_http_event-response"><code>'response'</code></a> event is executed with one
argument which is an instance of <a href="#all_http_class-httpincomingmessage"><code>http.IncomingMessage</code></a>.</p>
<p>During the <a href="#all_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="#all_http_event-response"><code>'response'</code></a> handler is added, then the response will be
entirely discarded. However, if a <a href="#all_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>For backward compatibility, <code>res</code> will only emit <code>'error'</code> if there is an
<code>'error'</code> listener registered.</p>
<p>Set <code>Content-Length</code> header to limit the response body size.
If <a href="#all_http_responsestrictcontentlength"><code>response.strictContentLength</code></a> is set to <code>true</code>, mismatching the
<code>Content-Length</code> header value will result in an <code>Error</code> being thrown,
identified by <code>code:</code> <a href="#all_errors_err_http_content_length_mismatch"><code>'ERR_HTTP_CONTENT_LENGTH_MISMATCH'</code></a>.</p>
<p><code>Content-Length</code> value should be in bytes, not characters. Use
<a href="#all_buffer_static-method-bufferbytelengthstring-encoding"><code>Buffer.byteLength()</code></a> to determine the length of the body in bytes.</p>
<h4>Event: <code>'abort'</code><span><a class="mark" href="#all_http_event-abort" id="all_http_event-abort">#</a></span><a aria-hidden="true" class="legacy" id="http_event_abort"></a></h4>
<div class="api_metadata">
<span>Added in: v1.4.1</span><span>Deprecated since: v17.0.0, v16.12.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated. Listen for the <code>'close'</code> event instead.</div><p></p>
<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>
<h4>Event: <code>'close'</code><span><a class="mark" href="#all_http_event-close" id="all_http_event-close">#</a></span><a aria-hidden="true" class="legacy" id="http_event_close"></a></h4>
<div class="api_metadata">
<span>Added in: v0.5.4</span>
</div>
<p>Indicates that the request is completed, or its underlying connection was
terminated prematurely (before the response completion).</p>
<h4>Event: <code>'connect'</code><span><a class="mark" href="#all_http_event-connect" id="all_http_event-connect">#</a></span><a aria-hidden="true" class="legacy" id="http_event_connect"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div>
<ul>
<li><code>response</code> <a href="#all_http_class-httpincomingmessage" class="type">&#x3C;http.IncomingMessage></a></li>
<li><code>socket</code> <a href="#all_stream_class-streamduplex" class="type">&#x3C;stream.Duplex></a></li>
<li><code>head</code> <a href="#all_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="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a> class,
a subclass of <a href="#all_stream_class-streamduplex" class="type">&#x3C;stream.Duplex></a>, unless the user specifies a socket
type other than <a href="#all_net_class-netsocket" 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 class="with-50-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createServer, request } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;
<span class="hljs-keyword">import</span> { connect } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:net'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-variable constant_">URL</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:url'</span>;

<span class="hljs-comment">// Create an HTTP tunneling proxy</span>
<span class="hljs-keyword">const</span> proxy = <span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
  res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain'</span> });
  res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'okay'</span>);
});
proxy.<span class="hljs-title function_">on</span>(<span class="hljs-string">'connect'</span>, <span class="hljs-function">(<span class="hljs-params">req, clientSocket, head</span>) =></span> {
  <span class="hljs-comment">// Connect to an origin server</span>
  <span class="hljs-keyword">const</span> { port, hostname } = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">`http://<span class="hljs-subst">${req.url}</span>`</span>);
  <span class="hljs-keyword">const</span> serverSocket = <span class="hljs-title function_">connect</span>(port || <span class="hljs-number">80</span>, hostname, <span class="hljs-function">() =></span> {
    clientSocket.<span class="hljs-title function_">write</span>(<span class="hljs-string">'HTTP/1.1 200 Connection Established\r\n'</span> +
                    <span class="hljs-string">'Proxy-agent: Node.js-Proxy\r\n'</span> +
                    <span class="hljs-string">'\r\n'</span>);
    serverSocket.<span class="hljs-title function_">write</span>(head);
    serverSocket.<span class="hljs-title function_">pipe</span>(clientSocket);
    clientSocket.<span class="hljs-title function_">pipe</span>(serverSocket);
  });
});

<span class="hljs-comment">// Now that proxy is running</span>
proxy.<span class="hljs-title function_">listen</span>(<span class="hljs-number">1337</span>, <span class="hljs-string">'127.0.0.1'</span>, <span class="hljs-function">() =></span> {

  <span class="hljs-comment">// Make a request to a tunneling proxy</span>
  <span class="hljs-keyword">const</span> options = {
    <span class="hljs-attr">port</span>: <span class="hljs-number">1337</span>,
    <span class="hljs-attr">host</span>: <span class="hljs-string">'127.0.0.1'</span>,
    <span class="hljs-attr">method</span>: <span class="hljs-string">'CONNECT'</span>,
    <span class="hljs-attr">path</span>: <span class="hljs-string">'www.google.com:80'</span>,
  };

  <span class="hljs-keyword">const</span> req = <span class="hljs-title function_">request</span>(options);
  req.<span class="hljs-title function_">end</span>();

  req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'connect'</span>, <span class="hljs-function">(<span class="hljs-params">res, socket, head</span>) =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'got connected!'</span>);

    <span class="hljs-comment">// Make a request over an HTTP tunnel</span>
    socket.<span class="hljs-title function_">write</span>(<span class="hljs-string">'GET / HTTP/1.1\r\n'</span> +
                 <span class="hljs-string">'Host: www.google.com:80\r\n'</span> +
                 <span class="hljs-string">'Connection: close\r\n'</span> +
                 <span class="hljs-string">'\r\n'</span>);
    socket.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> {
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk.<span class="hljs-title function_">toString</span>());
    });
    socket.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> {
      proxy.<span class="hljs-title function_">close</span>();
    });
  });
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);
<span class="hljs-keyword">const</span> net = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:net'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-variable constant_">URL</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);

<span class="hljs-comment">// Create an HTTP tunneling proxy</span>
<span class="hljs-keyword">const</span> proxy = http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
  res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain'</span> });
  res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'okay'</span>);
});
proxy.<span class="hljs-title function_">on</span>(<span class="hljs-string">'connect'</span>, <span class="hljs-function">(<span class="hljs-params">req, clientSocket, head</span>) =></span> {
  <span class="hljs-comment">// Connect to an origin server</span>
  <span class="hljs-keyword">const</span> { port, hostname } = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">`http://<span class="hljs-subst">${req.url}</span>`</span>);
  <span class="hljs-keyword">const</span> serverSocket = net.<span class="hljs-title function_">connect</span>(port || <span class="hljs-number">80</span>, hostname, <span class="hljs-function">() =></span> {
    clientSocket.<span class="hljs-title function_">write</span>(<span class="hljs-string">'HTTP/1.1 200 Connection Established\r\n'</span> +
                    <span class="hljs-string">'Proxy-agent: Node.js-Proxy\r\n'</span> +
                    <span class="hljs-string">'\r\n'</span>);
    serverSocket.<span class="hljs-title function_">write</span>(head);
    serverSocket.<span class="hljs-title function_">pipe</span>(clientSocket);
    clientSocket.<span class="hljs-title function_">pipe</span>(serverSocket);
  });
});

<span class="hljs-comment">// Now that proxy is running</span>
proxy.<span class="hljs-title function_">listen</span>(<span class="hljs-number">1337</span>, <span class="hljs-string">'127.0.0.1'</span>, <span class="hljs-function">() =></span> {

  <span class="hljs-comment">// Make a request to a tunneling proxy</span>
  <span class="hljs-keyword">const</span> options = {
    <span class="hljs-attr">port</span>: <span class="hljs-number">1337</span>,
    <span class="hljs-attr">host</span>: <span class="hljs-string">'127.0.0.1'</span>,
    <span class="hljs-attr">method</span>: <span class="hljs-string">'CONNECT'</span>,
    <span class="hljs-attr">path</span>: <span class="hljs-string">'www.google.com:80'</span>,
  };

  <span class="hljs-keyword">const</span> req = http.<span class="hljs-title function_">request</span>(options);
  req.<span class="hljs-title function_">end</span>();

  req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'connect'</span>, <span class="hljs-function">(<span class="hljs-params">res, socket, head</span>) =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'got connected!'</span>);

    <span class="hljs-comment">// Make a request over an HTTP tunnel</span>
    socket.<span class="hljs-title function_">write</span>(<span class="hljs-string">'GET / HTTP/1.1\r\n'</span> +
                 <span class="hljs-string">'Host: www.google.com:80\r\n'</span> +
                 <span class="hljs-string">'Connection: close\r\n'</span> +
                 <span class="hljs-string">'\r\n'</span>);
    socket.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> {
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk.<span class="hljs-title function_">toString</span>());
    });
    socket.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> {
      proxy.<span class="hljs-title function_">close</span>();
    });
  });
});</code><button class="copy-button">copy</button></pre>
<h4>Event: <code>'continue'</code><span><a class="mark" href="#all_http_event-continue" id="all_http_event-continue">#</a></span><a aria-hidden="true" class="legacy" id="http_event_continue"></a></h4>
<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>
<h4>Event: <code>'finish'</code><span><a class="mark" href="#all_http_event-finish" id="all_http_event-finish">#</a></span><a aria-hidden="true" class="legacy" id="http_event_finish"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.6</span>
</div>
<p>Emitted when the request 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 server has received anything yet.</p>
<h4>Event: <code>'information'</code><span><a class="mark" href="#all_http_event-information" id="all_http_event-information">#</a></span><a aria-hidden="true" class="legacy" id="http_event_information"></a></h4>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>info</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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 class="with-36-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { request } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;

<span class="hljs-keyword">const</span> options = {
  <span class="hljs-attr">host</span>: <span class="hljs-string">'127.0.0.1'</span>,
  <span class="hljs-attr">port</span>: <span class="hljs-number">8080</span>,
  <span class="hljs-attr">path</span>: <span class="hljs-string">'/length_request'</span>,
};

<span class="hljs-comment">// Make a request</span>
<span class="hljs-keyword">const</span> req = <span class="hljs-title function_">request</span>(options);
req.<span class="hljs-title function_">end</span>();

req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'information'</span>, <span class="hljs-function">(<span class="hljs-params">info</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Got information prior to main response: <span class="hljs-subst">${info.statusCode}</span>`</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);

<span class="hljs-keyword">const</span> options = {
  <span class="hljs-attr">host</span>: <span class="hljs-string">'127.0.0.1'</span>,
  <span class="hljs-attr">port</span>: <span class="hljs-number">8080</span>,
  <span class="hljs-attr">path</span>: <span class="hljs-string">'/length_request'</span>,
};

<span class="hljs-comment">// Make a request</span>
<span class="hljs-keyword">const</span> req = http.<span class="hljs-title function_">request</span>(options);
req.<span class="hljs-title function_">end</span>();

req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'information'</span>, <span class="hljs-function">(<span class="hljs-params">info</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Got information prior to main response: <span class="hljs-subst">${info.statusCode}</span>`</span>);
});</code><button class="copy-button">copy</button></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="#all_http_event-upgrade"><code>'upgrade'</code></a> event instead.</p>
<h4>Event: <code>'response'</code><span><a class="mark" href="#all_http_event-response" id="all_http_event-response">#</a></span><a aria-hidden="true" class="legacy" id="http_event_response"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.0</span>
</div>
<ul>
<li><code>response</code> <a href="#all_http_class-httpincomingmessage" 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>
<h4>Event: <code>'socket'</code><span><a class="mark" href="#all_http_event-socket" id="all_http_event-socket">#</a></span><a aria-hidden="true" class="legacy" id="http_event_socket"></a></h4>
<div class="api_metadata">
<span>Added in: v0.5.3</span>
</div>
<ul>
<li><code>socket</code> <a href="#all_stream_class-streamduplex" class="type">&#x3C;stream.Duplex></a></li>
</ul>
<p>This event is guaranteed to be passed an instance of the <a href="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a> class,
a subclass of <a href="#all_stream_class-streamduplex" class="type">&#x3C;stream.Duplex></a>, unless the user specifies a socket
type other than <a href="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a>.</p>
<h4>Event: <code>'timeout'</code><span><a class="mark" href="#all_http_event-timeout" id="all_http_event-timeout">#</a></span><a aria-hidden="true" class="legacy" id="http_event_timeout"></a></h4>
<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 destroyed manually.</p>
<p>See also: <a href="#all_http_requestsettimeouttimeout-callback"><code>request.setTimeout()</code></a>.</p>
<h4>Event: <code>'upgrade'</code><span><a class="mark" href="#all_http_event-upgrade" id="all_http_event-upgrade">#</a></span><a aria-hidden="true" class="legacy" id="http_event_upgrade"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.94</span>
</div>
<ul>
<li><code>response</code> <a href="#all_http_class-httpincomingmessage" class="type">&#x3C;http.IncomingMessage></a></li>
<li><code>socket</code> <a href="#all_stream_class-streamduplex" class="type">&#x3C;stream.Duplex></a></li>
<li><code>head</code> <a href="#all_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="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a> class,
a subclass of <a href="#all_stream_class-streamduplex" class="type">&#x3C;stream.Duplex></a>, unless the user specifies a socket
type other than <a href="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a>.</p>
<p>A client server pair demonstrating how to listen for the <code>'upgrade'</code> event.</p>

<pre class="with-35-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> http <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-comment">// Create an HTTP server</span>
<span class="hljs-keyword">const</span> server = http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
  res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain'</span> });
  res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'okay'</span>);
});
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'upgrade'</span>, <span class="hljs-function">(<span class="hljs-params">req, socket, head</span>) =></span> {
  socket.<span class="hljs-title function_">write</span>(<span class="hljs-string">'HTTP/1.1 101 Web Socket Protocol Handshake\r\n'</span> +
               <span class="hljs-string">'Upgrade: WebSocket\r\n'</span> +
               <span class="hljs-string">'Connection: Upgrade\r\n'</span> +
               <span class="hljs-string">'\r\n'</span>);

  socket.<span class="hljs-title function_">pipe</span>(socket); <span class="hljs-comment">// echo back</span>
});

<span class="hljs-comment">// Now that server is running</span>
server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">1337</span>, <span class="hljs-string">'127.0.0.1'</span>, <span class="hljs-function">() =></span> {

  <span class="hljs-comment">// make a request</span>
  <span class="hljs-keyword">const</span> options = {
    <span class="hljs-attr">port</span>: <span class="hljs-number">1337</span>,
    <span class="hljs-attr">host</span>: <span class="hljs-string">'127.0.0.1'</span>,
    <span class="hljs-attr">headers</span>: {
      <span class="hljs-string">'Connection'</span>: <span class="hljs-string">'Upgrade'</span>,
      <span class="hljs-string">'Upgrade'</span>: <span class="hljs-string">'websocket'</span>,
    },
  };

  <span class="hljs-keyword">const</span> req = http.<span class="hljs-title function_">request</span>(options);
  req.<span class="hljs-title function_">end</span>();

  req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'upgrade'</span>, <span class="hljs-function">(<span class="hljs-params">res, socket, upgradeHead</span>) =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'got upgraded!'</span>);
    socket.<span class="hljs-title function_">end</span>();
    process.<span class="hljs-title function_">exit</span>(<span class="hljs-number">0</span>);
  });
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);

<span class="hljs-comment">// Create an HTTP server</span>
<span class="hljs-keyword">const</span> server = http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
  res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain'</span> });
  res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'okay'</span>);
});
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'upgrade'</span>, <span class="hljs-function">(<span class="hljs-params">req, socket, head</span>) =></span> {
  socket.<span class="hljs-title function_">write</span>(<span class="hljs-string">'HTTP/1.1 101 Web Socket Protocol Handshake\r\n'</span> +
               <span class="hljs-string">'Upgrade: WebSocket\r\n'</span> +
               <span class="hljs-string">'Connection: Upgrade\r\n'</span> +
               <span class="hljs-string">'\r\n'</span>);

  socket.<span class="hljs-title function_">pipe</span>(socket); <span class="hljs-comment">// echo back</span>
});

<span class="hljs-comment">// Now that server is running</span>
server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">1337</span>, <span class="hljs-string">'127.0.0.1'</span>, <span class="hljs-function">() =></span> {

  <span class="hljs-comment">// make a request</span>
  <span class="hljs-keyword">const</span> options = {
    <span class="hljs-attr">port</span>: <span class="hljs-number">1337</span>,
    <span class="hljs-attr">host</span>: <span class="hljs-string">'127.0.0.1'</span>,
    <span class="hljs-attr">headers</span>: {
      <span class="hljs-string">'Connection'</span>: <span class="hljs-string">'Upgrade'</span>,
      <span class="hljs-string">'Upgrade'</span>: <span class="hljs-string">'websocket'</span>,
    },
  };

  <span class="hljs-keyword">const</span> req = http.<span class="hljs-title function_">request</span>(options);
  req.<span class="hljs-title function_">end</span>();

  req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'upgrade'</span>, <span class="hljs-function">(<span class="hljs-params">res, socket, upgradeHead</span>) =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'got upgraded!'</span>);
    socket.<span class="hljs-title function_">end</span>();
    process.<span class="hljs-title function_">exit</span>(<span class="hljs-number">0</span>);
  });
});</code><button class="copy-button">copy</button></pre>
<h4><code>request.abort()</code><span><a class="mark" href="#all_http_requestabort" id="all_http_requestabort">#</a></span><a aria-hidden="true" class="legacy" id="http_request_abort"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.8</span><span>Deprecated since: v14.1.0, v13.14.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_http_requestdestroyerror"><code>request.destroy()</code></a> instead.</div><p></p>
<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>
<h4><code>request.aborted</code><span><a class="mark" href="#all_http_requestaborted" id="all_http_requestaborted">#</a></span><a aria-hidden="true" class="legacy" id="http_request_aborted"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.0.0, v16.12.0</td>
<td><p><span>Deprecated since: v17.0.0, v16.12.0</span></p></td></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>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated. Check <a href="#all_http_requestdestroyed"><code>request.destroyed</code></a> instead.</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.aborted</code> property will be <code>true</code> if the request has
been aborted.</p>
<h4><code>request.connection</code><span><a class="mark" href="#all_http_requestconnection" id="all_http_requestconnection">#</a></span><a aria-hidden="true" class="legacy" id="http_request_connection"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.0</span><span>Deprecated since: v13.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated. Use <a href="#all_http_requestsocket"><code>request.socket</code></a>.</div><p></p>
<ul>
<li><a href="#all_stream_class-streamduplex" class="type">&#x3C;stream.Duplex></a></li>
</ul>
<p>See <a href="#all_http_requestsocket"><code>request.socket</code></a>.</p>
<h4><code>request.cork()</code><span><a class="mark" href="#all_http_requestcork" id="all_http_requestcork">#</a></span><a aria-hidden="true" class="legacy" id="http_request_cork"></a></h4>
<div class="api_metadata">
<span>Added in: v13.2.0, v12.16.0</span>
</div>
<p>See <a href="#all_stream_writablecork"><code>writable.cork()</code></a>.</p>
<h4><code>request.end([data[, encoding]][, callback])</code><span><a class="mark" href="#all_http_requestenddata-encoding-callback" id="all_http_requestenddata-encoding-callback">#</a></span><a aria-hidden="true" class="legacy" id="http_request_end_data_encoding_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>The <code>data</code> parameter can now be a <code>Uint8Array</code>.</p></td></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="#all_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>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="#all_http_requestwritechunk-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>
<h4><code>request.destroy([error])</code><span><a class="mark" href="#all_http_requestdestroyerror" id="all_http_requestdestroyerror">#</a></span><a aria-hidden="true" class="legacy" id="http_request_destroy_error"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.5.0</td>
<td><p>The function returns <code>this</code> for consistency with other Readable streams.</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>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 request. Optionally emit an <code>'error'</code> event,
and emit a <code>'close'</code> event. Calling this will cause remaining data
in the response to be dropped and the socket to be destroyed.</p>
<p>See <a href="#all_stream_writabledestroyerror"><code>writable.destroy()</code></a> for further details.</p>
<h5><code>request.destroyed</code><span><a class="mark" href="#all_http_requestdestroyed" id="all_http_requestdestroyed">#</a></span><a aria-hidden="true" class="legacy" id="http_request_destroyed"></a></h5>
<div class="api_metadata">
<span>Added in: v14.1.0, v13.14.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="#all_http_requestdestroyerror"><code>request.destroy()</code></a> has been called.</p>
<p>See <a href="#all_stream_writabledestroyed"><code>writable.destroyed</code></a> for further details.</p>
<h4><code>request.finished</code><span><a class="mark" href="#all_http_requestfinished" id="all_http_requestfinished">#</a></span><a aria-hidden="true" class="legacy" id="http_request_finished"></a></h4>
<div class="api_metadata">
<span>Added in: v0.0.1</span><span>Deprecated since: v13.4.0, v12.16.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated. Use <a href="#all_http_requestwritableended"><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="#all_http_requestenddata-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="#all_http_httpgetoptions-callback"><code>http.get()</code></a>.</p>
<h4><code>request.flushHeaders()</code><span><a class="mark" href="#all_http_requestflushheaders" id="all_http_requestflushheaders">#</a></span><a aria-hidden="true" class="legacy" id="http_request_flushheaders"></a></h4>
<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>
<h4><code>request.getHeader(name)</code><span><a class="mark" href="#all_http_requestgetheadername" id="all_http_requestgetheadername">#</a></span><a aria-hidden="true" class="legacy" id="http_request_getheader_name"></a></h4>
<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="#all_http_requestsetheadername-value"><code>request.setHeader()</code></a>.</p>
<pre><code class="language-js">request.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'content-type'</span>, <span class="hljs-string">'text/html'</span>);
request.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Content-Length'</span>, <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">byteLength</span>(body));
request.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Cookie'</span>, [<span class="hljs-string">'type=ninja'</span>, <span class="hljs-string">'language=javascript'</span>]);
<span class="hljs-keyword">const</span> contentType = request.<span class="hljs-title function_">getHeader</span>(<span class="hljs-string">'Content-Type'</span>);
<span class="hljs-comment">// 'contentType' is 'text/html'</span>
<span class="hljs-keyword">const</span> contentLength = request.<span class="hljs-title function_">getHeader</span>(<span class="hljs-string">'Content-Length'</span>);
<span class="hljs-comment">// 'contentLength' is of type number</span>
<span class="hljs-keyword">const</span> cookie = request.<span class="hljs-title function_">getHeader</span>(<span class="hljs-string">'Cookie'</span>);
<span class="hljs-comment">// 'cookie' is of type string[]</span></code> <button class="copy-button">copy</button></pre>
<h4><code>request.getHeaderNames()</code><span><a class="mark" href="#all_http_requestgetheadernames" id="all_http_requestgetheadernames">#</a></span><a aria-hidden="true" class="legacy" id="http_request_getheadernames"></a></h4>
<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">request.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Foo'</span>, <span class="hljs-string">'bar'</span>);
request.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Cookie'</span>, [<span class="hljs-string">'foo=bar'</span>, <span class="hljs-string">'bar=baz'</span>]);

<span class="hljs-keyword">const</span> headerNames = request.<span class="hljs-title function_">getHeaderNames</span>();
<span class="hljs-comment">// headerNames === ['foo', 'cookie']</span></code> <button class="copy-button">copy</button></pre>
<h4><code>request.getHeaders()</code><span><a class="mark" href="#all_http_requestgetheaders" id="all_http_requestgetheaders">#</a></span><a aria-hidden="true" class="legacy" id="http_request_getheaders"></a></h4>
<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>request.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">request.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Foo'</span>, <span class="hljs-string">'bar'</span>);
request.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Cookie'</span>, [<span class="hljs-string">'foo=bar'</span>, <span class="hljs-string">'bar=baz'</span>]);

<span class="hljs-keyword">const</span> headers = request.<span class="hljs-title function_">getHeaders</span>();
<span class="hljs-comment">// headers === { foo: 'bar', 'cookie': ['foo=bar', 'bar=baz'] }</span></code> <button class="copy-button">copy</button></pre>
<h4><code>request.getRawHeaderNames()</code><span><a class="mark" href="#all_http_requestgetrawheadernames" id="all_http_requestgetrawheadernames">#</a></span><a aria-hidden="true" class="legacy" id="http_request_getrawheadernames"></a></h4>
<div class="api_metadata">
<span>Added in: v15.13.0, v14.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 an array containing the unique names of the current outgoing raw
headers. Header names are returned with their exact casing being set.</p>
<pre><code class="language-js">request.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Foo'</span>, <span class="hljs-string">'bar'</span>);
request.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Set-Cookie'</span>, [<span class="hljs-string">'foo=bar'</span>, <span class="hljs-string">'bar=baz'</span>]);

<span class="hljs-keyword">const</span> headerNames = request.<span class="hljs-title function_">getRawHeaderNames</span>();
<span class="hljs-comment">// headerNames === ['Foo', 'Set-Cookie']</span></code> <button class="copy-button">copy</button></pre>
<h4><code>request.hasHeader(name)</code><span><a class="mark" href="#all_http_requesthasheadername" id="all_http_requesthasheadername">#</a></span><a aria-hidden="true" class="legacy" id="http_request_hasheader_name"></a></h4>
<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"><span class="hljs-keyword">const</span> hasContentType = request.<span class="hljs-title function_">hasHeader</span>(<span class="hljs-string">'content-type'</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>request.maxHeadersCount</code><span><a class="mark" href="#all_http_requestmaxheaderscount" id="all_http_requestmaxheaderscount">#</a></span><a aria-hidden="true" class="legacy" id="http_request_maxheaderscount"></a></h4>
<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>
<h4><code>request.path</code><span><a class="mark" href="#all_http_requestpath" id="all_http_requestpath">#</a></span><a aria-hidden="true" class="legacy" id="http_request_path"></a></h4>
<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>
<h4><code>request.method</code><span><a class="mark" href="#all_http_requestmethod" id="all_http_requestmethod">#</a></span><a aria-hidden="true" class="legacy" id="http_request_method"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.97</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 method.</li>
</ul>
<h4><code>request.host</code><span><a class="mark" href="#all_http_requesthost" id="all_http_requesthost">#</a></span><a aria-hidden="true" class="legacy" id="http_request_host"></a></h4>
<div class="api_metadata">
<span>Added in: v14.5.0, v12.19.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 host.</li>
</ul>
<h4><code>request.protocol</code><span><a class="mark" href="#all_http_requestprotocol" id="all_http_requestprotocol">#</a></span><a aria-hidden="true" class="legacy" id="http_request_protocol"></a></h4>
<div class="api_metadata">
<span>Added in: v14.5.0, v12.19.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 protocol.</li>
</ul>
<h4><code>request.removeHeader(name)</code><span><a class="mark" href="#all_http_requestremoveheadername" id="all_http_requestremoveheadername">#</a></span><a aria-hidden="true" class="legacy" id="http_request_removeheader_name"></a></h4>
<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.<span class="hljs-title function_">removeHeader</span>(<span class="hljs-string">'Content-Type'</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>request.reusedSocket</code><span><a class="mark" href="#all_http_requestreusedsocket" id="all_http_requestreusedsocket">#</a></span><a aria-hidden="true" class="legacy" id="http_request_reusedsocket"></a></h4>
<div class="api_metadata">
<span>Added in: v13.0.0, 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 class="with-34-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> http <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;

<span class="hljs-comment">// Server has a 5 seconds keep-alive timeout by default</span>
http
  .<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
    res.<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello\n'</span>);
    res.<span class="hljs-title function_">end</span>();
  })
  .<span class="hljs-title function_">listen</span>(<span class="hljs-number">3000</span>);

<span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =></span> {
  <span class="hljs-comment">// Adapting a keep-alive agent</span>
  http.<span class="hljs-title function_">get</span>(<span class="hljs-string">'http://localhost:3000'</span>, { agent }, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
    res.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
      <span class="hljs-comment">// Do nothing</span>
    });
  });
}, <span class="hljs-number">5000</span>); <span class="hljs-comment">// Sending request on 5s interval so it's easy to hit idle timeout</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);

<span class="hljs-comment">// Server has a 5 seconds keep-alive timeout by default</span>
http
  .<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
    res.<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello\n'</span>);
    res.<span class="hljs-title function_">end</span>();
  })
  .<span class="hljs-title function_">listen</span>(<span class="hljs-number">3000</span>);

<span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =></span> {
  <span class="hljs-comment">// Adapting a keep-alive agent</span>
  http.<span class="hljs-title function_">get</span>(<span class="hljs-string">'http://localhost:3000'</span>, { agent }, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
    res.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
      <span class="hljs-comment">// Do nothing</span>
    });
  });
}, <span class="hljs-number">5000</span>); <span class="hljs-comment">// Sending request on 5s interval so it's easy to hit idle timeout</span></code><button class="copy-button">copy</button></pre>
<p>By marking a request whether it reused socket or not, we can do
automatic error retry base on it.</p>

<pre class="with-50-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> http <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;
<span class="hljs-keyword">const</span> agent = <span class="hljs-keyword">new</span> http.<span class="hljs-title class_">Agent</span>({ <span class="hljs-attr">keepAlive</span>: <span class="hljs-literal">true</span> });

<span class="hljs-keyword">function</span> <span class="hljs-title function_">retriableRequest</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">const</span> req = http
    .<span class="hljs-title function_">get</span>(<span class="hljs-string">'http://localhost:3000'</span>, { agent }, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
      <span class="hljs-comment">// ...</span>
    })
    .<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
      <span class="hljs-comment">// Check if retry is needed</span>
      <span class="hljs-keyword">if</span> (req.<span class="hljs-property">reusedSocket</span> &#x26;&#x26; err.<span class="hljs-property">code</span> === <span class="hljs-string">'ECONNRESET'</span>) {
        <span class="hljs-title function_">retriableRequest</span>();
      }
    });
}

<span class="hljs-title function_">retriableRequest</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);
<span class="hljs-keyword">const</span> agent = <span class="hljs-keyword">new</span> http.<span class="hljs-title class_">Agent</span>({ <span class="hljs-attr">keepAlive</span>: <span class="hljs-literal">true</span> });

<span class="hljs-keyword">function</span> <span class="hljs-title function_">retriableRequest</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">const</span> req = http
    .<span class="hljs-title function_">get</span>(<span class="hljs-string">'http://localhost:3000'</span>, { agent }, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
      <span class="hljs-comment">// ...</span>
    })
    .<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
      <span class="hljs-comment">// Check if retry is needed</span>
      <span class="hljs-keyword">if</span> (req.<span class="hljs-property">reusedSocket</span> &#x26;&#x26; err.<span class="hljs-property">code</span> === <span class="hljs-string">'ECONNRESET'</span>) {
        <span class="hljs-title function_">retriableRequest</span>();
      }
    });
}

<span class="hljs-title function_">retriableRequest</span>();</code><button class="copy-button">copy</button></pre>
<h4><code>request.setHeader(name, value)</code><span><a class="mark" href="#all_http_requestsetheadername-value" id="all_http_requestsetheadername-value">#</a></span><a aria-hidden="true" class="legacy" id="http_request_setheader_name_value"></a></h4>
<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="#all_http_requestgetheadername"><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.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Content-Type'</span>, <span class="hljs-string">'application/json'</span>);</code> <button class="copy-button">copy</button></pre>
<p>or</p>
<pre><code class="language-js">request.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Cookie'</span>, [<span class="hljs-string">'type=ninja'</span>, <span class="hljs-string">'language=javascript'</span>]);</code> <button class="copy-button">copy</button></pre>
<p>When the value is a string an exception will be thrown if it contains
characters outside the <code>latin1</code> encoding.</p>
<p>If you need to pass UTF-8 characters in the value please encode the value
using the <a href="https://www.rfc-editor.org/rfc/rfc8187.txt">RFC 8187</a> standard.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> filename = <span class="hljs-string">'Rock 🎵.txt'</span>;
request.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Content-Disposition'</span>, <span class="hljs-string">`attachment; filename*=utf-8''<span class="hljs-subst">${<span class="hljs-built_in">encodeURIComponent</span>(filename)}</span>`</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>request.setNoDelay([noDelay])</code><span><a class="mark" href="#all_http_requestsetnodelaynodelay" id="all_http_requestsetnodelaynodelay">#</a></span><a aria-hidden="true" class="legacy" id="http_request_setnodelay_nodelay"></a></h4>
<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="#all_net_socketsetnodelaynodelay"><code>socket.setNoDelay()</code></a> will be called.</p>
<h4><code>request.setSocketKeepAlive([enable][, initialDelay])</code><span><a class="mark" href="#all_http_requestsetsocketkeepaliveenable-initialdelay" id="all_http_requestsetsocketkeepaliveenable-initialdelay">#</a></span><a aria-hidden="true" class="legacy" id="http_request_setsocketkeepalive_enable_initialdelay"></a></h4>
<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="#all_net_socketsetkeepaliveenable-initialdelay"><code>socket.setKeepAlive()</code></a> will be called.</p>
<h4><code>request.setTimeout(timeout[, callback])</code><span><a class="mark" href="#all_http_requestsettimeouttimeout-callback" id="all_http_requestsettimeouttimeout-callback">#</a></span><a aria-hidden="true" class="legacy" id="http_request_settimeout_timeout_callback"></a></h4>
<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="#all_http_class-httpclientrequest" class="type">&#x3C;http.ClientRequest></a></li>
</ul>
<p>Once a socket is assigned to this request and is connected
<a href="#all_net_socketsettimeouttimeout-callback"><code>socket.setTimeout()</code></a> will be called.</p>
<h4><code>request.socket</code><span><a class="mark" href="#all_http_requestsocket" id="all_http_requestsocket">#</a></span><a aria-hidden="true" class="legacy" id="http_request_socket"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div>
<ul>
<li><a href="#all_stream_class-streamduplex" 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.</p>

<pre class="with-34-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> http <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;
<span class="hljs-keyword">const</span> options = {
  <span class="hljs-attr">host</span>: <span class="hljs-string">'www.google.com'</span>,
};
<span class="hljs-keyword">const</span> req = http.<span class="hljs-title function_">get</span>(options);
req.<span class="hljs-title function_">end</span>();
req.<span class="hljs-title function_">once</span>(<span class="hljs-string">'response'</span>, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
  <span class="hljs-keyword">const</span> ip = req.<span class="hljs-property">socket</span>.<span class="hljs-property">localAddress</span>;
  <span class="hljs-keyword">const</span> port = req.<span class="hljs-property">socket</span>.<span class="hljs-property">localPort</span>;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Your IP address is <span class="hljs-subst">${ip}</span> and your source port is <span class="hljs-subst">${port}</span>.`</span>);
  <span class="hljs-comment">// Consume response object</span>
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);
<span class="hljs-keyword">const</span> options = {
  <span class="hljs-attr">host</span>: <span class="hljs-string">'www.google.com'</span>,
};
<span class="hljs-keyword">const</span> req = http.<span class="hljs-title function_">get</span>(options);
req.<span class="hljs-title function_">end</span>();
req.<span class="hljs-title function_">once</span>(<span class="hljs-string">'response'</span>, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
  <span class="hljs-keyword">const</span> ip = req.<span class="hljs-property">socket</span>.<span class="hljs-property">localAddress</span>;
  <span class="hljs-keyword">const</span> port = req.<span class="hljs-property">socket</span>.<span class="hljs-property">localPort</span>;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Your IP address is <span class="hljs-subst">${ip}</span> and your source port is <span class="hljs-subst">${port}</span>.`</span>);
  <span class="hljs-comment">// Consume response object</span>
});</code><button class="copy-button">copy</button></pre>
<p>This property is guaranteed to be an instance of the <a href="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a> class,
a subclass of <a href="#all_stream_class-streamduplex" class="type">&#x3C;stream.Duplex></a>, unless the user specified a socket
type other than <a href="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a>.</p>
<h4><code>request.uncork()</code><span><a class="mark" href="#all_http_requestuncork" id="all_http_requestuncork">#</a></span><a aria-hidden="true" class="legacy" id="http_request_uncork"></a></h4>
<div class="api_metadata">
<span>Added in: v13.2.0, v12.16.0</span>
</div>
<p>See <a href="#all_stream_writableuncork"><code>writable.uncork()</code></a>.</p>
<h4><code>request.writableEnded</code><span><a class="mark" href="#all_http_requestwritableended" id="all_http_requestwritableended">#</a></span><a aria-hidden="true" class="legacy" id="http_request_writableended"></a></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="#all_http_requestenddata-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="#all_http_requestwritablefinished"><code>request.writableFinished</code></a> instead.</p>
<h4><code>request.writableFinished</code><span><a class="mark" href="#all_http_requestwritablefinished" id="all_http_requestwritablefinished">#</a></span><a aria-hidden="true" class="legacy" id="http_request_writablefinished"></a></h4>
<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="#all_http_event-finish"><code>'finish'</code></a> event is emitted.</p>
<h4><code>request.write(chunk[, encoding][, callback])</code><span><a class="mark" href="#all_http_requestwritechunk-encoding-callback" id="all_http_requestwritechunk-encoding-callback">#</a></span><a aria-hidden="true" class="legacy" id="http_request_write_chunk_encoding_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>The <code>chunk</code> parameter can now be a <code>Uint8Array</code>.</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>chunk</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#all_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>Sends a chunk of the body. This method can be called multiple times. If no
<code>Content-Length</code> is set, data will automatically be encoded in HTTP Chunked
transfer encoding, so that server knows when the data ends. The
<code>Transfer-Encoding: chunked</code> header is added. Calling <a href="#all_http_requestenddata-encoding-callback"><code>request.end()</code></a>
is necessary to finish sending 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>
</section><section><h3>Class: <code>http.Server</code><span><a class="mark" href="#all_http_class-httpserver" id="all_http_class-httpserver">#</a></span><a aria-hidden="true" class="legacy" id="http_class_http_server"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.17</span>
</div>
<ul>
<li>Extends: <a href="#all_net_class-netserver" class="type">&#x3C;net.Server></a></li>
</ul>
<h4>Event: <code>'checkContinue'</code><span><a class="mark" href="#all_http_event-checkcontinue" id="all_http_event-checkcontinue">#</a></span><a aria-hidden="true" class="legacy" id="http_event_checkcontinue"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div>
<ul>
<li><code>request</code> <a href="#all_http_class-httpincomingmessage" class="type">&#x3C;http.IncomingMessage></a></li>
<li><code>response</code> <a href="#all_http_class-httpserverresponse" 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="#all_http_responsewritecontinue"><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="#all_http_event-request"><code>'request'</code></a> event will
not be emitted.</p>
<h4>Event: <code>'checkExpectation'</code><span><a class="mark" href="#all_http_event-checkexpectation" id="all_http_event-checkexpectation">#</a></span><a aria-hidden="true" class="legacy" id="http_event_checkexpectation"></a></h4>
<div class="api_metadata">
<span>Added in: v5.5.0</span>
</div>
<ul>
<li><code>request</code> <a href="#all_http_class-httpincomingmessage" class="type">&#x3C;http.IncomingMessage></a></li>
<li><code>response</code> <a href="#all_http_class-httpserverresponse" 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="#all_http_event-request"><code>'request'</code></a> event will
not be emitted.</p>
<h4>Event: <code>'clientError'</code><span><a class="mark" href="#all_http_event-clienterror" id="all_http_event-clienterror">#</a></span><a aria-hidden="true" class="legacy" id="http_event_clienterror"></a></h4>
<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="#all_stream_class-streamduplex" 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. The socket
<strong>must be closed or destroyed</strong> before the listener ends.</p>
<p>This event is guaranteed to be passed an instance of the <a href="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a> class,
a subclass of <a href="#all_stream_class-streamduplex" class="type">&#x3C;stream.Duplex></a>, unless the user specifies a socket
type other than <a href="#all_net_class-netsocket" 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="#all_errors_hpe_header_overflow"><code>HPE_HEADER_OVERFLOW</code></a> error. If the socket is not writable or headers
of the current attached <a href="#all_http_class-httpserverresponse"><code>http.ServerResponse</code></a> has been sent, it is
immediately destroyed.</p>
<p><code>socket</code> is the <a href="#all_net_class-netsocket"><code>net.Socket</code></a> object that the error originated from.</p>

<pre class="with-34-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> http <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;

<span class="hljs-keyword">const</span> server = http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
  res.<span class="hljs-title function_">end</span>();
});
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'clientError'</span>, <span class="hljs-function">(<span class="hljs-params">err, socket</span>) =></span> {
  socket.<span class="hljs-title function_">end</span>(<span class="hljs-string">'HTTP/1.1 400 Bad Request\r\n\r\n'</span>);
});
server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);

<span class="hljs-keyword">const</span> server = http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
  res.<span class="hljs-title function_">end</span>();
});
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'clientError'</span>, <span class="hljs-function">(<span class="hljs-params">err, socket</span>) =></span> {
  socket.<span class="hljs-title function_">end</span>(<span class="hljs-string">'HTTP/1.1 400 Bad Request\r\n\r\n'</span>);
});
server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);</code><button class="copy-button">copy</button></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.<span class="hljs-title function_">on</span>(<span class="hljs-string">'clientError'</span>, <span class="hljs-function">(<span class="hljs-params">err, socket</span>) =></span> {
  <span class="hljs-keyword">if</span> (err.<span class="hljs-property">code</span> === <span class="hljs-string">'ECONNRESET'</span> || !socket.<span class="hljs-property">writable</span>) {
    <span class="hljs-keyword">return</span>;
  }

  socket.<span class="hljs-title function_">end</span>(<span class="hljs-string">'HTTP/1.1 400 Bad Request\r\n\r\n'</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4>Event: <code>'close'</code><span><a class="mark" href="#all_http_event-close_1" id="all_http_event-close_1">#</a></span><a aria-hidden="true" class="legacy" id="http_event_close_1"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.4</span>
</div>
<p>Emitted when the server closes.</p>
<h4>Event: <code>'connect'</code><span><a class="mark" href="#all_http_event-connect_1" id="all_http_event-connect_1">#</a></span><a aria-hidden="true" class="legacy" id="http_event_connect_1"></a></h4>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div>
<ul>
<li><code>request</code> <a href="#all_http_class-httpincomingmessage" class="type">&#x3C;http.IncomingMessage></a> Arguments for the HTTP request, as it is in
the <a href="#all_http_event-request"><code>'request'</code></a> event</li>
<li><code>socket</code> <a href="#all_stream_class-streamduplex" class="type">&#x3C;stream.Duplex></a> Network socket between the server and client</li>
<li><code>head</code> <a href="#all_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="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a> class,
a subclass of <a href="#all_stream_class-streamduplex" class="type">&#x3C;stream.Duplex></a>, unless the user specifies a socket
type other than <a href="#all_net_class-netsocket" 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>
<h4>Event: <code>'connection'</code><span><a class="mark" href="#all_http_event-connection" id="all_http_event-connection">#</a></span><a aria-hidden="true" class="legacy" id="http_event_connection"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.0</span>
</div>
<ul>
<li><code>socket</code> <a href="#all_stream_class-streamduplex" 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="#all_net_class-netsocket"><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.socket</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="#all_stream_class-streamduplex"><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="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a> class,
a subclass of <a href="#all_stream_class-streamduplex" class="type">&#x3C;stream.Duplex></a>, unless the user specifies a socket
type other than <a href="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a>.</p>
<h4>Event: <code>'dropRequest'</code><span><a class="mark" href="#all_http_event-droprequest" id="all_http_event-droprequest">#</a></span><a aria-hidden="true" class="legacy" id="http_event_droprequest"></a></h4>
<div class="api_metadata">
<span>Added in: v18.7.0, v16.17.0</span>
</div>
<ul>
<li><code>request</code> <a href="#all_http_class-httpincomingmessage" class="type">&#x3C;http.IncomingMessage></a> Arguments for the HTTP request, as it is in
the <a href="#all_http_event-request"><code>'request'</code></a> event</li>
<li><code>socket</code> <a href="#all_stream_class-streamduplex" class="type">&#x3C;stream.Duplex></a> Network socket between the server and client</li>
</ul>
<p>When the number of requests on a socket reaches the threshold of
<code>server.maxRequestsPerSocket</code>, the server will drop new requests
and emit <code>'dropRequest'</code> event instead, then send <code>503</code> to client.</p>
<h4>Event: <code>'request'</code><span><a class="mark" href="#all_http_event-request" id="all_http_event-request">#</a></span><a aria-hidden="true" class="legacy" id="http_event_request"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.0</span>
</div>
<ul>
<li><code>request</code> <a href="#all_http_class-httpincomingmessage" class="type">&#x3C;http.IncomingMessage></a></li>
<li><code>response</code> <a href="#all_http_class-httpserverresponse" 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>
<h4>Event: <code>'upgrade'</code><span><a class="mark" href="#all_http_event-upgrade_1" id="all_http_event-upgrade_1">#</a></span><a aria-hidden="true" class="legacy" id="http_event_upgrade_1"></a></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>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="#all_http_class-httpincomingmessage" class="type">&#x3C;http.IncomingMessage></a> Arguments for the HTTP request, as it is in
the <a href="#all_http_event-request"><code>'request'</code></a> event</li>
<li><code>socket</code> <a href="#all_stream_class-streamduplex" class="type">&#x3C;stream.Duplex></a> Network socket between the server and client</li>
<li><code>head</code> <a href="#all_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="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a> class,
a subclass of <a href="#all_stream_class-streamduplex" class="type">&#x3C;stream.Duplex></a>, unless the user specifies a socket
type other than <a href="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a>.</p>
<h4><code>server.close([callback])</code><span><a class="mark" href="#all_http_serverclosecallback" id="all_http_serverclosecallback">#</a></span><a aria-hidden="true" class="legacy" id="http_server_close_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>The method closes idle connections before returning.</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>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 and closes all connections
connected to this server which are not sending a request or waiting for
a response.
See <a href="#all_net_serverclosecallback"><code>net.Server.close()</code></a>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);

<span class="hljs-keyword">const</span> server = http.<span class="hljs-title function_">createServer</span>({ <span class="hljs-attr">keepAliveTimeout</span>: <span class="hljs-number">60000</span> }, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
  res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span> });
  res.<span class="hljs-title function_">end</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>({
    <span class="hljs-attr">data</span>: <span class="hljs-string">'Hello World!'</span>,
  }));
});

server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);
<span class="hljs-comment">// Close the server after 10 seconds</span>
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
  server.<span class="hljs-title function_">close</span>(<span class="hljs-function">() =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'server on port 8000 closed successfully'</span>);
  });
}, <span class="hljs-number">10000</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>server.closeAllConnections()</code><span><a class="mark" href="#all_http_servercloseallconnections" id="all_http_servercloseallconnections">#</a></span><a aria-hidden="true" class="legacy" id="http_server_closeallconnections"></a></h4>
<div class="api_metadata">
<span>Added in: v18.2.0</span>
</div>
<p>Closes all established HTTP(S) connections connected to this server, including
active connections connected to this server which are sending a request or
waiting for a response. This does <em>not</em> destroy sockets upgraded to a different
protocol, such as WebSocket or HTTP/2.</p>
<blockquote>
<p>This is a forceful way of closing all connections and should be used with
caution. Whenever using this in conjunction with <code>server.close</code>, calling this
<em>after</em> <code>server.close</code> is recommended as to avoid race conditions where new
connections are created between a call to this and a call to <code>server.close</code>.</p>
</blockquote>
<pre><code class="language-js"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);

<span class="hljs-keyword">const</span> server = http.<span class="hljs-title function_">createServer</span>({ <span class="hljs-attr">keepAliveTimeout</span>: <span class="hljs-number">60000</span> }, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
  res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span> });
  res.<span class="hljs-title function_">end</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>({
    <span class="hljs-attr">data</span>: <span class="hljs-string">'Hello World!'</span>,
  }));
});

server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);
<span class="hljs-comment">// Close the server after 10 seconds</span>
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
  server.<span class="hljs-title function_">close</span>(<span class="hljs-function">() =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'server on port 8000 closed successfully'</span>);
  });
  <span class="hljs-comment">// Closes all connections, ensuring the server closes successfully</span>
  server.<span class="hljs-title function_">closeAllConnections</span>();
}, <span class="hljs-number">10000</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>server.closeIdleConnections()</code><span><a class="mark" href="#all_http_servercloseidleconnections" id="all_http_servercloseidleconnections">#</a></span><a aria-hidden="true" class="legacy" id="http_server_closeidleconnections"></a></h4>
<div class="api_metadata">
<span>Added in: v18.2.0</span>
</div>
<p>Closes all connections connected to this server which are not sending a request
or waiting for a response.</p>
<blockquote>
<p>Starting with Node.js 19.0.0, there's no need for calling this method in
conjunction with <code>server.close</code> to reap <code>keep-alive</code> connections. Using it
won't cause any harm though, and it can be useful to ensure backwards
compatibility for libraries and applications that need to support versions
older than 19.0.0. Whenever using this in conjunction with <code>server.close</code>,
calling this <em>after</em> <code>server.close</code> is recommended as to avoid race
conditions where new connections are created between a call to this and a
call to <code>server.close</code>.</p>
</blockquote>
<pre><code class="language-js"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);

<span class="hljs-keyword">const</span> server = http.<span class="hljs-title function_">createServer</span>({ <span class="hljs-attr">keepAliveTimeout</span>: <span class="hljs-number">60000</span> }, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
  res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span> });
  res.<span class="hljs-title function_">end</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>({
    <span class="hljs-attr">data</span>: <span class="hljs-string">'Hello World!'</span>,
  }));
});

server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);
<span class="hljs-comment">// Close the server after 10 seconds</span>
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
  server.<span class="hljs-title function_">close</span>(<span class="hljs-function">() =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'server on port 8000 closed successfully'</span>);
  });
  <span class="hljs-comment">// Closes idle connections, such as keep-alive connections. Server will close</span>
  <span class="hljs-comment">// once remaining active connections are terminated</span>
  server.<span class="hljs-title function_">closeIdleConnections</span>();
}, <span class="hljs-number">10000</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>server.headersTimeout</code><span><a class="mark" href="#all_http_serverheaderstimeout" id="all_http_serverheaderstimeout">#</a></span><a aria-hidden="true" class="legacy" id="http_server_headerstimeout"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.4.0, v18.14.0</td>
<td><p>The default is now set to the minimum between 60000 (60 seconds) or <code>requestTimeout</code>.</p></td></tr>
<tr><td>v11.3.0, v10.14.0</td>
<td><p><span>Added in: v11.3.0, v10.14.0</span></p></td></tr>
</tbody></table>
</details>
</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> The minimum between <a href="#all_http_serverrequesttimeout"><code>server.requestTimeout</code></a> or <code>60000</code>.</li>
</ul>
<p>Limit the amount of time the parser will wait to receive the complete HTTP
headers.</p>
<p>If the timeout expires, the server responds with status 408 without
forwarding the request to the request listener and then closes the connection.</p>
<p>It must be set to a non-zero value (e.g. 120 seconds) to protect against
potential Denial-of-Service attacks in case the server is deployed without a
reverse proxy in front.</p>
<h4><code>server.listen()</code><span><a class="mark" href="#all_http_serverlisten" id="all_http_serverlisten">#</a></span><a aria-hidden="true" class="legacy" id="http_server_listen"></a></h4>
<p>Starts the HTTP server listening for connections.
This method is identical to <a href="#all_net_serverlisten"><code>server.listen()</code></a> from <a href="#all_net_class-netserver"><code>net.Server</code></a>.</p>
<h4><code>server.listening</code><span><a class="mark" href="#all_http_serverlistening" id="all_http_serverlistening">#</a></span><a aria-hidden="true" class="legacy" id="http_server_listening"></a></h4>
<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>
<h4><code>server.maxHeadersCount</code><span><a class="mark" href="#all_http_servermaxheaderscount" id="all_http_servermaxheaderscount">#</a></span><a aria-hidden="true" class="legacy" id="http_server_maxheaderscount"></a></h4>
<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>
<h4><code>server.requestTimeout</code><span><a class="mark" href="#all_http_serverrequesttimeout" id="all_http_serverrequesttimeout">#</a></span><a aria-hidden="true" class="legacy" id="http_server_requesttimeout"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>The default request timeout changed from no timeout to 300s (5 minutes).</p></td></tr>
<tr><td>v14.11.0</td>
<td><p><span>Added in: v14.11.0</span></p></td></tr>
</tbody></table>
</details>
</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>300000</code></li>
</ul>
<p>Sets the timeout value in milliseconds for receiving the entire request from
the client.</p>
<p>If the timeout expires, the server responds with status 408 without
forwarding the request to the request listener and then closes the connection.</p>
<p>It must be set to a non-zero value (e.g. 120 seconds) to protect against
potential Denial-of-Service attacks in case the server is deployed without a
reverse proxy in front.</p>
<h4><code>server.setTimeout([msecs][, callback])</code><span><a class="mark" href="#all_http_serversettimeoutmsecs-callback" id="all_http_serversettimeoutmsecs-callback">#</a></span><a aria-hidden="true" class="legacy" id="http_server_settimeout_msecs_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.0.0</td>
<td><p>The default timeout changed from 120s to 0 (no timeout).</p></td></tr>
<tr><td>v0.9.12</td>
<td><p><span>Added in: v0.9.12</span></p></td></tr>
</tbody></table>
</details>
</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> 0 (no timeout)</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="#all_http_class-httpserver" 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 does not timeout sockets. However, if a callback
is assigned to the Server's <code>'timeout'</code> event, timeouts must be handled
explicitly.</p>
<h4><code>server.maxRequestsPerSocket</code><span><a class="mark" href="#all_http_servermaxrequestspersocket" id="all_http_servermaxrequestspersocket">#</a></span><a aria-hidden="true" class="legacy" id="http_server_maxrequestspersocket"></a></h4>
<div class="api_metadata">
<span>Added in: v16.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> Requests per socket. <strong>Default:</strong> 0 (no limit)</li>
</ul>
<p>The maximum number of requests socket can handle
before closing keep alive connection.</p>
<p>A value of <code>0</code> will disable the limit.</p>
<p>When the limit is reached it will set the <code>Connection</code> header value to <code>close</code>,
but will not actually close the connection, subsequent requests sent
after the limit is reached will get <code>503 Service Unavailable</code> as a response.</p>
<h4><code>server.timeout</code><span><a class="mark" href="#all_http_servertimeout" id="all_http_servertimeout">#</a></span><a aria-hidden="true" class="legacy" id="http_server_timeout"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.0.0</td>
<td><p>The default timeout changed from 120s to 0 (no timeout).</p></td></tr>
<tr><td>v0.9.12</td>
<td><p><span>Added in: v0.9.12</span></p></td></tr>
</tbody></table>
</details>
</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> 0 (no timeout)</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>
<h4><code>server.keepAliveTimeout</code><span><a class="mark" href="#all_http_serverkeepalivetimeout" id="all_http_serverkeepalivetimeout">#</a></span><a aria-hidden="true" class="legacy" id="http_server_keepalivetimeout"></a></h4>
<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="#all_http_servertimeout"><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>
<h4><code>server[Symbol.asyncDispose]()</code><span><a class="mark" href="#all_http_serversymbolasyncdispose" id="all_http_serversymbolasyncdispose">#</a></span><a aria-hidden="true" class="legacy" id="http_server_symbol_asyncdispose"></a></h4>
<div class="api_metadata">
<span>Added in: v20.4.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Calls <a href="#all_http_serverclosecallback"><code>server.close()</code></a> and returns a promise that fulfills when the
server has closed.</p>
</section><section><h3>Class: <code>http.ServerResponse</code><span><a class="mark" href="#all_http_class-httpserverresponse" id="all_http_class-httpserverresponse">#</a></span><a aria-hidden="true" class="legacy" id="http_class_http_serverresponse"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.17</span>
</div>
<ul>
<li>Extends: <a href="#all_http_class-httpoutgoingmessage" class="type">&#x3C;http.OutgoingMessage></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="#all_http_event-request"><code>'request'</code></a> event.</p>
<h4>Event: <code>'close'</code><span><a class="mark" href="#all_http_event-close_2" id="all_http_event-close_2">#</a></span><a aria-hidden="true" class="legacy" id="http_event_close_2"></a></h4>
<div class="api_metadata">
<span>Added in: v0.6.7</span>
</div>
<p>Indicates that the response is completed, or its underlying connection was
terminated prematurely (before the response completion).</p>
<h4>Event: <code>'finish'</code><span><a class="mark" href="#all_http_event-finish_1" id="all_http_event-finish_1">#</a></span><a aria-hidden="true" class="legacy" id="http_event_finish_1"></a></h4>
<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>
<h4><code>response.addTrailers(headers)</code><span><a class="mark" href="#all_http_responseaddtrailersheaders" id="all_http_responseaddtrailersheaders">#</a></span><a aria-hidden="true" class="legacy" id="http_response_addtrailers_headers"></a></h4>
<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.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain'</span>,
                          <span class="hljs-string">'Trailer'</span>: <span class="hljs-string">'Content-MD5'</span> });
response.<span class="hljs-title function_">write</span>(fileData);
response.<span class="hljs-title function_">addTrailers</span>({ <span class="hljs-string">'Content-MD5'</span>: <span class="hljs-string">'7895bf4b8828b55ceaf47747b4bca667'</span> });
response.<span class="hljs-title function_">end</span>();</code> <button class="copy-button">copy</button></pre>
<p>Attempting to set a header field name or value that contains invalid characters
will result in a <a href="#all_errors_class-typeerror"><code>TypeError</code></a> being thrown.</p>
<h4><code>response.connection</code><span><a class="mark" href="#all_http_responseconnection" id="all_http_responseconnection">#</a></span><a aria-hidden="true" class="legacy" id="http_response_connection"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.0</span><span>Deprecated since: v13.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated. Use <a href="#all_http_responsesocket"><code>response.socket</code></a>.</div><p></p>
<ul>
<li><a href="#all_stream_class-streamduplex" class="type">&#x3C;stream.Duplex></a></li>
</ul>
<p>See <a href="#all_http_responsesocket"><code>response.socket</code></a>.</p>
<h4><code>response.cork()</code><span><a class="mark" href="#all_http_responsecork" id="all_http_responsecork">#</a></span><a aria-hidden="true" class="legacy" id="http_response_cork"></a></h4>
<div class="api_metadata">
<span>Added in: v13.2.0, v12.16.0</span>
</div>
<p>See <a href="#all_stream_writablecork"><code>writable.cork()</code></a>.</p>
<h4><code>response.end([data[, encoding]][, callback])</code><span><a class="mark" href="#all_http_responseenddata-encoding-callback" id="all_http_responseenddata-encoding-callback">#</a></span><a aria-hidden="true" class="legacy" id="http_response_end_data_encoding_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>The <code>data</code> parameter can now be a <code>Uint8Array</code>.</p></td></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="#all_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 similar in effect to calling
<a href="#all_http_responsewritechunk-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="#all_http_responsefinished" id="all_http_responsefinished">#</a></span><a aria-hidden="true" class="legacy" id="http_response_finished"></a></h4>
<div class="api_metadata">
<span>Added in: v0.0.2</span><span>Deprecated since: v13.4.0, v12.16.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated. Use <a href="#all_http_responsewritableended"><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="#all_http_responseenddata-encoding-callback"><code>response.end()</code></a>
has been called.</p>
<h4><code>response.flushHeaders()</code><span><a class="mark" href="#all_http_responseflushheaders" id="all_http_responseflushheaders">#</a></span><a aria-hidden="true" class="legacy" id="http_response_flushheaders"></a></h4>
<div class="api_metadata">
<span>Added in: v1.6.0</span>
</div>
<p>Flushes the response headers. See also: <a href="#all_http_requestflushheaders"><code>request.flushHeaders()</code></a>.</p>
<h4><code>response.getHeader(name)</code><span><a class="mark" href="#all_http_responsegetheadername" id="all_http_responsegetheadername">#</a></span><a aria-hidden="true" class="legacy" id="http_response_getheader_name"></a></h4>
<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="#all_http_responsesetheadername-value"><code>response.setHeader()</code></a>.</p>
<pre><code class="language-js">response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Content-Type'</span>, <span class="hljs-string">'text/html'</span>);
response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Content-Length'</span>, <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">byteLength</span>(body));
response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Set-Cookie'</span>, [<span class="hljs-string">'type=ninja'</span>, <span class="hljs-string">'language=javascript'</span>]);
<span class="hljs-keyword">const</span> contentType = response.<span class="hljs-title function_">getHeader</span>(<span class="hljs-string">'content-type'</span>);
<span class="hljs-comment">// contentType is 'text/html'</span>
<span class="hljs-keyword">const</span> contentLength = response.<span class="hljs-title function_">getHeader</span>(<span class="hljs-string">'Content-Length'</span>);
<span class="hljs-comment">// contentLength is of type number</span>
<span class="hljs-keyword">const</span> setCookie = response.<span class="hljs-title function_">getHeader</span>(<span class="hljs-string">'set-cookie'</span>);
<span class="hljs-comment">// setCookie is of type string[]</span></code> <button class="copy-button">copy</button></pre>
<h4><code>response.getHeaderNames()</code><span><a class="mark" href="#all_http_responsegetheadernames" id="all_http_responsegetheadernames">#</a></span><a aria-hidden="true" class="legacy" id="http_response_getheadernames"></a></h4>
<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.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Foo'</span>, <span class="hljs-string">'bar'</span>);
response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Set-Cookie'</span>, [<span class="hljs-string">'foo=bar'</span>, <span class="hljs-string">'bar=baz'</span>]);

<span class="hljs-keyword">const</span> headerNames = response.<span class="hljs-title function_">getHeaderNames</span>();
<span class="hljs-comment">// headerNames === ['foo', 'set-cookie']</span></code> <button class="copy-button">copy</button></pre>
<h4><code>response.getHeaders()</code><span><a class="mark" href="#all_http_responsegetheaders" id="all_http_responsegetheaders">#</a></span><a aria-hidden="true" class="legacy" id="http_response_getheaders"></a></h4>
<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.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Foo'</span>, <span class="hljs-string">'bar'</span>);
response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Set-Cookie'</span>, [<span class="hljs-string">'foo=bar'</span>, <span class="hljs-string">'bar=baz'</span>]);

<span class="hljs-keyword">const</span> headers = response.<span class="hljs-title function_">getHeaders</span>();
<span class="hljs-comment">// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }</span></code> <button class="copy-button">copy</button></pre>
<h4><code>response.hasHeader(name)</code><span><a class="mark" href="#all_http_responsehasheadername" id="all_http_responsehasheadername">#</a></span><a aria-hidden="true" class="legacy" id="http_response_hasheader_name"></a></h4>
<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"><span class="hljs-keyword">const</span> hasContentType = response.<span class="hljs-title function_">hasHeader</span>(<span class="hljs-string">'content-type'</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>response.headersSent</code><span><a class="mark" href="#all_http_responseheaderssent" id="all_http_responseheaderssent">#</a></span><a aria-hidden="true" class="legacy" id="http_response_headerssent"></a></h4>
<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>
<h4><code>response.removeHeader(name)</code><span><a class="mark" href="#all_http_responseremoveheadername" id="all_http_responseremoveheadername">#</a></span><a aria-hidden="true" class="legacy" id="http_response_removeheader_name"></a></h4>
<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.<span class="hljs-title function_">removeHeader</span>(<span class="hljs-string">'Content-Encoding'</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>response.req</code><span><a class="mark" href="#all_http_responsereq" id="all_http_responsereq">#</a></span><a aria-hidden="true" class="legacy" id="http_response_req"></a></h4>
<div class="api_metadata">
<span>Added in: v15.7.0</span>
</div>
<ul>
<li><a href="#all_http_class-httpincomingmessage" class="type">&#x3C;http.IncomingMessage></a></li>
</ul>
<p>A reference to the original HTTP <code>request</code> object.</p>
<h4><code>response.sendDate</code><span><a class="mark" href="#all_http_responsesenddate" id="all_http_responsesenddate">#</a></span><a aria-hidden="true" class="legacy" id="http_response_senddate"></a></h4>
<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>
<h4><code>response.setHeader(name, value)</code><span><a class="mark" href="#all_http_responsesetheadername-value" id="all_http_responsesetheadername-value">#</a></span><a aria-hidden="true" class="legacy" id="http_response_setheader_name_value"></a></h4>
<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>
<li>Returns: <a href="#all_http_class-httpserverresponse" class="type">&#x3C;http.ServerResponse></a></li>
</ul>
<p>Returns the response object.</p>
<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="#all_http_responsegetheadername"><code>response.getHeader()</code></a> may return
non-string values. However, the non-string values will be converted to strings
for network transmission. The same response object is returned to the caller,
to enable call chaining.</p>
<pre><code class="language-js">response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Content-Type'</span>, <span class="hljs-string">'text/html'</span>);</code> <button class="copy-button">copy</button></pre>
<p>or</p>
<pre><code class="language-js">response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Set-Cookie'</span>, [<span class="hljs-string">'type=ninja'</span>, <span class="hljs-string">'language=javascript'</span>]);</code> <button class="copy-button">copy</button></pre>
<p>Attempting to set a header field name or value that contains invalid characters
will result in a <a href="#all_errors_class-typeerror"><code>TypeError</code></a> being thrown.</p>
<p>When headers have been set with <a href="#all_http_responsesetheadername-value"><code>response.setHeader()</code></a>, they will be merged
with any headers passed to <a href="#all_http_responsewriteheadstatuscode-statusmessage-headers"><code>response.writeHead()</code></a>, with the headers passed
to <a href="#all_http_responsewriteheadstatuscode-statusmessage-headers"><code>response.writeHead()</code></a> given precedence.</p>
<pre><code class="language-js"><span class="hljs-comment">// Returns content-type = text/plain</span>
<span class="hljs-keyword">const</span> server = http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
  res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Content-Type'</span>, <span class="hljs-string">'text/html'</span>);
  res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'X-Foo'</span>, <span class="hljs-string">'bar'</span>);
  res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain'</span> });
  res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'ok'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>If <a href="#all_http_responsewriteheadstatuscode-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="#all_http_responsegetheadername"><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="#all_http_responsesetheadername-value"><code>response.setHeader()</code></a> instead of <a href="#all_http_responsewriteheadstatuscode-statusmessage-headers"><code>response.writeHead()</code></a>.</p>
<h4><code>response.setTimeout(msecs[, callback])</code><span><a class="mark" href="#all_http_responsesettimeoutmsecs-callback" id="all_http_responsesettimeoutmsecs-callback">#</a></span><a aria-hidden="true" class="legacy" id="http_response_settimeout_msecs_callback"></a></h4>
<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="#all_http_class-httpserverresponse" 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>
<h4><code>response.socket</code><span><a class="mark" href="#all_http_responsesocket" id="all_http_responsesocket">#</a></span><a aria-hidden="true" class="legacy" id="http_response_socket"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div>
<ul>
<li><a href="#all_stream_class-streamduplex" 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.</p>

<pre class="with-48-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> http <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;
<span class="hljs-keyword">const</span> server = http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
  <span class="hljs-keyword">const</span> ip = res.<span class="hljs-property">socket</span>.<span class="hljs-property">remoteAddress</span>;
  <span class="hljs-keyword">const</span> port = res.<span class="hljs-property">socket</span>.<span class="hljs-property">remotePort</span>;
  res.<span class="hljs-title function_">end</span>(<span class="hljs-string">`Your IP address is <span class="hljs-subst">${ip}</span> and your source port is <span class="hljs-subst">${port}</span>.`</span>);
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">3000</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);
<span class="hljs-keyword">const</span> server = http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
  <span class="hljs-keyword">const</span> ip = res.<span class="hljs-property">socket</span>.<span class="hljs-property">remoteAddress</span>;
  <span class="hljs-keyword">const</span> port = res.<span class="hljs-property">socket</span>.<span class="hljs-property">remotePort</span>;
  res.<span class="hljs-title function_">end</span>(<span class="hljs-string">`Your IP address is <span class="hljs-subst">${ip}</span> and your source port is <span class="hljs-subst">${port}</span>.`</span>);
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">3000</span>);</code><button class="copy-button">copy</button></pre>
<p>This property is guaranteed to be an instance of the <a href="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a> class,
a subclass of <a href="#all_stream_class-streamduplex" class="type">&#x3C;stream.Duplex></a>, unless the user specified a socket
type other than <a href="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a>.</p>
<h4><code>response.statusCode</code><span><a class="mark" href="#all_http_responsestatuscode" id="all_http_responsestatuscode">#</a></span><a aria-hidden="true" class="legacy" id="http_response_statuscode"></a></h4>
<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="#all_http_responsewriteheadstatuscode-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.<span class="hljs-property">statusCode</span> = <span class="hljs-number">404</span>;</code> <button class="copy-button">copy</button></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="#all_http_responsestatusmessage" id="all_http_responsestatusmessage">#</a></span><a aria-hidden="true" class="legacy" id="http_response_statusmessage"></a></h4>
<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="#all_http_responsewriteheadstatuscode-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.<span class="hljs-property">statusMessage</span> = <span class="hljs-string">'Not found'</span>;</code> <button class="copy-button">copy</button></pre>
<p>After response header was sent to the client, this property indicates the
status message which was sent out.</p>
<h4><code>response.strictContentLength</code><span><a class="mark" href="#all_http_responsestrictcontentlength" id="all_http_responsestrictcontentlength">#</a></span><a aria-hidden="true" class="legacy" id="http_response_strictcontentlength"></a></h4>
<div class="api_metadata">
<span>Added in: v18.10.0, v16.18.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> <strong>Default:</strong> <code>false</code></li>
</ul>
<p>If set to <code>true</code>, Node.js will check whether the <code>Content-Length</code>
header value and the size of the body, in bytes, are equal.
Mismatching the <code>Content-Length</code> header value will result
in an <code>Error</code> being thrown, identified by <code>code:</code> <a href="#all_errors_err_http_content_length_mismatch"><code>'ERR_HTTP_CONTENT_LENGTH_MISMATCH'</code></a>.</p>
<h4><code>response.uncork()</code><span><a class="mark" href="#all_http_responseuncork" id="all_http_responseuncork">#</a></span><a aria-hidden="true" class="legacy" id="http_response_uncork"></a></h4>
<div class="api_metadata">
<span>Added in: v13.2.0, v12.16.0</span>
</div>
<p>See <a href="#all_stream_writableuncork"><code>writable.uncork()</code></a>.</p>
<h4><code>response.writableEnded</code><span><a class="mark" href="#all_http_responsewritableended" id="all_http_responsewritableended">#</a></span><a aria-hidden="true" class="legacy" id="http_response_writableended"></a></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="#all_http_responseenddata-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="#all_http_responsewritablefinished"><code>response.writableFinished</code></a> instead.</p>
<h4><code>response.writableFinished</code><span><a class="mark" href="#all_http_responsewritablefinished" id="all_http_responsewritablefinished">#</a></span><a aria-hidden="true" class="legacy" id="http_response_writablefinished"></a></h4>
<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="#all_http_event-finish"><code>'finish'</code></a> event is emitted.</p>
<h4><code>response.write(chunk[, encoding][, callback])</code><span><a class="mark" href="#all_http_responsewritechunk-encoding-callback" id="all_http_responsewritechunk-encoding-callback">#</a></span><a aria-hidden="true" class="legacy" id="http_response_write_chunk_encoding_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>The <code>chunk</code> parameter can now be a <code>Uint8Array</code>.</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>chunk</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#all_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> <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="#all_http_responsewriteheadstatuscode-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>If <code>rejectNonStandardBodyWrites</code> is set to true in <code>createServer</code>
then writing to the body is not allowed when the request method or response
status do not support content. If an attempt is made to write to the body for a
HEAD request or as part of a <code>204</code> or <code>304</code>response, a synchronous <code>Error</code>
with the code <code>ERR_HTTP_BODY_NOT_ALLOWED</code> is thrown.</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="#all_http_responsewritechunk-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="#all_http_responsewritechunk-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="#all_http_responsewritecontinue" id="all_http_responsewritecontinue">#</a></span><a aria-hidden="true" class="legacy" id="http_response_writecontinue"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div>
<p>Sends an HTTP/1.1 100 Continue message to the client, indicating that
the request body should be sent. See the <a href="#all_http_event-checkcontinue"><code>'checkContinue'</code></a> event on
<code>Server</code>.</p>
<h4><code>response.writeEarlyHints(hints[, callback])</code><span><a class="mark" href="#all_http_responsewriteearlyhintshints-callback" id="all_http_responsewriteearlyhintshints-callback">#</a></span><a aria-hidden="true" class="legacy" id="http_response_writeearlyhints_hints_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.11.0</td>
<td><p>Allow passing hints as an object.</p></td></tr>
<tr><td>v18.11.0</td>
<td><p><span>Added in: v18.11.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>hints</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>Sends an HTTP/1.1 103 Early Hints message to the client with a Link header,
indicating that the user agent can preload/preconnect the linked resources.
The <code>hints</code> is an object containing the values of headers to be sent with
early hints message. The optional <code>callback</code> argument will be called when
the response message has been written.</p>
<p><strong>Example</strong></p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> earlyHintsLink = <span class="hljs-string">'&#x3C;/styles.css>; rel=preload; as=style'</span>;
response.<span class="hljs-title function_">writeEarlyHints</span>({
  <span class="hljs-string">'link'</span>: earlyHintsLink,
});

<span class="hljs-keyword">const</span> earlyHintsLinks = [
  <span class="hljs-string">'&#x3C;/styles.css>; rel=preload; as=style'</span>,
  <span class="hljs-string">'&#x3C;/scripts.js>; rel=preload; as=script'</span>,
];
response.<span class="hljs-title function_">writeEarlyHints</span>({
  <span class="hljs-string">'link'</span>: earlyHintsLinks,
  <span class="hljs-string">'x-trace-id'</span>: <span class="hljs-string">'id for diagnostics'</span>,
});

<span class="hljs-keyword">const</span> <span class="hljs-title function_">earlyHintsCallback</span> = (<span class="hljs-params"></span>) => <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'early hints message sent'</span>);
response.<span class="hljs-title function_">writeEarlyHints</span>({
  <span class="hljs-string">'link'</span>: earlyHintsLinks,
}, earlyHintsCallback);</code> <button class="copy-button">copy</button></pre>
<h4><code>response.writeHead(statusCode[, statusMessage][, headers])</code><span><a class="mark" href="#all_http_responsewriteheadstatuscode-statusmessage-headers" id="all_http_responsewriteheadstatuscode-statusmessage-headers">#</a></span><a aria-hidden="true" class="legacy" id="http_response_writehead_statuscode_statusmessage_headers"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.14.0</td>
<td><p>Allow passing headers as an array.</p></td></tr>
<tr><td>v11.10.0, v10.17.0</td>
<td><p>Return <code>this</code> from <code>writeHead()</code> to allow chaining with <code>end()</code>.</p></td></tr>
<tr><td>v5.11.0, v4.4.5</td>
<td><p>A <code>RangeError</code> is thrown if <code>statusCode</code> is not a number in the range <code>[100, 999]</code>.</p></td></tr>
<tr><td>v0.1.30</td>
<td><p><span>Added in: v0.1.30</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>statusCode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type">&#x3C;Array></a></li>
<li>Returns: <a href="#all_http_class-httpserverresponse" 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><code>headers</code> may be an <code>Array</code> where 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. The array is in the same
format as <code>request.rawHeaders</code>.</p>
<p>Returns a reference to the <code>ServerResponse</code>, so that calls can be chained.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> body = <span class="hljs-string">'hello world'</span>;
response
  .<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, {
    <span class="hljs-string">'Content-Length'</span>: <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">byteLength</span>(body),
    <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain'</span>,
  })
  .<span class="hljs-title function_">end</span>(body);</code> <button class="copy-button">copy</button></pre>
<p>This method must only be called once on a message and it must
be called before <a href="#all_http_responseenddata-encoding-callback"><code>response.end()</code></a> is called.</p>
<p>If <a href="#all_http_responsewritechunk-encoding-callback"><code>response.write()</code></a> or <a href="#all_http_responseenddata-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="#all_http_responsesetheadername-value"><code>response.setHeader()</code></a>, they will be merged
with any headers passed to <a href="#all_http_responsewriteheadstatuscode-statusmessage-headers"><code>response.writeHead()</code></a>, with the headers passed
to <a href="#all_http_responsewriteheadstatuscode-statusmessage-headers"><code>response.writeHead()</code></a> given precedence.</p>
<p>If this method is called and <a href="#all_http_responsesetheadername-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="#all_http_responsegetheadername"><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="#all_http_responsesetheadername-value"><code>response.setHeader()</code></a> instead.</p>
<pre><code class="language-js"><span class="hljs-comment">// Returns content-type = text/plain</span>
<span class="hljs-keyword">const</span> server = http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
  res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Content-Type'</span>, <span class="hljs-string">'text/html'</span>);
  res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'X-Foo'</span>, <span class="hljs-string">'bar'</span>);
  res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain'</span> });
  res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'ok'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p><code>Content-Length</code> is read in bytes, not characters. Use
<a href="#all_buffer_static-method-bufferbytelengthstring-encoding"><code>Buffer.byteLength()</code></a> to determine the length of the body in bytes. Node.js
will 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 [<code>Error</code>][] being thrown.</p>
<h4><code>response.writeProcessing()</code><span><a class="mark" href="#all_http_responsewriteprocessing" id="all_http_responsewriteprocessing">#</a></span><a aria-hidden="true" class="legacy" id="http_response_writeprocessing"></a></h4>
<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>
</section><section><h3>Class: <code>http.IncomingMessage</code><span><a class="mark" href="#all_http_class-httpincomingmessage" id="all_http_class-httpincomingmessage">#</a></span><a aria-hidden="true" class="legacy" id="http_class_http_incomingmessage"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.5.0</td>
<td><p>The <code>destroyed</code> value returns <code>true</code> after the incoming data is consumed.</p></td></tr>
<tr><td>v13.1.0, 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="#all_stream_class-streamreadable" class="type">&#x3C;stream.Readable></a></li>
</ul>
<p>An <code>IncomingMessage</code> object is created by <a href="#all_http_class-httpserver"><code>http.Server</code></a> or
<a href="#all_http_class-httpclientrequest"><code>http.ClientRequest</code></a> and passed as the first argument to the <a href="#all_http_event-request"><code>'request'</code></a>
and <a href="#all_http_event-response"><code>'response'</code></a> event respectively. It may be used to access response
status, headers, and data.</p>
<p>Different from its <code>socket</code> value which is a subclass of <a href="#all_stream_class-streamduplex" class="type">&#x3C;stream.Duplex></a>, the
<code>IncomingMessage</code> itself extends <a href="#all_stream_class-streamreadable" class="type">&#x3C;stream.Readable></a> and is created separately to
parse and emit the incoming HTTP headers and payload, as the underlying socket
may be reused multiple times in case of keep-alive.</p>
<h4>Event: <code>'aborted'</code><span><a class="mark" href="#all_http_event-aborted" id="all_http_event-aborted">#</a></span><a aria-hidden="true" class="legacy" id="http_event_aborted"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.8</span><span>Deprecated since: v17.0.0, v16.12.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated. Listen for <code>'close'</code> event instead.</div><p></p>
<p>Emitted when the request has been aborted.</p>
<h4>Event: <code>'close'</code><span><a class="mark" href="#all_http_event-close_3" id="all_http_event-close_3">#</a></span><a aria-hidden="true" class="legacy" id="http_event_close_3"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0</td>
<td><p>The close event is now emitted when the request has been completed and not when the underlying socket is closed.</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>
<p>Emitted when the request has been completed.</p>
<h4><code>message.aborted</code><span><a class="mark" href="#all_http_messageaborted" id="all_http_messageaborted">#</a></span><a aria-hidden="true" class="legacy" id="http_message_aborted"></a></h4>
<div class="api_metadata">
<span>Added in: v10.1.0</span><span>Deprecated since: v17.0.0, v16.12.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated. Check <code>message.destroyed</code> from <a href="#all_stream_class-streamreadable" class="type">&#x3C;stream.Readable></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>message.aborted</code> property will be <code>true</code> if the request has
been aborted.</p>
<h4><code>message.complete</code><span><a class="mark" href="#all_http_messagecomplete" id="all_http_messagecomplete">#</a></span><a aria-hidden="true" class="legacy" id="http_message_complete"></a></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/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"><span class="hljs-keyword">const</span> req = http.<span class="hljs-title function_">request</span>({
  <span class="hljs-attr">host</span>: <span class="hljs-string">'127.0.0.1'</span>,
  <span class="hljs-attr">port</span>: <span class="hljs-number">8080</span>,
  <span class="hljs-attr">method</span>: <span class="hljs-string">'POST'</span>,
}, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
  res.<span class="hljs-title function_">resume</span>();
  res.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> {
    <span class="hljs-keyword">if</span> (!res.<span class="hljs-property">complete</span>)
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(
        <span class="hljs-string">'The connection was terminated while the message was still being sent'</span>);
  });
});</code> <button class="copy-button">copy</button></pre>
<h4><code>message.connection</code><span><a class="mark" href="#all_http_messageconnection" id="all_http_messageconnection">#</a></span><a aria-hidden="true" class="legacy" id="http_message_connection"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</span><span>Deprecated since: v16.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated. Use <a href="#all_http_messagesocket"><code>message.socket</code></a>.</div><p></p>
<p>Alias for <a href="#all_http_messagesocket"><code>message.socket</code></a>.</p>
<h4><code>message.destroy([error])</code><span><a class="mark" href="#all_http_messagedestroyerror" id="all_http_messagedestroyerror">#</a></span><a aria-hidden="true" class="legacy" id="http_message_destroy_error"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.5.0, v12.19.0</td>
<td><p>The function returns <code>this</code> for consistency with other Readable streams.</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>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>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>
<h4><code>message.headers</code><span><a class="mark" href="#all_http_messageheaders" id="all_http_messageheaders">#</a></span><a aria-hidden="true" class="legacy" id="http_message_headers"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.5.0, v18.14.0</td>
<td><p>The <code>joinDuplicateHeaders</code> option in the <code>http.request()</code> and <code>http.createServer()</code> functions ensures that duplicate headers are not discarded, but rather combined using a comma separator, in accordance with RFC 9110 Section 5.3.</p></td></tr>
<tr><td>v15.1.0</td>
<td><p><code>message.headers</code> is now lazily computed using an accessor property on the prototype and is no longer enumerable.</p></td></tr>
<tr><td>v0.1.5</td>
<td><p><span>Added in: v0.1.5</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 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"><span class="hljs-comment">// Prints something like:</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// { 'user-agent': 'curl/7.22.0',</span>
<span class="hljs-comment">//   host: '127.0.0.1:8000',</span>
<span class="hljs-comment">//   accept: '*/*' }</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(request.<span class="hljs-property">headers</span>);</code> <button class="copy-button">copy</button></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.
To allow duplicate values of the headers listed above to be joined,
use the option <code>joinDuplicateHeaders</code> in <a href="#all_http_httprequestoptions-callback"><code>http.request()</code></a>
and <a href="#all_http_httpcreateserveroptions-requestlistener"><code>http.createServer()</code></a>. See RFC 9110 Section 5.3 for more
information.</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 <code>; </code>.</li>
<li>For all other headers, the values are joined together with <code>, </code>.</li>
</ul>
<h4><code>message.headersDistinct</code><span><a class="mark" href="#all_http_messageheadersdistinct" id="all_http_messageheadersdistinct">#</a></span><a aria-hidden="true" class="legacy" id="http_message_headersdistinct"></a></h4>
<div class="api_metadata">
<span>Added in: v18.3.0, v16.17.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>Similar to <a href="#all_http_messageheaders"><code>message.headers</code></a>, but there is no join logic and the values are
always arrays of strings, even for headers received just once.</p>
<pre><code class="language-js"><span class="hljs-comment">// Prints something like:</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// { 'user-agent': ['curl/7.22.0'],</span>
<span class="hljs-comment">//   host: ['127.0.0.1:8000'],</span>
<span class="hljs-comment">//   accept: ['*/*'] }</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(request.<span class="hljs-property">headersDistinct</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>message.httpVersion</code><span><a class="mark" href="#all_http_messagehttpversion" id="all_http_messagehttpversion">#</a></span><a aria-hidden="true" class="legacy" id="http_message_httpversion"></a></h4>
<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>
<h4><code>message.method</code><span><a class="mark" href="#all_http_messagemethod" id="all_http_messagemethod">#</a></span><a aria-hidden="true" class="legacy" id="http_message_method"></a></h4>
<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="#all_http_class-httpserver"><code>http.Server</code></a>.</strong></p>
<p>The request method as a string. Read only. Examples: <code>'GET'</code>, <code>'DELETE'</code>.</p>
<h4><code>message.rawHeaders</code><span><a class="mark" href="#all_http_messagerawheaders" id="all_http_messagerawheaders">#</a></span><a aria-hidden="true" class="legacy" id="http_message_rawheaders"></a></h4>
<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"><span class="hljs-comment">// Prints something like:</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// [ 'user-agent',</span>
<span class="hljs-comment">//   'this is invalid because there can be only one',</span>
<span class="hljs-comment">//   'User-Agent',</span>
<span class="hljs-comment">//   'curl/7.22.0',</span>
<span class="hljs-comment">//   'Host',</span>
<span class="hljs-comment">//   '127.0.0.1:8000',</span>
<span class="hljs-comment">//   'ACCEPT',</span>
<span class="hljs-comment">//   '*/*' ]</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(request.<span class="hljs-property">rawHeaders</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>message.rawTrailers</code><span><a class="mark" href="#all_http_messagerawtrailers" id="all_http_messagerawtrailers">#</a></span><a aria-hidden="true" class="legacy" id="http_message_rawtrailers"></a></h4>
<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>
<h4><code>message.setTimeout(msecs[, callback])</code><span><a class="mark" href="#all_http_messagesettimeoutmsecs-callback" id="all_http_messagesettimeoutmsecs-callback">#</a></span><a aria-hidden="true" class="legacy" id="http_message_settimeout_msecs_callback"></a></h4>
<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="#all_http_class-httpincomingmessage" class="type">&#x3C;http.IncomingMessage></a></li>
</ul>
<p>Calls <code>message.socket.setTimeout(msecs, callback)</code>.</p>
<h4><code>message.socket</code><span><a class="mark" href="#all_http_messagesocket" id="all_http_messagesocket">#</a></span><a aria-hidden="true" class="legacy" id="http_message_socket"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div>
<ul>
<li><a href="#all_stream_class-streamduplex" class="type">&#x3C;stream.Duplex></a></li>
</ul>
<p>The <a href="#all_net_class-netsocket"><code>net.Socket</code></a> object associated with the connection.</p>
<p>With HTTPS support, use <a href="#all_tls_tlssocketgetpeercertificatedetailed"><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="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a> class,
a subclass of <a href="#all_stream_class-streamduplex" class="type">&#x3C;stream.Duplex></a>, unless the user specified a socket
type other than <a href="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a> or internally nulled.</p>
<h4><code>message.statusCode</code><span><a class="mark" href="#all_http_messagestatuscode" id="all_http_messagestatuscode">#</a></span><a aria-hidden="true" class="legacy" id="http_message_statuscode"></a></h4>
<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="#all_http_class-httpclientrequest"><code>http.ClientRequest</code></a>.</strong></p>
<p>The 3-digit HTTP response status code. E.G. <code>404</code>.</p>
<h4><code>message.statusMessage</code><span><a class="mark" href="#all_http_messagestatusmessage" id="all_http_messagestatusmessage">#</a></span><a aria-hidden="true" class="legacy" id="http_message_statusmessage"></a></h4>
<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="#all_http_class-httpclientrequest"><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>
<h4><code>message.trailers</code><span><a class="mark" href="#all_http_messagetrailers" id="all_http_messagetrailers">#</a></span><a aria-hidden="true" class="legacy" id="http_message_trailers"></a></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>The request/response trailers object. Only populated at the <code>'end'</code> event.</p>
<h4><code>message.trailersDistinct</code><span><a class="mark" href="#all_http_messagetrailersdistinct" id="all_http_messagetrailersdistinct">#</a></span><a aria-hidden="true" class="legacy" id="http_message_trailersdistinct"></a></h4>
<div class="api_metadata">
<span>Added in: v18.3.0, v16.17.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>Similar to <a href="#all_http_messagetrailers"><code>message.trailers</code></a>, but there is no join logic and the values are
always arrays of strings, even for headers received just once.
Only populated at the <code>'end'</code> event.</p>
<h4><code>message.url</code><span><a class="mark" href="#all_http_messageurl" id="all_http_messageurl">#</a></span><a aria-hidden="true" class="legacy" id="http_message_url"></a></h4>
<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="#all_http_class-httpserver"><code>http.Server</code></a>.</strong></p>
<p>Request URL string. This contains only the URL that is present in the actual
HTTP request. Take the following request:</p>
<pre><code class="language-http"><span class="hljs-keyword">GET</span> <span class="hljs-string">/status?name=ryan</span> <span class="hljs-meta">HTTP/1.1</span>
<span class="hljs-attribute">Accept</span><span class="hljs-punctuation">: </span>text/plain</code> <button class="copy-button">copy</button></pre>
<p>To parse the URL into its parts:</p>
<pre><code class="language-js"><span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">`http://<span class="hljs-subst">${process.env.HOST ?? <span class="hljs-string">'localhost'</span>}</span><span class="hljs-subst">${request.url}</span>`</span>);</code> <button class="copy-button">copy</button></pre>
<p>When <code>request.url</code> is <code>'/status?name=ryan'</code> and <code>process.env.HOST</code> is undefined:</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node</span>
<span class="hljs-meta prompt_">> </span><span class="language-bash">new URL(`http://<span class="hljs-variable">${process.env.HOST ?? 'localhost'}</span><span class="hljs-variable">${request.url}</span>`);</span>
URL {
  href: 'http://localhost/status?name=ryan',
  origin: 'http://localhost',
  protocol: 'http:',
  username: '',
  password: '',
  host: 'localhost',
  hostname: 'localhost',
  port: '',
  pathname: '/status',
  search: '?name=ryan',
  searchParams: URLSearchParams { 'name' => 'ryan' },
  hash: ''
}</code> <button class="copy-button">copy</button></pre>
<p>Ensure that you set <code>process.env.HOST</code> to the server's host name, or consider
replacing this part entirely. If using <code>req.headers.host</code>, ensure proper
validation is used, as clients may specify a custom <code>Host</code> header.</p>
</section><section><h3>Class: <code>http.OutgoingMessage</code><span><a class="mark" href="#all_http_class-httpoutgoingmessage" id="all_http_class-httpoutgoingmessage">#</a></span><a aria-hidden="true" class="legacy" id="http_class_http_outgoingmessage"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.17</span>
</div>
<ul>
<li>Extends: <a href="#all_stream_stream" class="type">&#x3C;Stream></a></li>
</ul>
<p>This class serves as the parent class of <a href="#all_http_class-httpclientrequest"><code>http.ClientRequest</code></a>
and <a href="#all_http_class-httpserverresponse"><code>http.ServerResponse</code></a>. It is an abstract outgoing message from
the perspective of the participants of an HTTP transaction.</p>
<h4>Event: <code>'drain'</code><span><a class="mark" href="#all_http_event-drain" id="all_http_event-drain">#</a></span><a aria-hidden="true" class="legacy" id="http_event_drain"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.6</span>
</div>
<p>Emitted when the buffer of the message is free again.</p>
<h4>Event: <code>'finish'</code><span><a class="mark" href="#all_http_event-finish_2" id="all_http_event-finish_2">#</a></span><a aria-hidden="true" class="legacy" id="http_event_finish_2"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.17</span>
</div>
<p>Emitted when the transmission is finished successfully.</p>
<h4>Event: <code>'prefinish'</code><span><a class="mark" href="#all_http_event-prefinish" id="all_http_event-prefinish">#</a></span><a aria-hidden="true" class="legacy" id="http_event_prefinish"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.6</span>
</div>
<p>Emitted after <code>outgoingMessage.end()</code> is called.
When the event is emitted, all data has been processed but not necessarily
completely flushed.</p>
<h4><code>outgoingMessage.addTrailers(headers)</code><span><a class="mark" href="#all_http_outgoingmessageaddtrailersheaders" id="all_http_outgoingmessageaddtrailersheaders">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_addtrailers_headers"></a></h4>
<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>Adds HTTP trailers (headers but at the end of the message) to the message.</p>
<p>Trailers will <strong>only</strong> be emitted if the message is chunked encoded. If not,
the trailers will be silently discarded.</p>
<p>HTTP requires the <code>Trailer</code> header to be sent to emit trailers,
with a list of header field names in its value, e.g.</p>
<pre><code class="language-js">message.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain'</span>,
                         <span class="hljs-string">'Trailer'</span>: <span class="hljs-string">'Content-MD5'</span> });
message.<span class="hljs-title function_">write</span>(fileData);
message.<span class="hljs-title function_">addTrailers</span>({ <span class="hljs-string">'Content-MD5'</span>: <span class="hljs-string">'7895bf4b8828b55ceaf47747b4bca667'</span> });
message.<span class="hljs-title function_">end</span>();</code> <button class="copy-button">copy</button></pre>
<p>Attempting to set a header field name or value that contains invalid characters
will result in a <code>TypeError</code> being thrown.</p>
<h4><code>outgoingMessage.appendHeader(name, value)</code><span><a class="mark" href="#all_http_outgoingmessageappendheadername-value" id="all_http_outgoingmessageappendheadername-value">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_appendheader_name_value"></a></h4>
<div class="api_metadata">
<span>Added in: v18.3.0, v16.17.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> Header name</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> Header value</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>Append a single header value to the header object.</p>
<p>If the value is an array, this is equivalent to calling this method multiple
times.</p>
<p>If there were no previous values for the header, this is equivalent to calling
<a href="#all_http_outgoingmessagesetheadername-value"><code>outgoingMessage.setHeader(name, value)</code></a>.</p>
<p>Depending of the value of <code>options.uniqueHeaders</code> when the client request or the
server were created, this will end up in the header being sent multiple times or
a single time with values joined using <code>; </code>.</p>
<h4><code>outgoingMessage.connection</code><span><a class="mark" href="#all_http_outgoingmessageconnection" id="all_http_outgoingmessageconnection">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_connection"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.0</span><span>Deprecated since: v15.12.0, v14.17.1</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_http_outgoingmessagesocket"><code>outgoingMessage.socket</code></a> instead.</div><p></p>
<p>Alias of <a href="#all_http_outgoingmessagesocket"><code>outgoingMessage.socket</code></a>.</p>
<h4><code>outgoingMessage.cork()</code><span><a class="mark" href="#all_http_outgoingmessagecork" id="all_http_outgoingmessagecork">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_cork"></a></h4>
<div class="api_metadata">
<span>Added in: v13.2.0, v12.16.0</span>
</div>
<p>See <a href="#all_stream_writablecork"><code>writable.cork()</code></a>.</p>
<h4><code>outgoingMessage.destroy([error])</code><span><a class="mark" href="#all_http_outgoingmessagedestroyerror" id="all_http_outgoingmessagedestroyerror">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_destroy_error"></a></h4>
<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> 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>Destroys the message. Once a socket is associated with the message
and is connected, that socket will be destroyed as well.</p>
<h4><code>outgoingMessage.end(chunk[, encoding][, callback])</code><span><a class="mark" href="#all_http_outgoingmessageendchunk-encoding-callback" id="all_http_outgoingmessageendchunk-encoding-callback">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_end_chunk_encoding_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>The <code>chunk</code> parameter can now be a <code>Uint8Array</code>.</p></td></tr>
<tr><td>v0.11.6</td>
<td><p>add <code>callback</code> argument.</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>chunk</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#all_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> Optional, <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</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 the outgoing message. If any parts of the body are unsent, it will
flush them to the underlying system. If the message is chunked, it will
send the terminating chunk <code>0\r\n\r\n</code>, and send the trailers (if any).</p>
<p>If <code>chunk</code> is specified, it is equivalent to calling
<code>outgoingMessage.write(chunk, encoding)</code>, followed by
<code>outgoingMessage.end(callback)</code>.</p>
<p>If <code>callback</code> is provided, it will be called when the message is finished
(equivalent to a listener of the <code>'finish'</code> event).</p>
<h4><code>outgoingMessage.flushHeaders()</code><span><a class="mark" href="#all_http_outgoingmessageflushheaders" id="all_http_outgoingmessageflushheaders">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_flushheaders"></a></h4>
<div class="api_metadata">
<span>Added in: v1.6.0</span>
</div>
<p>Flushes the message headers.</p>
<p>For efficiency reason, Node.js normally buffers the message headers
until <code>outgoingMessage.end()</code> is called or the first chunk of message data
is written. It then tries to pack the headers and data into a single TCP
packet.</p>
<p>It is usually desired (it saves a TCP round-trip), but not when the first
data is not sent until possibly much later. <code>outgoingMessage.flushHeaders()</code>
bypasses the optimization and kickstarts the message.</p>
<h4><code>outgoingMessage.getHeader(name)</code><span><a class="mark" href="#all_http_outgoingmessagegetheadername" id="all_http_outgoingmessagegetheadername">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_getheader_name"></a></h4>
<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> Name of header</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>Gets the value of the HTTP header with the given name. If that header is not
set, the returned value will be <code>undefined</code>.</p>
<h4><code>outgoingMessage.getHeaderNames()</code><span><a class="mark" href="#all_http_outgoingmessagegetheadernames" id="all_http_outgoingmessagegetheadernames">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_getheadernames"></a></h4>
<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 names are lowercase.</p>
<h4><code>outgoingMessage.getHeaders()</code><span><a class="mark" href="#all_http_outgoingmessagegetheaders" id="all_http_outgoingmessagegetheaders">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_getheaders"></a></h4>
<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>outgoingMessage.getHeaders()</code> method does
not 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 will not work.</p>
<pre><code class="language-js">outgoingMessage.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Foo'</span>, <span class="hljs-string">'bar'</span>);
outgoingMessage.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Set-Cookie'</span>, [<span class="hljs-string">'foo=bar'</span>, <span class="hljs-string">'bar=baz'</span>]);

<span class="hljs-keyword">const</span> headers = outgoingMessage.<span class="hljs-title function_">getHeaders</span>();
<span class="hljs-comment">// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }</span></code> <button class="copy-button">copy</button></pre>
<h4><code>outgoingMessage.hasHeader(name)</code><span><a class="mark" href="#all_http_outgoingmessagehasheadername" id="all_http_outgoingmessagehasheadername">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_hasheader_name"></a></h4>
<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 is case-insensitive.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> hasContentType = outgoingMessage.<span class="hljs-title function_">hasHeader</span>(<span class="hljs-string">'content-type'</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>outgoingMessage.headersSent</code><span><a class="mark" href="#all_http_outgoingmessageheaderssent" id="all_http_outgoingmessageheaderssent">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_headerssent"></a></h4>
<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>Read-only. <code>true</code> if the headers were sent, otherwise <code>false</code>.</p>
<h4><code>outgoingMessage.pipe()</code><span><a class="mark" href="#all_http_outgoingmessagepipe" id="all_http_outgoingmessagepipe">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_pipe"></a></h4>
<div class="api_metadata">
<span>Added in: v9.0.0</span>
</div>
<p>Overrides the <code>stream.pipe()</code> method inherited from the legacy <code>Stream</code> class
which is the parent class of <code>http.OutgoingMessage</code>.</p>
<p>Calling this method will throw an <code>Error</code> because <code>outgoingMessage</code> is a
write-only stream.</p>
<h4><code>outgoingMessage.removeHeader(name)</code><span><a class="mark" href="#all_http_outgoingmessageremoveheadername" id="all_http_outgoingmessageremoveheadername">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_removeheader_name"></a></h4>
<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> Header name</li>
</ul>
<p>Removes a header that is queued for implicit sending.</p>
<pre><code class="language-js">outgoingMessage.<span class="hljs-title function_">removeHeader</span>(<span class="hljs-string">'Content-Encoding'</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>outgoingMessage.setHeader(name, value)</code><span><a class="mark" href="#all_http_outgoingmessagesetheadername-value" id="all_http_outgoingmessagesetheadername-value">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_setheader_name_value"></a></h4>
<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> Header name</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> Header value</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>Sets a single header value. If the header already exists in the to-be-sent
headers, its value will be replaced. Use an array of strings to send multiple
headers with the same name.</p>
<h4><code>outgoingMessage.setHeaders(headers)</code><span><a class="mark" href="#all_http_outgoingmessagesetheadersheaders" id="all_http_outgoingmessagesetheadersheaders">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_setheaders_headers"></a></h4>
<div class="api_metadata">
<span>Added in: v19.6.0, v18.15.0</span>
</div>
<ul>
<li><code>headers</code> <a href="https://developer.mozilla.org/en-US/docs/Web/API/Headers" class="type">&#x3C;Headers></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map" class="type">&#x3C;Map></a></li>
<li>Returns: <a href="#all_http_class-httpserverresponse" class="type">&#x3C;http.ServerResponse></a></li>
</ul>
<p>Returns the response object.</p>
<p>Sets multiple header values for implicit headers.
<code>headers</code> must be an instance of <a href="#all_globals_class-headers"><code>Headers</code></a> or <code>Map</code>,
if a header already exists in the to-be-sent headers,
its value will be replaced.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> headers = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Headers</span>({ <span class="hljs-attr">foo</span>: <span class="hljs-string">'bar'</span> });
response.<span class="hljs-title function_">setHeaders</span>(headers);</code> <button class="copy-button">copy</button></pre>
<p>or</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> headers = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Map</span>([[<span class="hljs-string">'foo'</span>, <span class="hljs-string">'bar'</span>]]);
res.<span class="hljs-title function_">setHeaders</span>(headers);</code> <button class="copy-button">copy</button></pre>
<p>When headers have been set with <a href="#all_http_outgoingmessagesetheadersheaders"><code>outgoingMessage.setHeaders()</code></a>,
they will be merged with any headers passed to <a href="#all_http_responsewriteheadstatuscode-statusmessage-headers"><code>response.writeHead()</code></a>,
with the headers passed to <a href="#all_http_responsewriteheadstatuscode-statusmessage-headers"><code>response.writeHead()</code></a> given precedence.</p>
<pre><code class="language-js"><span class="hljs-comment">// Returns content-type = text/plain</span>
<span class="hljs-keyword">const</span> server = http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
  <span class="hljs-keyword">const</span> headers = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Headers</span>({ <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/html'</span> });
  res.<span class="hljs-title function_">setHeaders</span>(headers);
  res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain'</span> });
  res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'ok'</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4><code>outgoingMessage.setTimeout(msesc[, callback])</code><span><a class="mark" href="#all_http_outgoingmessagesettimeoutmsesc-callback" id="all_http_outgoingmessagesettimeoutmsesc-callback">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_settimeout_msesc_callback"></a></h4>
<div class="api_metadata">
<span>Added in: v0.9.12</span>
</div>
<ul>
<li><code>msesc</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> Optional function to be called when a timeout
occurs. Same as binding to the <code>timeout</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>Once a socket is associated with the message and is connected,
<a href="#all_net_socketsettimeouttimeout-callback"><code>socket.setTimeout()</code></a> will be called with <code>msecs</code> as the first parameter.</p>
<h4><code>outgoingMessage.socket</code><span><a class="mark" href="#all_http_outgoingmessagesocket" id="all_http_outgoingmessagesocket">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_socket"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div>
<ul>
<li><a href="#all_stream_class-streamduplex" class="type">&#x3C;stream.Duplex></a></li>
</ul>
<p>Reference to the underlying socket. Usually, users will not want to access
this property.</p>
<p>After calling <code>outgoingMessage.end()</code>, this property will be nulled.</p>
<h4><code>outgoingMessage.uncork()</code><span><a class="mark" href="#all_http_outgoingmessageuncork" id="all_http_outgoingmessageuncork">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_uncork"></a></h4>
<div class="api_metadata">
<span>Added in: v13.2.0, v12.16.0</span>
</div>
<p>See <a href="#all_stream_writableuncork"><code>writable.uncork()</code></a></p>
<h4><code>outgoingMessage.writableCorked</code><span><a class="mark" href="#all_http_outgoingmessagewritablecorked" id="all_http_outgoingmessagewritablecorked">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_writablecorked"></a></h4>
<div class="api_metadata">
<span>Added in: v13.2.0, 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;number></a></li>
</ul>
<p>The number of times <code>outgoingMessage.cork()</code> has been called.</p>
<h4><code>outgoingMessage.writableEnded</code><span><a class="mark" href="#all_http_outgoingmessagewritableended" id="all_http_outgoingmessagewritableended">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_writableended"></a></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> if <code>outgoingMessage.end()</code> has been called. This property does
not indicate whether the data has been flushed. For that purpose, use
<code>message.writableFinished</code> instead.</p>
<h4><code>outgoingMessage.writableFinished</code><span><a class="mark" href="#all_http_outgoingmessagewritablefinished" id="all_http_outgoingmessagewritablefinished">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_writablefinished"></a></h4>
<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.</p>
<h4><code>outgoingMessage.writableHighWaterMark</code><span><a class="mark" href="#all_http_outgoingmessagewritablehighwatermark" id="all_http_outgoingmessagewritablehighwatermark">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_writablehighwatermark"></a></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#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>The <code>highWaterMark</code> of the underlying socket if assigned. Otherwise, the default
buffer level when <a href="#all_stream_writablewritechunk-encoding-callback"><code>writable.write()</code></a> starts returning false (<code>16384</code>).</p>
<h4><code>outgoingMessage.writableLength</code><span><a class="mark" href="#all_http_outgoingmessagewritablelength" id="all_http_outgoingmessagewritablelength">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_writablelength"></a></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#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>The number of buffered bytes.</p>
<h4><code>outgoingMessage.writableObjectMode</code><span><a class="mark" href="#all_http_outgoingmessagewritableobjectmode" id="all_http_outgoingmessagewritableobjectmode">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_writableobjectmode"></a></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>Always <code>false</code>.</p>
<h4><code>outgoingMessage.write(chunk[, encoding][, callback])</code><span><a class="mark" href="#all_http_outgoingmessagewritechunk-encoding-callback" id="all_http_outgoingmessagewritechunk-encoding-callback">#</a></span><a aria-hidden="true" class="legacy" id="http_outgoingmessage_write_chunk_encoding_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>The <code>chunk</code> parameter can now be a <code>Uint8Array</code>.</p></td></tr>
<tr><td>v0.11.6</td>
<td><p>The <code>callback</code> argument was added.</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>chunk</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#all_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> <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 a chunk of the body. This method can be called multiple times.</p>
<p>The <code>encoding</code> argument is only relevant when <code>chunk</code> is a string. Defaults to
<code>'utf8'</code>.</p>
<p>The <code>callback</code> argument is optional and will be called when this chunk of data
is flushed.</p>
<p>Returns <code>true</code> if the entire data was flushed successfully to the kernel
buffer. Returns <code>false</code> if all or part of the data was queued in the user
memory. The <code>'drain'</code> event will be emitted when the buffer is free again.</p>
</section><section><h3><code>http.METHODS</code><span><a class="mark" href="#all_http_httpmethods" id="all_http_httpmethods">#</a></span><a aria-hidden="true" class="legacy" id="http_http_methods"></a></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>A list of the HTTP methods that are supported by the parser.</p>
</section><section><h3><code>http.STATUS_CODES</code><span><a class="mark" href="#all_http_httpstatus_codes" id="all_http_httpstatus_codes">#</a></span><a aria-hidden="true" class="legacy" id="http_http_status_codes"></a></h3>
<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>
</section><section><h3><code>http.createServer([options][, requestListener])</code><span><a class="mark" href="#all_http_httpcreateserveroptions-requestlistener" id="all_http_httpcreateserveroptions-requestlistener">#</a></span><a aria-hidden="true" class="legacy" id="http_http_createserver_options_requestlistener"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.1.0</td>
<td><p>The <code>highWaterMark</code> option is supported now.</p></td></tr>
<tr><td>v18.0.0</td>
<td><p>The <code>requestTimeout</code>, <code>headersTimeout</code>, <code>keepAliveTimeout</code>, and <code>connectionsCheckingInterval</code> options are supported now.</p></td></tr>
<tr><td>v18.0.0</td>
<td><p>The <code>noDelay</code> option now defaults to <code>true</code>.</p></td></tr>
<tr><td>v17.7.0, v16.15.0</td>
<td><p>The <code>noDelay</code>, <code>keepAlive</code> and <code>keepAliveInitialDelay</code> options are supported now.</p></td></tr>
<tr><td>v13.3.0</td>
<td><p>The <code>maxHeaderSize</code> option is supported now.</p></td></tr>
<tr><td>v13.8.0, v12.15.0, v10.19.0</td>
<td><p>The <code>insecureHTTPParser</code> option is supported now.</p></td></tr>
<tr><td>v9.6.0, v8.12.0</td>
<td><p>The <code>options</code> argument is supported now.</p></td></tr>
<tr><td>v0.1.13</td>
<td><p><span>Added in: v0.1.13</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>
<p><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></p>
<ul>
<li><code>connectionsCheckingInterval</code>: Sets the interval value in milliseconds to
check for request and headers timeout in incomplete requests.
<strong>Default:</strong> <code>30000</code>.</li>
<li><code>headersTimeout</code>: Sets the timeout value in milliseconds for receiving
the complete HTTP headers from the client.
See <a href="#all_http_serverheaderstimeout"><code>server.headersTimeout</code></a> for more information.
<strong>Default:</strong> <code>60000</code>.</li>
<li><code>highWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Optionally overrides all <code>socket</code>s'
<code>readableHighWaterMark</code> and <code>writableHighWaterMark</code>. This affects
<code>highWaterMark</code> property of both <code>IncomingMessage</code> and <code>ServerResponse</code>.
<strong>Default:</strong> See <a href="#all_stream_streamgetdefaulthighwatermarkobjectmode"><code>stream.getDefaultHighWaterMark()</code></a>.</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="#all_cli_--insecure-http-parser"><code>--insecure-http-parser</code></a> for more information.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>IncomingMessage</code> <a href="#all_http_class-httpincomingmessage" 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>joinDuplicateHeaders</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>, this option allows
joining the field line values of multiple headers in a request with
a comma (<code>, </code>) instead of discarding the duplicates.
For more information, refer to <a href="#all_http_messageheaders"><code>message.headers</code></a>.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>keepAlive</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>, it enables keep-alive functionality
on the socket immediately after a new incoming connection is received,
similarly on what is done in [<code>socket.setKeepAlive([enable][, initialDelay])</code>][<code>socket.setKeepAlive(enable, initialDelay)</code>].
<strong>Default:</strong> <code>false</code>.</li>
<li><code>keepAliveInitialDelay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> If set to a positive number, it sets the
initial delay before the first keepalive probe is sent on an idle socket.
<strong>Default:</strong> <code>0</code>.</li>
<li><code>keepAliveTimeout</code>: 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.
See <a href="#all_http_serverkeepalivetimeout"><code>server.keepAliveTimeout</code></a> for more information.
<strong>Default:</strong> <code>5000</code>.</li>
<li><code>maxHeaderSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Optionally overrides the value of
<a href="#all_cli_--max-http-header-sizesize"><code>--max-http-header-size</code></a> for requests received by this server, i.e.
the maximum length of request headers in bytes.
<strong>Default:</strong> 16384 (16 KiB).</li>
<li><code>noDelay</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>, it disables the use of Nagle's
algorithm immediately after a new incoming connection is received.
<strong>Default:</strong> <code>true</code>.</li>
<li><code>requestTimeout</code>: Sets the timeout value in milliseconds for receiving
the entire request from the client.
See <a href="#all_http_serverrequesttimeout"><code>server.requestTimeout</code></a> for more information.
<strong>Default:</strong> <code>300000</code>.</li>
<li><code>requireHostHeader</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>, it forces the server to
respond with a 400 (Bad Request) status code to any HTTP/1.1
request message that lacks a Host header
(as mandated by the specification).
<strong>Default:</strong> <code>true</code>.</li>
<li><code>ServerResponse</code> <a href="#all_http_class-httpserverresponse" 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>uniqueHeaders</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type">&#x3C;Array></a> A list of response headers that should be sent only
once. If the header's value is an array, the items will be joined
using <code>; </code>.</li>
<li><code>rejectNonStandardBodyWrites</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>, an error is thrown
when writing to an HTTP response which does not have a body.
<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="#all_http_class-httpserver" class="type">&#x3C;http.Server></a></p>
</li>
</ul>
<p>Returns a new instance of <a href="#all_http_class-httpserver"><code>http.Server</code></a>.</p>
<p>The <code>requestListener</code> is a function which is automatically
added to the <a href="#all_http_event-request"><code>'request'</code></a> event.</p>

<pre class="with-34-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> http <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;

<span class="hljs-comment">// Create a local server to receive data from</span>
<span class="hljs-keyword">const</span> server = http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
  res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span> });
  res.<span class="hljs-title function_">end</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>({
    <span class="hljs-attr">data</span>: <span class="hljs-string">'Hello World!'</span>,
  }));
});

server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);

<span class="hljs-comment">// Create a local server to receive data from</span>
<span class="hljs-keyword">const</span> server = http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
  res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span> });
  res.<span class="hljs-title function_">end</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>({
    <span class="hljs-attr">data</span>: <span class="hljs-string">'Hello World!'</span>,
  }));
});

server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);</code><button class="copy-button">copy</button></pre>

<pre class="with-34-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> http <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;

<span class="hljs-comment">// Create a local server to receive data from</span>
<span class="hljs-keyword">const</span> server = http.<span class="hljs-title function_">createServer</span>();

<span class="hljs-comment">// Listen to the request event</span>
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'request'</span>, <span class="hljs-function">(<span class="hljs-params">request, res</span>) =></span> {
  res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span> });
  res.<span class="hljs-title function_">end</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>({
    <span class="hljs-attr">data</span>: <span class="hljs-string">'Hello World!'</span>,
  }));
});

server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);

<span class="hljs-comment">// Create a local server to receive data from</span>
<span class="hljs-keyword">const</span> server = http.<span class="hljs-title function_">createServer</span>();

<span class="hljs-comment">// Listen to the request event</span>
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'request'</span>, <span class="hljs-function">(<span class="hljs-params">request, res</span>) =></span> {
  res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span> });
  res.<span class="hljs-title function_">end</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>({
    <span class="hljs-attr">data</span>: <span class="hljs-string">'Hello World!'</span>,
  }));
});

server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>http.get(options[, callback])</code><span><a class="mark" href="#all_http_httpgetoptions-callback" id="all_http_httpgetoptions-callback">#</a></span><a aria-hidden="true" class="legacy" id="http_http_get_options_callback"></a></h3>
</section><section><h3><code>http.get(url[, options][, callback])</code><span><a class="mark" href="#all_http_httpgeturl-options-callback" id="all_http_httpgeturl-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="http_http_get_url_options_callback"></a></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>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="#all_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="#all_http_httprequestoptions-callback"><code>http.request()</code></a>, with the method set to GET by default.</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="#all_http_class-httpclientrequest" 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="#all_http_httprequestoptions-callback"><code>http.request()</code></a> is that it sets the method to GET by default and calls <code>req.end()</code>
automatically. The callback must take care to consume the response
data for reasons stated in <a href="#all_http_class-httpclientrequest"><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="#all_http_class-httpincomingmessage"><code>http.IncomingMessage</code></a>.</p>
<p>JSON fetching example:</p>
<pre><code class="language-js">http.<span class="hljs-title function_">get</span>(<span class="hljs-string">'http://localhost:8000/'</span>, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
  <span class="hljs-keyword">const</span> { statusCode } = res;
  <span class="hljs-keyword">const</span> contentType = res.<span class="hljs-property">headers</span>[<span class="hljs-string">'content-type'</span>];

  <span class="hljs-keyword">let</span> error;
  <span class="hljs-comment">// Any 2xx status code signals a successful response but</span>
  <span class="hljs-comment">// here we're only checking for 200.</span>
  <span class="hljs-keyword">if</span> (statusCode !== <span class="hljs-number">200</span>) {
    error = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Request Failed.\n'</span> +
                      <span class="hljs-string">`Status Code: <span class="hljs-subst">${statusCode}</span>`</span>);
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (!<span class="hljs-regexp">/^application\/json/</span>.<span class="hljs-title function_">test</span>(contentType)) {
    error = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Invalid content-type.\n'</span> +
                      <span class="hljs-string">`Expected application/json but received <span class="hljs-subst">${contentType}</span>`</span>);
  }
  <span class="hljs-keyword">if</span> (error) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(error.<span class="hljs-property">message</span>);
    <span class="hljs-comment">// Consume response data to free up memory</span>
    res.<span class="hljs-title function_">resume</span>();
    <span class="hljs-keyword">return</span>;
  }

  res.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>);
  <span class="hljs-keyword">let</span> rawData = <span class="hljs-string">''</span>;
  res.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> { rawData += chunk; });
  res.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> {
    <span class="hljs-keyword">try</span> {
      <span class="hljs-keyword">const</span> parsedData = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(rawData);
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(parsedData);
    } <span class="hljs-keyword">catch</span> (e) {
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(e.<span class="hljs-property">message</span>);
    }
  });
}).<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`Got error: <span class="hljs-subst">${e.message}</span>`</span>);
});

<span class="hljs-comment">// Create a local server to receive data from</span>
<span class="hljs-keyword">const</span> server = http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
  res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span> });
  res.<span class="hljs-title function_">end</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>({
    <span class="hljs-attr">data</span>: <span class="hljs-string">'Hello World!'</span>,
  }));
});

server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>http.globalAgent</code><span><a class="mark" href="#all_http_httpglobalagent" id="all_http_httpglobalagent">#</a></span><a aria-hidden="true" class="legacy" id="http_http_globalagent"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>The agent now uses HTTP Keep-Alive and a 5 second timeout by default.</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><a href="#all_http_class-httpagent" 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. Diverges from a default <code>Agent</code> configuration by having <code>keepAlive</code>
enabled and a <code>timeout</code> of 5 seconds.</p>
</section><section><h3><code>http.maxHeaderSize</code><span><a class="mark" href="#all_http_httpmaxheadersize" id="all_http_httpmaxheadersize">#</a></span><a aria-hidden="true" class="legacy" id="http_http_maxheadersize"></a></h3>
<div class="api_metadata">
<span>Added in: v11.6.0, v10.15.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 16 KiB. Configurable using the <a href="#all_cli_--max-http-header-sizesize"><code>--max-http-header-size</code></a> CLI
option.</p>
<p>This can be overridden for servers and client requests by passing the
<code>maxHeaderSize</code> option.</p>
</section><section><h3><code>http.request(options[, callback])</code><span><a class="mark" href="#all_http_httprequestoptions-callback" id="all_http_httprequestoptions-callback">#</a></span><a aria-hidden="true" class="legacy" id="http_http_request_options_callback"></a></h3>
</section><section><h3><code>http.request(url[, options][, callback])</code><span><a class="mark" href="#all_http_httprequesturl-options-callback" id="all_http_httprequesturl-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="http_http_request_url_options_callback"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.7.0, v14.18.0</td>
<td><p>When using a <code>URL</code> object parsed username and password will now be properly URI decoded.</p></td></tr>
<tr><td>v15.3.0, v14.17.0</td>
<td><p>It is possible to abort a request with an AbortSignal.</p></td></tr>
<tr><td>v13.3.0</td>
<td><p>The <code>maxHeaderSize</code> option is supported now.</p></td></tr>
<tr><td>v13.8.0, v12.15.0, v10.19.0</td>
<td><p>The <code>insecureHTTPParser</code> option is supported now.</p></td></tr>
<tr><td>v10.9.0</td>
<td><p>The <code>url</code> parameter can now be passed along with a separate <code>options</code> object.</p></td></tr>
<tr><td>v7.5.0</td>
<td><p>The <code>options</code> parameter can be a WHATWG <code>URL</code> object.</p></td></tr>
<tr><td>v0.3.6</td>
<td><p><span>Added in: v0.3.6</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>url</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#all_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>
<ul>
<li><code>agent</code> <a href="#all_http_class-httpagent" 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="#all_http_class-httpagent"><code>Agent</code></a> behavior. Possible
values:
<ul>
<li><code>undefined</code> (default): use <a href="#all_http_httpglobalagent"><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 (<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="#all_http_agentcreateconnectionoptions-callback"><code>agent.createConnection()</code></a> for more
details. Any <a href="#all_stream_class-streamduplex"><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>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="#all_dns_supported-getaddrinfo-flags"><code>dns.lookup()</code> hints</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> 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="#all_url_urlparseurlstring-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="#all_cli_--insecure-http-parser"><code>--insecure-http-parser</code></a> for more information.
<strong>Default:</strong> <code>false</code></li>
<li><code>joinDuplicateHeaders</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> It joins the field line values of
multiple headers in a request with <code>, </code> instead of discarding
the duplicates. See <a href="#all_http_messageheaders"><code>message.headers</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>localPort</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Local port to connect from.</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="#all_dns_dnslookuphostname-options-callback"><code>dns.lookup()</code></a>.</li>
<li><code>maxHeaderSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Optionally overrides the value of
<a href="#all_cli_--max-http-header-sizesize"><code>--max-http-header-size</code></a> (the maximum length of response headers in
bytes) for responses received from the server.
<strong>Default:</strong> 16384 (16 KiB).</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>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a>: An AbortSignal that may be used to abort an ongoing
request.</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, as 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>
<li><code>uniqueHeaders</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type">&#x3C;Array></a> A list of request headers that should be sent
only once. If the header's value is an array, the items will be joined
using <code>; </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="#all_http_class-httpclientrequest" class="type">&#x3C;http.ClientRequest></a></li>
</ul>
<p><code>options</code> in <a href="#all_net_socketconnectoptions-connectlistener"><code>socket.connect()</code></a> are also supported.</p>
<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="#all_url_the-whatwg-url-api"><code>URL</code></a> object. If <code>url</code> is a
string, it is automatically parsed with <a href="#all_url_new-urlinput-base"><code>new URL()</code></a>. If it is a <a href="#all_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="#all_http_event-response"><code>'response'</code></a> event.</p>
<p><code>http.request()</code> returns an instance of the <a href="#all_http_class-httpclientrequest"><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 class="with-37-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> http <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> postData = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>({
  <span class="hljs-string">'msg'</span>: <span class="hljs-string">'Hello World!'</span>,
});

<span class="hljs-keyword">const</span> options = {
  <span class="hljs-attr">hostname</span>: <span class="hljs-string">'www.google.com'</span>,
  <span class="hljs-attr">port</span>: <span class="hljs-number">80</span>,
  <span class="hljs-attr">path</span>: <span class="hljs-string">'/upload'</span>,
  <span class="hljs-attr">method</span>: <span class="hljs-string">'POST'</span>,
  <span class="hljs-attr">headers</span>: {
    <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>,
    <span class="hljs-string">'Content-Length'</span>: <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">byteLength</span>(postData),
  },
};

<span class="hljs-keyword">const</span> req = http.<span class="hljs-title function_">request</span>(options, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`STATUS: <span class="hljs-subst">${res.statusCode}</span>`</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`HEADERS: <span class="hljs-subst">${<span class="hljs-built_in">JSON</span>.stringify(res.headers)}</span>`</span>);
  res.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>);
  res.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`BODY: <span class="hljs-subst">${chunk}</span>`</span>);
  });
  res.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'No more data in response.'</span>);
  });
});

req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`problem with request: <span class="hljs-subst">${e.message}</span>`</span>);
});

<span class="hljs-comment">// Write data to request body</span>
req.<span class="hljs-title function_">write</span>(postData);
req.<span class="hljs-title function_">end</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);

<span class="hljs-keyword">const</span> postData = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>({
  <span class="hljs-string">'msg'</span>: <span class="hljs-string">'Hello World!'</span>,
});

<span class="hljs-keyword">const</span> options = {
  <span class="hljs-attr">hostname</span>: <span class="hljs-string">'www.google.com'</span>,
  <span class="hljs-attr">port</span>: <span class="hljs-number">80</span>,
  <span class="hljs-attr">path</span>: <span class="hljs-string">'/upload'</span>,
  <span class="hljs-attr">method</span>: <span class="hljs-string">'POST'</span>,
  <span class="hljs-attr">headers</span>: {
    <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>,
    <span class="hljs-string">'Content-Length'</span>: <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">byteLength</span>(postData),
  },
};

<span class="hljs-keyword">const</span> req = http.<span class="hljs-title function_">request</span>(options, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`STATUS: <span class="hljs-subst">${res.statusCode}</span>`</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`HEADERS: <span class="hljs-subst">${<span class="hljs-built_in">JSON</span>.stringify(res.headers)}</span>`</span>);
  res.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>);
  res.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`BODY: <span class="hljs-subst">${chunk}</span>`</span>);
  });
  res.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'No more data in response.'</span>);
  });
});

req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`problem with request: <span class="hljs-subst">${e.message}</span>`</span>);
});

<span class="hljs-comment">// Write data to request body</span>
req.<span class="hljs-title function_">write</span>(postData);
req.<span class="hljs-title function_">end</span>();</code><button class="copy-button">copy</button></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="#all_url_the-whatwg-url-api"><code>URL</code></a> as <code>options</code>:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> options = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'http://abc:xyz@example.com'</span>);

<span class="hljs-keyword">const</span> req = http.<span class="hljs-title function_">request</span>(options, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
  <span class="hljs-comment">// ...</span>
});</code> <button class="copy-button">copy</button></pre>
<p>In a successful request, the following events will be emitted in the following
order:</p>
<ul>
<li><code>'socket'</code></li>
<li><code>'response'</code>
<ul>
<li><code>'data'</code> any number of times, on the <code>res</code> object
(<code>'data'</code> will not be emitted at all if the response body is empty, for
instance, in most redirects)</li>
<li><code>'end'</code> on the <code>res</code> object</li>
</ul>
</li>
<li><code>'close'</code></li>
</ul>
<p>In the case of a connection error, the following events will be emitted:</p>
<ul>
<li><code>'socket'</code></li>
<li><code>'error'</code></li>
<li><code>'close'</code></li>
</ul>
<p>In the case of a premature connection close before the response is received,
the following events will be emitted in the following order:</p>
<ul>
<li><code>'socket'</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>In the case of a premature connection close after the response is received,
the following events will be emitted in the following order:</p>
<ul>
<li><code>'socket'</code></li>
<li><code>'response'</code>
<ul>
<li><code>'data'</code> any number of times, on the <code>res</code> object</li>
</ul>
</li>
<li>(connection closed here)</li>
<li><code>'aborted'</code> on the <code>res</code> object</li>
<li><code>'close'</code></li>
<li><code>'error'</code> on the <code>res</code> object with an error with message
<code>'Error: aborted'</code> and code <code>'ECONNRESET'</code></li>
<li><code>'close'</code> on the <code>res</code> object</li>
</ul>
<p>If <code>req.destroy()</code> is called before a socket is assigned, the following
events will be emitted in the following order:</p>
<ul>
<li>(<code>req.destroy()</code> called here)</li>
<li><code>'error'</code> with an error with message <code>'Error: socket hang up'</code> and code
<code>'ECONNRESET'</code>, or the error with which <code>req.destroy()</code> was called</li>
<li><code>'close'</code></li>
</ul>
<p>If <code>req.destroy()</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.destroy()</code> called here)</li>
<li><code>'error'</code> with an error with message <code>'Error: socket hang up'</code> and code
<code>'ECONNRESET'</code>, or the error with which <code>req.destroy()</code> was called</li>
<li><code>'close'</code></li>
</ul>
<p>If <code>req.destroy()</code> is called after the response is received, the following
events will be emitted in the following order:</p>
<ul>
<li><code>'socket'</code></li>
<li><code>'response'</code>
<ul>
<li><code>'data'</code> any number of times, on the <code>res</code> object</li>
</ul>
</li>
<li>(<code>req.destroy()</code> called here)</li>
<li><code>'aborted'</code> on the <code>res</code> object</li>
<li><code>'close'</code></li>
<li><code>'error'</code> on the <code>res</code> object with an error with message <code>'Error: aborted'</code>
and code <code>'ECONNRESET'</code>, or the error with which <code>req.destroy()</code> was called</li>
<li><code>'close'</code> on the <code>res</code> object</li>
</ul>
<p>If <code>req.abort()</code> is called before a socket is assigned, the following
events will be emitted in the following order:</p>
<ul>
<li>(<code>req.abort()</code> called here)</li>
<li><code>'abort'</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><code>'response'</code>
<ul>
<li><code>'data'</code> any number of times, on the <code>res</code> object</li>
</ul>
</li>
<li>(<code>req.abort()</code> called here)</li>
<li><code>'abort'</code></li>
<li><code>'aborted'</code> on the <code>res</code> object</li>
<li><code>'error'</code> on the <code>res</code> object with an error with message
<code>'Error: aborted'</code> and code <code>'ECONNRESET'</code>.</li>
<li><code>'close'</code></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>
<p>Passing an <code>AbortSignal</code> and then calling <code>abort()</code> on the corresponding
<code>AbortController</code> will behave the same way as calling <code>.destroy()</code> on the
request. Specifically, the <code>'error'</code> event will be emitted with an error with
the message <code>'AbortError: The operation was aborted'</code>, the code <code>'ABORT_ERR'</code>
and the <code>cause</code>, if one was provided.</p>
</section><section><h3><code>http.validateHeaderName(name[, label])</code><span><a class="mark" href="#all_http_httpvalidateheadernamename-label" id="all_http_httpvalidateheadernamename-label">#</a></span><a aria-hidden="true" class="legacy" id="http_http_validateheadername_name_label"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.5.0, v18.14.0</td>
<td><p>The <code>label</code> parameter is added.</p></td></tr>
<tr><td>v14.3.0</td>
<td><p><span>Added in: v14.3.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>label</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Label for error message. <strong>Default:</strong> <code>'Header name'</code>.</li>
</ul>
<p>Performs the low-level validations on the provided <code>name</code> that are done when
<code>res.setHeader(name, value)</code> is called.</p>
<p>Passing illegal value as <code>name</code> will result in a <a href="#all_errors_class-typeerror"><code>TypeError</code></a> being thrown,
identified by <code>code: 'ERR_INVALID_HTTP_TOKEN'</code>.</p>
<p>It is not necessary to use this method before passing headers to an HTTP request
or response. The HTTP module will automatically validate such headers.</p>
<p>Example:</p>

<pre class="with-52-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { validateHeaderName } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;

<span class="hljs-keyword">try</span> {
  <span class="hljs-title function_">validateHeaderName</span>(<span class="hljs-string">''</span>);
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">TypeError</span>); <span class="hljs-comment">// --> true</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err.<span class="hljs-property">code</span>); <span class="hljs-comment">// --> 'ERR_INVALID_HTTP_TOKEN'</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err.<span class="hljs-property">message</span>); <span class="hljs-comment">// --> 'Header name must be a valid HTTP token [""]'</span>
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { validateHeaderName } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);

<span class="hljs-keyword">try</span> {
  <span class="hljs-title function_">validateHeaderName</span>(<span class="hljs-string">''</span>);
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">TypeError</span>); <span class="hljs-comment">// --> true</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err.<span class="hljs-property">code</span>); <span class="hljs-comment">// --> 'ERR_INVALID_HTTP_TOKEN'</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err.<span class="hljs-property">message</span>); <span class="hljs-comment">// --> 'Header name must be a valid HTTP token [""]'</span>
}</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>http.validateHeaderValue(name, value)</code><span><a class="mark" href="#all_http_httpvalidateheadervaluename-value" id="all_http_httpvalidateheadervaluename-value">#</a></span><a aria-hidden="true" class="legacy" id="http_http_validateheadervalue_name_value"></a></h3>
<div class="api_metadata">
<span>Added in: v14.3.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>Performs the low-level validations on the provided <code>value</code> that are done when
<code>res.setHeader(name, value)</code> is called.</p>
<p>Passing illegal value as <code>value</code> will result in a <a href="#all_errors_class-typeerror"><code>TypeError</code></a> being thrown.</p>
<ul>
<li>Undefined value error is identified by <code>code: 'ERR_HTTP_INVALID_HEADER_VALUE'</code>.</li>
<li>Invalid value character error is identified by <code>code: 'ERR_INVALID_CHAR'</code>.</li>
</ul>
<p>It is not necessary to use this method before passing headers to an HTTP request
or response. The HTTP module will automatically validate such headers.</p>
<p>Examples:</p>

<pre class="with-53-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { validateHeaderValue } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http'</span>;

<span class="hljs-keyword">try</span> {
  <span class="hljs-title function_">validateHeaderValue</span>(<span class="hljs-string">'x-my-header'</span>, <span class="hljs-literal">undefined</span>);
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">TypeError</span>); <span class="hljs-comment">// --> true</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err.<span class="hljs-property">code</span> === <span class="hljs-string">'ERR_HTTP_INVALID_HEADER_VALUE'</span>); <span class="hljs-comment">// --> true</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err.<span class="hljs-property">message</span>); <span class="hljs-comment">// --> 'Invalid value "undefined" for header "x-my-header"'</span>
}

<span class="hljs-keyword">try</span> {
  <span class="hljs-title function_">validateHeaderValue</span>(<span class="hljs-string">'x-my-header'</span>, <span class="hljs-string">'oʊmɪɡə'</span>);
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">TypeError</span>); <span class="hljs-comment">// --> true</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err.<span class="hljs-property">code</span> === <span class="hljs-string">'ERR_INVALID_CHAR'</span>); <span class="hljs-comment">// --> true</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err.<span class="hljs-property">message</span>); <span class="hljs-comment">// --> 'Invalid character in header content ["x-my-header"]'</span>
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { validateHeaderValue } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);

<span class="hljs-keyword">try</span> {
  <span class="hljs-title function_">validateHeaderValue</span>(<span class="hljs-string">'x-my-header'</span>, <span class="hljs-literal">undefined</span>);
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">TypeError</span>); <span class="hljs-comment">// --> true</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err.<span class="hljs-property">code</span> === <span class="hljs-string">'ERR_HTTP_INVALID_HEADER_VALUE'</span>); <span class="hljs-comment">// --> true</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err.<span class="hljs-property">message</span>); <span class="hljs-comment">// --> 'Invalid value "undefined" for header "x-my-header"'</span>
}

<span class="hljs-keyword">try</span> {
  <span class="hljs-title function_">validateHeaderValue</span>(<span class="hljs-string">'x-my-header'</span>, <span class="hljs-string">'oʊmɪɡə'</span>);
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">TypeError</span>); <span class="hljs-comment">// --> true</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err.<span class="hljs-property">code</span> === <span class="hljs-string">'ERR_INVALID_CHAR'</span>); <span class="hljs-comment">// --> true</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err.<span class="hljs-property">message</span>); <span class="hljs-comment">// --> 'Invalid character in header content ["x-my-header"]'</span>
}</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>http.setMaxIdleHTTPParsers(max)</code><span><a class="mark" href="#all_http_httpsetmaxidlehttpparsersmax" id="all_http_httpsetmaxidlehttpparsersmax">#</a></span><a aria-hidden="true" class="legacy" id="http_http_setmaxidlehttpparsers_max"></a></h3>
<div class="api_metadata">
<span>Added in: v18.8.0, v16.18.0</span>
</div>
<ul>
<li><code>max</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>1000</code>.</li>
</ul>
<p>Set the maximum number of idle HTTP parsers.</p></section>
        </section>
<section><h2>HTTP/2<span><a class="mark" href="#all_http2_http2" id="all_http2_http2">#</a></span><a aria-hidden="true" class="legacy" id="http2_http_2"></a></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>Requests with the <code>host</code> header (with or without <code>:authority</code>) can now be sent/received.</p></td></tr>
<tr><td>v15.3.0, v14.17.0</td>
<td><p>It is possible to abort a request with an AbortSignal.</p></td></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="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/http2.js">lib/http2.js</a></p>
<p>The <code>node: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"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);</code> <button class="copy-button">copy</button></pre>
<section><h3>Determining if crypto support is unavailable<span><a class="mark" href="#all_http2_determining-if-crypto-support-is-unavailable" id="all_http2_determining-if-crypto-support-is-unavailable">#</a></span><a aria-hidden="true" class="legacy" id="http2_determining_if_crypto_support_is_unavailable"></a></h3>
<p>It is possible for Node.js to be built without including support for the
<code>node:crypto</code> module. In such cases, attempting to <code>import</code> from <code>node:http2</code> or
calling <code>require('node:http2')</code> will result in an error being thrown.</p>
<p>When using CommonJS, the error thrown can be caught using try/catch:</p>
<pre><code class="language-js cjs"><span class="hljs-keyword">let</span> http2;
<span class="hljs-keyword">try</span> {
  http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'http2 support is disabled!'</span>);
}</code> <button class="copy-button">copy</button></pre>
<p>When using the lexical ESM <code>import</code> keyword, the error can only be
caught if a handler for <code>process.on('uncaughtException')</code> is registered
<em>before</em> any attempt to load the module is made (using, for instance,
a preload module).</p>
<p>When using ESM, if there is a chance that the code may be run on a build
of Node.js where crypto support is not enabled, consider using the
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import"><code>import()</code></a> function instead of the lexical <code>import</code> keyword:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">let</span> http2;
<span class="hljs-keyword">try</span> {
  http2 = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:http2'</span>);
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'http2 support is disabled!'</span>);
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Core API<span><a class="mark" href="#all_http2_core-api" id="all_http2_core-api">#</a></span><a aria-hidden="true" class="legacy" id="http2_core_api"></a></h3>
<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="#all_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>
<h4>Server-side example<span><a class="mark" href="#all_http2_server-side-example" id="all_http2_server-side-example">#</a></span><a aria-hidden="true" class="legacy" id="http2_server_side_example"></a></h4>
<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="#all_http2_http2createsecureserveroptions-onrequesthandler"><code>http2.createSecureServer()</code></a> is necessary when communicating
with browser clients.</p>

<pre class="with-48-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createSecureServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">import</span> { readFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createSecureServer</span>({
  <span class="hljs-attr">key</span>: <span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'localhost-privkey.pem'</span>),
  <span class="hljs-attr">cert</span>: <span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'localhost-cert.pem'</span>),
});

server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err));

server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream, headers</span>) =></span> {
  <span class="hljs-comment">// stream is a Duplex</span>
  stream.<span class="hljs-title function_">respond</span>({
    <span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/html; charset=utf-8'</span>,
    <span class="hljs-string">':status'</span>: <span class="hljs-number">200</span>,
  });
  stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'&#x3C;h1>Hello World&#x3C;/h1>'</span>);
});

server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8443</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);

<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createSecureServer</span>({
  <span class="hljs-attr">key</span>: fs.<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'localhost-privkey.pem'</span>),
  <span class="hljs-attr">cert</span>: fs.<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'localhost-cert.pem'</span>),
});
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err));

server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream, headers</span>) =></span> {
  <span class="hljs-comment">// stream is a Duplex</span>
  stream.<span class="hljs-title function_">respond</span>({
    <span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/html; charset=utf-8'</span>,
    <span class="hljs-string">':status'</span>: <span class="hljs-number">200</span>,
  });
  stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'&#x3C;h1>Hello World&#x3C;/h1>'</span>);
});

server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8443</span>);</code><button class="copy-button">copy</button></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 <span class="hljs-string">'/CN=localhost'</span> \
  -keyout localhost-privkey.pem -out localhost-cert.pem</code> <button class="copy-button">copy</button></pre>
<h4>Client-side example<span><a class="mark" href="#all_http2_client-side-example" id="all_http2_client-side-example">#</a></span><a aria-hidden="true" class="legacy" id="http2_client_side_example"></a></h4>
<p>The following illustrates an HTTP/2 client:</p>

<pre class="with-39-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { connect } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">import</span> { readFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-keyword">const</span> client = <span class="hljs-title function_">connect</span>(<span class="hljs-string">'https://localhost:8443'</span>, {
  <span class="hljs-attr">ca</span>: <span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'localhost-cert.pem'</span>),
});
client.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err));

<span class="hljs-keyword">const</span> req = client.<span class="hljs-title function_">request</span>({ <span class="hljs-string">':path'</span>: <span class="hljs-string">'/'</span> });

req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'response'</span>, <span class="hljs-function">(<span class="hljs-params">headers, flags</span>) =></span> {
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> name <span class="hljs-keyword">in</span> headers) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${name}</span>: <span class="hljs-subst">${headers[name]}</span>`</span>);
  }
});

req.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>);
<span class="hljs-keyword">let</span> data = <span class="hljs-string">''</span>;
req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> { data += chunk; });
req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`\n<span class="hljs-subst">${data}</span>`</span>);
  client.<span class="hljs-title function_">close</span>();
});
req.<span class="hljs-title function_">end</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);

<span class="hljs-keyword">const</span> client = http2.<span class="hljs-title function_">connect</span>(<span class="hljs-string">'https://localhost:8443'</span>, {
  <span class="hljs-attr">ca</span>: fs.<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'localhost-cert.pem'</span>),
});
client.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err));

<span class="hljs-keyword">const</span> req = client.<span class="hljs-title function_">request</span>({ <span class="hljs-string">':path'</span>: <span class="hljs-string">'/'</span> });

req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'response'</span>, <span class="hljs-function">(<span class="hljs-params">headers, flags</span>) =></span> {
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> name <span class="hljs-keyword">in</span> headers) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${name}</span>: <span class="hljs-subst">${headers[name]}</span>`</span>);
  }
});

req.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>);
<span class="hljs-keyword">let</span> data = <span class="hljs-string">''</span>;
req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> { data += chunk; });
req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`\n<span class="hljs-subst">${data}</span>`</span>);
  client.<span class="hljs-title function_">close</span>();
});
req.<span class="hljs-title function_">end</span>();</code><button class="copy-button">copy</button></pre>
<h4>Class: <code>Http2Session</code><span><a class="mark" href="#all_http2_class-http2session" id="all_http2_class-http2session">#</a></span><a aria-hidden="true" class="legacy" id="http2_class_http2session"></a></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li>Extends: <a href="#all_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>
<h5><code>Http2Session</code> and sockets<span><a class="mark" href="#all_http2_http2session-and-sockets" id="all_http2_http2session-and-sockets">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_and_sockets"></a></h5>
<p>Every <code>Http2Session</code> instance is associated with exactly one <a href="#all_net_class-netsocket"><code>net.Socket</code></a> or
<a href="#all_tls_class-tlstlssocket"><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>
<h5>Event: <code>'close'</code><span><a class="mark" href="#all_http2_event-close" id="all_http2_event-close">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_close"></a></h5>
<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>
<h5>Event: <code>'connect'</code><span><a class="mark" href="#all_http2_event-connect" id="all_http2_event-connect">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_connect"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>session</code> <a href="#all_http2_class-http2session" class="type">&#x3C;Http2Session></a></li>
<li><code>socket</code> <a href="#all_net_class-netsocket" 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>
<h5>Event: <code>'error'</code><span><a class="mark" href="#all_http2_event-error" id="all_http2_event-error">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_error"></a></h5>
<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>
<h5>Event: <code>'frameError'</code><span><a class="mark" href="#all_http2_event-frameerror" id="all_http2_event-frameerror">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_frameerror"></a></h5>
<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>
<h5>Event: <code>'goaway'</code><span><a class="mark" href="#all_http2_event-goaway" id="all_http2_event-goaway">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_goaway"></a></h5>
<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="#all_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>
<h5>Event: <code>'localSettings'</code><span><a class="mark" href="#all_http2_event-localsettings" id="all_http2_event-localsettings">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_localsettings"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>settings</code> <a href="#all_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.<span class="hljs-title function_">settings</span>({ <span class="hljs-attr">enablePush</span>: <span class="hljs-literal">false</span> });

session.<span class="hljs-title function_">on</span>(<span class="hljs-string">'localSettings'</span>, <span class="hljs-function">(<span class="hljs-params">settings</span>) =></span> {
  <span class="hljs-comment">/* Use the new settings */</span>
});</code> <button class="copy-button">copy</button></pre>
<h5>Event: <code>'ping'</code><span><a class="mark" href="#all_http2_event-ping" id="all_http2_event-ping">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_ping"></a></h5>
<div class="api_metadata">
<span>Added in: v10.12.0</span>
</div>
<ul>
<li><code>payload</code> <a href="#all_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>
<h5>Event: <code>'remoteSettings'</code><span><a class="mark" href="#all_http2_event-remotesettings" id="all_http2_event-remotesettings">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_remotesettings"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>settings</code> <a href="#all_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.<span class="hljs-title function_">on</span>(<span class="hljs-string">'remoteSettings'</span>, <span class="hljs-function">(<span class="hljs-params">settings</span>) =></span> {
  <span class="hljs-comment">/* Use the new settings */</span>
});</code> <button class="copy-button">copy</button></pre>
<h5>Event: <code>'stream'</code><span><a class="mark" href="#all_http2_event-stream" id="all_http2_event-stream">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_stream"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>stream</code> <a href="#all_http2_class-http2stream" class="type">&#x3C;Http2Stream></a> A reference to the stream</li>
<li><code>headers</code> <a href="#all_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">session.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream, headers, flags</span>) =></span> {
  <span class="hljs-keyword">const</span> method = headers[<span class="hljs-string">':method'</span>];
  <span class="hljs-keyword">const</span> path = headers[<span class="hljs-string">':path'</span>];
  <span class="hljs-comment">// ...</span>
  stream.<span class="hljs-title function_">respond</span>({
    <span class="hljs-string">':status'</span>: <span class="hljs-number">200</span>,
    <span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/plain; charset=utf-8'</span>,
  });
  stream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello '</span>);
  stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'world'</span>);
});</code> <button class="copy-button">copy</button></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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;

<span class="hljs-comment">// Create an unencrypted HTTP/2 server</span>
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>();

server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream, headers</span>) =></span> {
  stream.<span class="hljs-title function_">respond</span>({
    <span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/html; charset=utf-8'</span>,
    <span class="hljs-string">':status'</span>: <span class="hljs-number">200</span>,
  });
  stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">error</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(error));
  stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'&#x3C;h1>Hello World&#x3C;/h1>'</span>);
});

server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);

<span class="hljs-comment">// Create an unencrypted HTTP/2 server</span>
<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createServer</span>();

server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream, headers</span>) =></span> {
  stream.<span class="hljs-title function_">respond</span>({
    <span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/html; charset=utf-8'</span>,
    <span class="hljs-string">':status'</span>: <span class="hljs-number">200</span>,
  });
  stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">error</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(error));
  stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'&#x3C;h1>Hello World&#x3C;/h1>'</span>);
});

server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);</code><button class="copy-button">copy</button></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>
<h5>Event: <code>'timeout'</code><span><a class="mark" href="#all_http2_event-timeout" id="all_http2_event-timeout">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_timeout"></a></h5>
<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.<span class="hljs-built_in">setTimeout</span>(<span class="hljs-number">2000</span>);
session.<span class="hljs-title function_">on</span>(<span class="hljs-string">'timeout'</span>, <span class="hljs-function">() =></span> { <span class="hljs-comment">/* .. */</span> });</code> <button class="copy-button">copy</button></pre>
<h5><code>http2session.alpnProtocol</code><span><a class="mark" href="#all_http2_http2sessionalpnprotocol" id="all_http2_http2sessionalpnprotocol">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_alpnprotocol"></a></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#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>
<h5><code>http2session.close([callback])</code><span><a class="mark" href="#all_http2_http2sessionclosecallback" id="all_http2_http2sessionclosecallback">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_close_callback"></a></h5>
<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>
<h5><code>http2session.closed</code><span><a class="mark" href="#all_http2_http2sessionclosed" id="all_http2_http2sessionclosed">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_closed"></a></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>Will be <code>true</code> if this <code>Http2Session</code> instance has been closed, otherwise
<code>false</code>.</p>
<h5><code>http2session.connecting</code><span><a class="mark" href="#all_http2_http2sessionconnecting" id="all_http2_http2sessionconnecting">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_connecting"></a></h5>
<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>
<h5><code>http2session.destroy([error][, code])</code><span><a class="mark" href="#all_http2_http2sessiondestroyerror-code" id="all_http2_http2sessiondestroyerror-code">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_destroy_error_code"></a></h5>
<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>
<h5><code>http2session.destroyed</code><span><a class="mark" href="#all_http2_http2sessiondestroyed" id="all_http2_http2sessiondestroyed">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_destroyed"></a></h5>
<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>
<h5><code>http2session.encrypted</code><span><a class="mark" href="#all_http2_http2sessionencrypted" id="all_http2_http2sessionencrypted">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_encrypted"></a></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> | <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>
<h5><code>http2session.goaway([code[, lastStreamID[, opaqueData]]])</code><span><a class="mark" href="#all_http2_http2sessiongoawaycode-laststreamid-opaquedata" id="all_http2_http2sessiongoawaycode-laststreamid-opaquedata">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_goaway_code_laststreamid_opaquedata"></a></h5>
<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="#all_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>
<h5><code>http2session.localSettings</code><span><a class="mark" href="#all_http2_http2sessionlocalsettings" id="all_http2_http2sessionlocalsettings">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_localsettings"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="#all_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>
<h5><code>http2session.originSet</code><span><a class="mark" href="#all_http2_http2sessionoriginset" id="all_http2_http2sessionoriginset">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_originset"></a></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#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>
<h5><code>http2session.pendingSettingsAck</code><span><a class="mark" href="#all_http2_http2sessionpendingsettingsack" id="all_http2_http2sessionpendingsettingsack">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_pendingsettingsack"></a></h5>
<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>
<h5><code>http2session.ping([payload, ]callback)</code><span><a class="mark" href="#all_http2_http2sessionpingpayload-callback" id="all_http2_http2sessionpingpayload-callback">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_ping_payload_callback"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></tr>
<tr><td>v8.9.3</td>
<td><p><span>Added in: v8.9.3</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>payload</code> <a href="#all_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.<span class="hljs-title function_">ping</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'abcdefgh'</span>), <span class="hljs-function">(<span class="hljs-params">err, duration, payload</span>) =></span> {
  <span class="hljs-keyword">if</span> (!err) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Ping acknowledged in <span class="hljs-subst">${duration}</span> milliseconds`</span>);
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`With payload '<span class="hljs-subst">${payload.toString()}</span>'`</span>);
  }
});</code> <button class="copy-button">copy</button></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>
<h5><code>http2session.ref()</code><span><a class="mark" href="#all_http2_http2sessionref" id="all_http2_http2sessionref">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_ref"></a></h5>
<div class="api_metadata">
<span>Added in: v9.4.0</span>
</div>
<p>Calls <a href="#all_net_socketref"><code>ref()</code></a> on this <code>Http2Session</code>
instance's underlying <a href="#all_net_class-netsocket"><code>net.Socket</code></a>.</p>
<h5><code>http2session.remoteSettings</code><span><a class="mark" href="#all_http2_http2sessionremotesettings" id="all_http2_http2sessionremotesettings">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_remotesettings"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="#all_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>
<h5><code>http2session.setLocalWindowSize(windowSize)</code><span><a class="mark" href="#all_http2_http2sessionsetlocalwindowsizewindowsize" id="all_http2_http2sessionsetlocalwindowsizewindowsize">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_setlocalwindowsize_windowsize"></a></h5>
<div class="api_metadata">
<span>Added in: v15.3.0, v14.18.0</span>
</div>
<ul>
<li><code>windowSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>Sets the local endpoint's window size.
The <code>windowSize</code> is the total window size to set, not
the delta.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;

<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>();
<span class="hljs-keyword">const</span> expectedWindowSize = <span class="hljs-number">2</span> ** <span class="hljs-number">20</span>;
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'session'</span>, <span class="hljs-function">(<span class="hljs-params">session</span>) =></span> {

  <span class="hljs-comment">// Set local window size to be 2 ** 20</span>
  session.<span class="hljs-title function_">setLocalWindowSize</span>(expectedWindowSize);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);

<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createServer</span>();
<span class="hljs-keyword">const</span> expectedWindowSize = <span class="hljs-number">2</span> ** <span class="hljs-number">20</span>;
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'session'</span>, <span class="hljs-function">(<span class="hljs-params">session</span>) =></span> {

  <span class="hljs-comment">// Set local window size to be 2 ** 20</span>
  session.<span class="hljs-title function_">setLocalWindowSize</span>(expectedWindowSize);
});</code><button class="copy-button">copy</button></pre>
<p>For http2 clients the proper event is either <code>'connect'</code> or <code>'remoteSettings'</code>.</p>
<h5><code>http2session.setTimeout(msecs, callback)</code><span><a class="mark" href="#all_http2_http2sessionsettimeoutmsecs-callback" id="all_http2_http2sessionsettimeoutmsecs-callback">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_settimeout_msecs_callback"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</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>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>
<h5><code>http2session.socket</code><span><a class="mark" href="#all_http2_http2sessionsocket" id="all_http2_http2sessionsocket">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_socket"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a> | <a href="#all_tls_class-tlstlssocket" 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="#all_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>
<h5><code>http2session.state</code><span><a class="mark" href="#all_http2_http2sessionstate" id="all_http2_http2sessionstate">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_state"></a></h5>
<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><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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>
<h5><code>http2session.settings([settings][, callback])</code><span><a class="mark" href="#all_http2_http2sessionsettingssettings-callback" id="all_http2_http2sessionsettingssettings-callback">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_settings_settings_callback"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</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>settings</code> <a href="#all_http2_settings-object" class="type">&#x3C;HTTP/2 Settings 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> Callback that is called once the session is connected or
right away if the session is already connected.
<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="#all_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>
<h5><code>http2session.type</code><span><a class="mark" href="#all_http2_http2sessiontype" id="all_http2_http2sessiontype">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_type"></a></h5>
<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>
<h5><code>http2session.unref()</code><span><a class="mark" href="#all_http2_http2sessionunref" id="all_http2_http2sessionunref">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2session_unref"></a></h5>
<div class="api_metadata">
<span>Added in: v9.4.0</span>
</div>
<p>Calls <a href="#all_net_socketunref"><code>unref()</code></a> on this <code>Http2Session</code>
instance's underlying <a href="#all_net_class-netsocket"><code>net.Socket</code></a>.</p>
<h4>Class: <code>ServerHttp2Session</code><span><a class="mark" href="#all_http2_class-serverhttp2session" id="all_http2_class-serverhttp2session">#</a></span><a aria-hidden="true" class="legacy" id="http2_class_serverhttp2session"></a></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li>Extends: <a href="#all_http2_class-http2session" class="type">&#x3C;Http2Session></a></li>
</ul>
<h5><code>serverhttp2session.altsvc(alt, originOrStream)</code><span><a class="mark" href="#all_http2_serverhttp2sessionaltsvcalt-originorstream" id="all_http2_serverhttp2sessionaltsvcalt-originorstream">#</a></span><a aria-hidden="true" class="legacy" id="http2_serverhttp2session_altsvc_alt_originorstream"></a></h5>
<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="#all_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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;

<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'session'</span>, <span class="hljs-function">(<span class="hljs-params">session</span>) =></span> {
  <span class="hljs-comment">// Set altsvc for origin https://example.org:80</span>
  session.<span class="hljs-title function_">altsvc</span>(<span class="hljs-string">'h2=":8000"'</span>, <span class="hljs-string">'https://example.org:80'</span>);
});

server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
  <span class="hljs-comment">// Set altsvc for a specific stream</span>
  stream.<span class="hljs-property">session</span>.<span class="hljs-title function_">altsvc</span>(<span class="hljs-string">'h2=":8000"'</span>, stream.<span class="hljs-property">id</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);

<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'session'</span>, <span class="hljs-function">(<span class="hljs-params">session</span>) =></span> {
  <span class="hljs-comment">// Set altsvc for origin https://example.org:80</span>
  session.<span class="hljs-title function_">altsvc</span>(<span class="hljs-string">'h2=":8000"'</span>, <span class="hljs-string">'https://example.org:80'</span>);
});

server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
  <span class="hljs-comment">// Set altsvc for a specific stream</span>
  stream.<span class="hljs-property">session</span>.<span class="hljs-title function_">altsvc</span>(<span class="hljs-string">'h2=":8000"'</span>, stream.<span class="hljs-property">id</span>);
});</code><button class="copy-button">copy</button></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>
<h5>Specifying alternative services<span><a class="mark" href="#all_http2_specifying-alternative-services" id="all_http2_specifying-alternative-services">#</a></span><a aria-hidden="true" class="legacy" id="http2_specifying_alternative_services"></a></h5>
<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>
<h5><code>serverhttp2session.origin(...origins)</code><span><a class="mark" href="#all_http2_serverhttp2sessionoriginorigins" id="all_http2_serverhttp2sessionoriginorigins">#</a></span><a aria-hidden="true" class="legacy" id="http2_serverhttp2session_origin_origins"></a></h5>
<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="#all_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 class="with-48-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createSecureServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> options = <span class="hljs-title function_">getSecureOptionsSomehow</span>();
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createSecureServer</span>(options);
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
  stream.<span class="hljs-title function_">respond</span>();
  stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'ok'</span>);
});
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'session'</span>, <span class="hljs-function">(<span class="hljs-params">session</span>) =></span> {
  session.<span class="hljs-title function_">origin</span>(<span class="hljs-string">'https://example.com'</span>, <span class="hljs-string">'https://example.org'</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> options = <span class="hljs-title function_">getSecureOptionsSomehow</span>();
<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createSecureServer</span>(options);
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
  stream.<span class="hljs-title function_">respond</span>();
  stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'ok'</span>);
});
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'session'</span>, <span class="hljs-function">(<span class="hljs-params">session</span>) =></span> {
  session.<span class="hljs-title function_">origin</span>(<span class="hljs-string">'https://example.com'</span>, <span class="hljs-string">'https://example.org'</span>);
});</code><button class="copy-button">copy</button></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 class="with-48-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createSecureServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> options = <span class="hljs-title function_">getSecureOptionsSomehow</span>();
options.<span class="hljs-property">origins</span> = [<span class="hljs-string">'https://example.com'</span>, <span class="hljs-string">'https://example.org'</span>];
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createSecureServer</span>(options);
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
  stream.<span class="hljs-title function_">respond</span>();
  stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'ok'</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> options = <span class="hljs-title function_">getSecureOptionsSomehow</span>();
options.<span class="hljs-property">origins</span> = [<span class="hljs-string">'https://example.com'</span>, <span class="hljs-string">'https://example.org'</span>];
<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createSecureServer</span>(options);
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
  stream.<span class="hljs-title function_">respond</span>();
  stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'ok'</span>);
});</code><button class="copy-button">copy</button></pre>
<h4>Class: <code>ClientHttp2Session</code><span><a class="mark" href="#all_http2_class-clienthttp2session" id="all_http2_class-clienthttp2session">#</a></span><a aria-hidden="true" class="legacy" id="http2_class_clienthttp2session"></a></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li>Extends: <a href="#all_http2_class-http2session" class="type">&#x3C;Http2Session></a></li>
</ul>
<h5>Event: <code>'altsvc'</code><span><a class="mark" href="#all_http2_event-altsvc" id="all_http2_event-altsvc">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_altsvc"></a></h5>
<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 class="with-52-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { connect } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> client = <span class="hljs-title function_">connect</span>(<span class="hljs-string">'https://example.org'</span>);

client.<span class="hljs-title function_">on</span>(<span class="hljs-string">'altsvc'</span>, <span class="hljs-function">(<span class="hljs-params">alt, origin, streamId</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(alt);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(origin);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(streamId);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> client = http2.<span class="hljs-title function_">connect</span>(<span class="hljs-string">'https://example.org'</span>);

client.<span class="hljs-title function_">on</span>(<span class="hljs-string">'altsvc'</span>, <span class="hljs-function">(<span class="hljs-params">alt, origin, streamId</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(alt);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(origin);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(streamId);
});</code><button class="copy-button">copy</button></pre>
<h5>Event: <code>'origin'</code><span><a class="mark" href="#all_http2_event-origin" id="all_http2_event-origin">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_origin"></a></h5>
<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 class="with-52-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { connect } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> client = <span class="hljs-title function_">connect</span>(<span class="hljs-string">'https://example.org'</span>);

client.<span class="hljs-title function_">on</span>(<span class="hljs-string">'origin'</span>, <span class="hljs-function">(<span class="hljs-params">origins</span>) =></span> {
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> n = <span class="hljs-number">0</span>; n &#x3C; origins.<span class="hljs-property">length</span>; n++)
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(origins[n]);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> client = http2.<span class="hljs-title function_">connect</span>(<span class="hljs-string">'https://example.org'</span>);

client.<span class="hljs-title function_">on</span>(<span class="hljs-string">'origin'</span>, <span class="hljs-function">(<span class="hljs-params">origins</span>) =></span> {
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> n = <span class="hljs-number">0</span>; n &#x3C; origins.<span class="hljs-property">length</span>; n++)
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(origins[n]);
});</code><button class="copy-button">copy</button></pre>
<p>The <code>'origin'</code> event is only emitted when using a secure TLS connection.</p>
<h5><code>clienthttp2session.request(headers[, options])</code><span><a class="mark" href="#all_http2_clienthttp2sessionrequestheaders-options" id="all_http2_clienthttp2sessionrequestheaders-options">#</a></span><a aria-hidden="true" class="legacy" id="http2_clienthttp2session_request_headers_options"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li>
<p><code>headers</code> <a href="#all_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>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> An AbortSignal that may be used to abort an ongoing
request.</li>
</ul>
</li>
<li>
<p>Returns: <a href="#all_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>When a <code>ClientHttp2Session</code> is first created, the socket may not yet be
connected. if <code>clienthttp2session.request()</code> is called during this time, the
actual request will be deferred until the socket is ready to go.
If the <code>session</code> is closed before the actual request be executed, an
<code>ERR_HTTP2_GOAWAY_SESSION</code> is thrown.</p>
<p>This method is only available if <code>http2session.type</code> is equal to
<code>http2.constants.NGHTTP2_SESSION_CLIENT</code>.</p>

<pre class="with-62-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { connect, constants } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> clientSession = <span class="hljs-title function_">connect</span>(<span class="hljs-string">'https://localhost:1234'</span>);
<span class="hljs-keyword">const</span> {
  <span class="hljs-title class_">HTTP2</span>_HEADER_PATH,
  <span class="hljs-title class_">HTTP2</span>_HEADER_STATUS,
} = constants;

<span class="hljs-keyword">const</span> req = clientSession.<span class="hljs-title function_">request</span>({ [<span class="hljs-title class_">HTTP2</span>_HEADER_PATH]: <span class="hljs-string">'/'</span> });
req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'response'</span>, <span class="hljs-function">(<span class="hljs-params">headers</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(headers[<span class="hljs-title class_">HTTP2</span>_HEADER_STATUS]);
  req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> { <span class="hljs-comment">/* .. */</span> });
  req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> { <span class="hljs-comment">/* .. */</span> });
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> clientSession = http2.<span class="hljs-title function_">connect</span>(<span class="hljs-string">'https://localhost:1234'</span>);
<span class="hljs-keyword">const</span> {
  <span class="hljs-title class_">HTTP2</span>_HEADER_PATH,
  <span class="hljs-title class_">HTTP2</span>_HEADER_STATUS,
} = http2.<span class="hljs-property">constants</span>;

<span class="hljs-keyword">const</span> req = clientSession.<span class="hljs-title function_">request</span>({ [<span class="hljs-title class_">HTTP2</span>_HEADER_PATH]: <span class="hljs-string">'/'</span> });
req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'response'</span>, <span class="hljs-function">(<span class="hljs-params">headers</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(headers[<span class="hljs-title class_">HTTP2</span>_HEADER_STATUS]);
  req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> { <span class="hljs-comment">/* .. */</span> });
  req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> { <span class="hljs-comment">/* .. */</span> });
});</code><button class="copy-button">copy</button></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>When <code>options.signal</code> is set with an <code>AbortSignal</code> and then <code>abort</code> on the
corresponding <code>AbortController</code> is called, the request will emit an <code>'error'</code>
event with an <code>AbortError</code> error.</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>
<h4>Class: <code>Http2Stream</code><span><a class="mark" href="#all_http2_class-http2stream" id="all_http2_class-http2stream">#</a></span><a aria-hidden="true" class="legacy" id="http2_class_http2stream"></a></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li>Extends: <a href="#all_stream_class-streamduplex" 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="#all_http2_class-serverhttp2stream"><code>ServerHttp2Stream</code></a> and
<a href="#all_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="#all_stream_class-streamduplex"><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>
<p>The default text character encoding for an <code>Http2Stream</code> is UTF-8. When using an
<code>Http2Stream</code> to send text, use the <code>'content-type'</code> header to set the character
encoding.</p>
<pre><code class="language-js">stream.<span class="hljs-title function_">respond</span>({
  <span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/html; charset=utf-8'</span>,
  <span class="hljs-string">':status'</span>: <span class="hljs-number">200</span>,
});</code> <button class="copy-button">copy</button></pre>
<h5><code>Http2Stream</code> Lifecycle<span><a class="mark" href="#all_http2_http2stream-lifecycle" id="all_http2_http2stream-lifecycle">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_lifecycle"></a></h5>
<h6>Creation<span><a class="mark" href="#all_http2_creation" id="all_http2_creation">#</a></span><a aria-hidden="true" class="legacy" id="http2_creation"></a></h6>
<p>On the server side, instances of <a href="#all_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="#all_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>
<h6>Destruction<span><a class="mark" href="#all_http2_destruction" id="all_http2_destruction">#</a></span><a aria-hidden="true" class="legacy" id="http2_destruction"></a></h6>
<p>All <a href="#all_http2_class-http2stream"><code>Http2Stream</code></a> instances are destroyed either when:</p>
<ul>
<li>An <code>RST_STREAM</code> frame for the stream is received by the connected peer,
and (for client streams only) pending data has been read.</li>
<li>The <code>http2stream.close()</code> method is called, and (for client streams only)
pending data has been read.</li>
<li>The <code>http2stream.destroy()</code> or <code>http2session.destroy()</code> methods are called.</li>
</ul>
<p>When an <code>Http2Stream</code> instance is destroyed, an attempt will be made to send an
<code>RST_STREAM</code> frame 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>
<h5>Event: <code>'aborted'</code><span><a class="mark" href="#all_http2_event-aborted" id="all_http2_event-aborted">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_aborted"></a></h5>
<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>
<h5>Event: <code>'close'</code><span><a class="mark" href="#all_http2_event-close_1" id="all_http2_event-close_1">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_close_1"></a></h5>
<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>
<h5>Event: <code>'error'</code><span><a class="mark" href="#all_http2_event-error_1" id="all_http2_event-error_1">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_error_1"></a></h5>
<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>
<h5>Event: <code>'frameError'</code><span><a class="mark" href="#all_http2_event-frameerror_1" id="all_http2_event-frameerror_1">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_frameerror_1"></a></h5>
<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>
<h5>Event: <code>'ready'</code><span><a class="mark" href="#all_http2_event-ready" id="all_http2_event-ready">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_ready"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<p>The <code>'ready'</code> event is emitted when the <code>Http2Stream</code> has been opened, has
been assigned an <code>id</code>, and can be used. The listener does not expect any
arguments.</p>
<h5>Event: <code>'timeout'</code><span><a class="mark" href="#all_http2_event-timeout_1" id="all_http2_event-timeout_1">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_timeout_1"></a></h5>
<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>
<h5>Event: <code>'trailers'</code><span><a class="mark" href="#all_http2_event-trailers" id="all_http2_event-trailers">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_trailers"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>headers</code> <a href="#all_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="#all_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.<span class="hljs-title function_">on</span>(<span class="hljs-string">'trailers'</span>, <span class="hljs-function">(<span class="hljs-params">headers, flags</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(headers);
});</code> <button class="copy-button">copy</button></pre>
<h5>Event: <code>'wantTrailers'</code><span><a class="mark" href="#all_http2_event-wanttrailers" id="all_http2_event-wanttrailers">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_wanttrailers"></a></h5>
<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>
<h5><code>http2stream.aborted</code><span><a class="mark" href="#all_http2_http2streamaborted" id="all_http2_http2streamaborted">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_aborted"></a></h5>
<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>
<h5><code>http2stream.bufferSize</code><span><a class="mark" href="#all_http2_http2streambuffersize" id="all_http2_http2streambuffersize">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_buffersize"></a></h5>
<div class="api_metadata">
<span>Added in: v11.2.0, v10.16.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="#all_net_socketbuffersize"><code>net.Socket.bufferSize</code></a> for details.</p>
<h5><code>http2stream.close(code[, callback])</code><span><a class="mark" href="#all_http2_http2streamclosecode-callback" id="all_http2_http2streamclosecode-callback">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_close_code_callback"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</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>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>
<h5><code>http2stream.closed</code><span><a class="mark" href="#all_http2_http2streamclosed" id="all_http2_http2streamclosed">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_closed"></a></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>Set to <code>true</code> if the <code>Http2Stream</code> instance has been closed.</p>
<h5><code>http2stream.destroyed</code><span><a class="mark" href="#all_http2_http2streamdestroyed" id="all_http2_http2streamdestroyed">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_destroyed"></a></h5>
<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>
<h5><code>http2stream.endAfterHeaders</code><span><a class="mark" href="#all_http2_http2streamendafterheaders" id="all_http2_http2streamendafterheaders">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_endafterheaders"></a></h5>
<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 to <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>
<h5><code>http2stream.id</code><span><a class="mark" href="#all_http2_http2streamid" id="all_http2_http2streamid">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_id"></a></h5>
<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>
<h5><code>http2stream.pending</code><span><a class="mark" href="#all_http2_http2streampending" id="all_http2_http2streampending">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_pending"></a></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>Set to <code>true</code> if the <code>Http2Stream</code> instance has not yet been assigned a
numeric stream identifier.</p>
<h5><code>http2stream.priority(options)</code><span><a class="mark" href="#all_http2_http2streampriorityoptions" id="all_http2_http2streampriorityoptions">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_priority_options"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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>
<h5><code>http2stream.rstCode</code><span><a class="mark" href="#all_http2_http2streamrstcode" id="all_http2_http2streamrstcode">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_rstcode"></a></h5>
<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="#all_http2_error-codes-for-rst_stream-and-goaway">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>
<h5><code>http2stream.sentHeaders</code><span><a class="mark" href="#all_http2_http2streamsentheaders" id="all_http2_http2streamsentheaders">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_sentheaders"></a></h5>
<div class="api_metadata">
<span>Added in: v9.5.0</span>
</div>
<ul>
<li><a href="#all_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>
<h5><code>http2stream.sentInfoHeaders</code><span><a class="mark" href="#all_http2_http2streamsentinfoheaders" id="all_http2_http2streamsentinfoheaders">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_sentinfoheaders"></a></h5>
<div class="api_metadata">
<span>Added in: v9.5.0</span>
</div>
<ul>
<li><a href="#all_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>
<h5><code>http2stream.sentTrailers</code><span><a class="mark" href="#all_http2_http2streamsenttrailers" id="all_http2_http2streamsenttrailers">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_senttrailers"></a></h5>
<div class="api_metadata">
<span>Added in: v9.5.0</span>
</div>
<ul>
<li><a href="#all_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>
<h5><code>http2stream.session</code><span><a class="mark" href="#all_http2_http2streamsession" id="all_http2_http2streamsession">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_session"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="#all_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>
<h5><code>http2stream.setTimeout(msecs, callback)</code><span><a class="mark" href="#all_http2_http2streamsettimeoutmsecs-callback" id="all_http2_http2streamsettimeoutmsecs-callback">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_settimeout_msecs_callback"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</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>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 class="with-56-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { connect, constants } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> client = <span class="hljs-title function_">connect</span>(<span class="hljs-string">'http://example.org:8000'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">NGHTTP2</span>_CANCEL } = constants;
<span class="hljs-keyword">const</span> req = client.<span class="hljs-title function_">request</span>({ <span class="hljs-string">':path'</span>: <span class="hljs-string">'/'</span> });

<span class="hljs-comment">// Cancel the stream if there's no activity after 5 seconds</span>
req.<span class="hljs-built_in">setTimeout</span>(<span class="hljs-number">5000</span>, <span class="hljs-function">() =></span> req.<span class="hljs-title function_">close</span>(<span class="hljs-title class_">NGHTTP2</span>_CANCEL));</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> client = http2.<span class="hljs-title function_">connect</span>(<span class="hljs-string">'http://example.org:8000'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">NGHTTP2</span>_CANCEL } = http2.<span class="hljs-property">constants</span>;
<span class="hljs-keyword">const</span> req = client.<span class="hljs-title function_">request</span>({ <span class="hljs-string">':path'</span>: <span class="hljs-string">'/'</span> });

<span class="hljs-comment">// Cancel the stream if there's no activity after 5 seconds</span>
req.<span class="hljs-built_in">setTimeout</span>(<span class="hljs-number">5000</span>, <span class="hljs-function">() =></span> req.<span class="hljs-title function_">close</span>(<span class="hljs-title class_">NGHTTP2</span>_CANCEL));</code><button class="copy-button">copy</button></pre>
<h5><code>http2stream.state</code><span><a class="mark" href="#all_http2_http2streamstate" id="all_http2_http2streamstate">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_state"></a></h5>
<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><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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>
<h5><code>http2stream.sendTrailers(headers)</code><span><a class="mark" href="#all_http2_http2streamsendtrailersheaders" id="all_http2_http2streamsendtrailersheaders">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_sendtrailers_headers"></a></h5>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<ul>
<li><code>headers</code> <a href="#all_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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
  stream.<span class="hljs-title function_">respond</span>(<span class="hljs-literal">undefined</span>, { <span class="hljs-attr">waitForTrailers</span>: <span class="hljs-literal">true</span> });
  stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'wantTrailers'</span>, <span class="hljs-function">() =></span> {
    stream.<span class="hljs-title function_">sendTrailers</span>({ <span class="hljs-attr">xyz</span>: <span class="hljs-string">'abc'</span> });
  });
  stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'Hello World'</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
  stream.<span class="hljs-title function_">respond</span>(<span class="hljs-literal">undefined</span>, { <span class="hljs-attr">waitForTrailers</span>: <span class="hljs-literal">true</span> });
  stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'wantTrailers'</span>, <span class="hljs-function">() =></span> {
    stream.<span class="hljs-title function_">sendTrailers</span>({ <span class="hljs-attr">xyz</span>: <span class="hljs-string">'abc'</span> });
  });
  stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'Hello World'</span>);
});</code><button class="copy-button">copy</button></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>
<h4>Class: <code>ClientHttp2Stream</code><span><a class="mark" href="#all_http2_class-clienthttp2stream" id="all_http2_class-clienthttp2stream">#</a></span><a aria-hidden="true" class="legacy" id="http2_class_clienthttp2stream"></a></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li>Extends <a href="#all_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>
<h5>Event: <code>'continue'</code><span><a class="mark" href="#all_http2_event-continue" id="all_http2_event-continue">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_continue"></a></h5>
<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>
<h5>Event: <code>'headers'</code><span><a class="mark" href="#all_http2_event-headers" id="all_http2_event-headers">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_headers"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>headers</code> <a href="#all_http2_headers-object" class="type">&#x3C;HTTP/2 Headers Object></a></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></li>
</ul>
<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="#all_http2_headers-object">HTTP/2 Headers Object</a> and flags
associated with the headers.</p>
<pre><code class="language-js">stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'headers'</span>, <span class="hljs-function">(<span class="hljs-params">headers, flags</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(headers);
});</code> <button class="copy-button">copy</button></pre>
<h5>Event: <code>'push'</code><span><a class="mark" href="#all_http2_event-push" id="all_http2_event-push">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_push"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>headers</code> <a href="#all_http2_headers-object" class="type">&#x3C;HTTP/2 Headers Object></a></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></li>
</ul>
<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="#all_http2_headers-object">HTTP/2 Headers Object</a> and
flags associated with the headers.</p>
<pre><code class="language-js">stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'push'</span>, <span class="hljs-function">(<span class="hljs-params">headers, flags</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(headers);
});</code> <button class="copy-button">copy</button></pre>
<h5>Event: <code>'response'</code><span><a class="mark" href="#all_http2_event-response" id="all_http2_event-response">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_response"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>headers</code> <a href="#all_http2_headers-object" class="type">&#x3C;HTTP/2 Headers Object></a></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></li>
</ul>
<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="#all_http2_headers-object">HTTP/2 Headers Object</a>, and flags associated with the headers.</p>

<pre class="with-50-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { connect } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> client = <span class="hljs-title function_">connect</span>(<span class="hljs-string">'https://localhost'</span>);
<span class="hljs-keyword">const</span> req = client.<span class="hljs-title function_">request</span>({ <span class="hljs-string">':path'</span>: <span class="hljs-string">'/'</span> });
req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'response'</span>, <span class="hljs-function">(<span class="hljs-params">headers, flags</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(headers[<span class="hljs-string">':status'</span>]);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> client = http2.<span class="hljs-title function_">connect</span>(<span class="hljs-string">'https://localhost'</span>);
<span class="hljs-keyword">const</span> req = client.<span class="hljs-title function_">request</span>({ <span class="hljs-string">':path'</span>: <span class="hljs-string">'/'</span> });
req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'response'</span>, <span class="hljs-function">(<span class="hljs-params">headers, flags</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(headers[<span class="hljs-string">':status'</span>]);
});</code><button class="copy-button">copy</button></pre>
<h4>Class: <code>ServerHttp2Stream</code><span><a class="mark" href="#all_http2_class-serverhttp2stream" id="all_http2_class-serverhttp2stream">#</a></span><a aria-hidden="true" class="legacy" id="http2_class_serverhttp2stream"></a></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li>Extends: <a href="#all_http2_class-http2stream" class="type">&#x3C;Http2Stream></a></li>
</ul>
<p>The <code>ServerHttp2Stream</code> class is an extension of <a href="#all_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>
<h5><code>http2stream.additionalHeaders(headers)</code><span><a class="mark" href="#all_http2_http2streamadditionalheadersheaders" id="all_http2_http2streamadditionalheadersheaders">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_additionalheaders_headers"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>headers</code> <a href="#all_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>
<h5><code>http2stream.headersSent</code><span><a class="mark" href="#all_http2_http2streamheaderssent" id="all_http2_http2streamheaderssent">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_headerssent"></a></h5>
<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>
<h5><code>http2stream.pushAllowed</code><span><a class="mark" href="#all_http2_http2streampushallowed" id="all_http2_http2streampushallowed">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_pushallowed"></a></h5>
<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>
<h5><code>http2stream.pushStream(headers[, options], callback)</code><span><a class="mark" href="#all_http2_http2streampushstreamheaders-options-callback" id="all_http2_http2streampushstreamheaders-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_pushstream_headers_options_callback"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</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>headers</code> <a href="#all_http2_headers-object" class="type">&#x3C;HTTP/2 Headers Object></a></li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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><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.
<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="#all_http2_class-serverhttp2stream" class="type">&#x3C;ServerHttp2Stream></a> The returned <code>pushStream</code> object.</li>
<li><code>headers</code> <a href="#all_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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
  stream.<span class="hljs-title function_">respond</span>({ <span class="hljs-string">':status'</span>: <span class="hljs-number">200</span> });
  stream.<span class="hljs-title function_">pushStream</span>({ <span class="hljs-string">':path'</span>: <span class="hljs-string">'/'</span> }, <span class="hljs-function">(<span class="hljs-params">err, pushStream, headers</span>) =></span> {
    <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
    pushStream.<span class="hljs-title function_">respond</span>({ <span class="hljs-string">':status'</span>: <span class="hljs-number">200</span> });
    pushStream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'some pushed data'</span>);
  });
  stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'some data'</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
  stream.<span class="hljs-title function_">respond</span>({ <span class="hljs-string">':status'</span>: <span class="hljs-number">200</span> });
  stream.<span class="hljs-title function_">pushStream</span>({ <span class="hljs-string">':path'</span>: <span class="hljs-string">'/'</span> }, <span class="hljs-function">(<span class="hljs-params">err, pushStream, headers</span>) =></span> {
    <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
    pushStream.<span class="hljs-title function_">respond</span>({ <span class="hljs-string">':status'</span>: <span class="hljs-number">200</span> });
    pushStream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'some pushed data'</span>);
  });
  stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'some data'</span>);
});</code><button class="copy-button">copy</button></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>
<h5><code>http2stream.respond([headers[, options]])</code><span><a class="mark" href="#all_http2_http2streamrespondheaders-options" id="all_http2_http2streamrespondheaders-options">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_respond_headers_options"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.5.0, v12.19.0</td>
<td><p>Allow explicitly setting date headers.</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>headers</code> <a href="#all_http2_headers-object" class="type">&#x3C;HTTP/2 Headers Object></a></li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
  stream.<span class="hljs-title function_">respond</span>({ <span class="hljs-string">':status'</span>: <span class="hljs-number">200</span> });
  stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'some data'</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
  stream.<span class="hljs-title function_">respond</span>({ <span class="hljs-string">':status'</span>: <span class="hljs-number">200</span> });
  stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'some data'</span>);
});</code><button class="copy-button">copy</button></pre>
<p>Initiates a response. 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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
  stream.<span class="hljs-title function_">respond</span>({ <span class="hljs-string">':status'</span>: <span class="hljs-number">200</span> }, { <span class="hljs-attr">waitForTrailers</span>: <span class="hljs-literal">true</span> });
  stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'wantTrailers'</span>, <span class="hljs-function">() =></span> {
    stream.<span class="hljs-title function_">sendTrailers</span>({ <span class="hljs-attr">ABC</span>: <span class="hljs-string">'some value to send'</span> });
  });
  stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'some data'</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
  stream.<span class="hljs-title function_">respond</span>({ <span class="hljs-string">':status'</span>: <span class="hljs-number">200</span> }, { <span class="hljs-attr">waitForTrailers</span>: <span class="hljs-literal">true</span> });
  stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'wantTrailers'</span>, <span class="hljs-function">() =></span> {
    stream.<span class="hljs-title function_">sendTrailers</span>({ <span class="hljs-attr">ABC</span>: <span class="hljs-string">'some value to send'</span> });
  });
  stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'some data'</span>);
});</code><button class="copy-button">copy</button></pre>
<h5><code>http2stream.respondWithFD(fd[, headers[, options]])</code><span><a class="mark" href="#all_http2_http2streamrespondwithfdfd-headers-options" id="all_http2_http2streamrespondwithfdfd-headers-options">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_respondwithfd_fd_headers_options"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.5.0, v12.19.0</td>
<td><p>Allow explicitly setting date headers.</p></td></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="#all_fs_class-filehandle" class="type">&#x3C;FileHandle></a> A readable file descriptor.</li>
<li><code>headers</code> <a href="#all_http2_headers-object" class="type">&#x3C;HTTP/2 Headers Object></a></li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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 class="with-57-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">import</span> { openSync, fstatSync, closeSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
  <span class="hljs-keyword">const</span> fd = <span class="hljs-title function_">openSync</span>(<span class="hljs-string">'/some/file'</span>, <span class="hljs-string">'r'</span>);

  <span class="hljs-keyword">const</span> stat = <span class="hljs-title function_">fstatSync</span>(fd);
  <span class="hljs-keyword">const</span> headers = {
    <span class="hljs-string">'content-length'</span>: stat.<span class="hljs-property">size</span>,
    <span class="hljs-string">'last-modified'</span>: stat.<span class="hljs-property">mtime</span>.<span class="hljs-title function_">toUTCString</span>(),
    <span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/plain; charset=utf-8'</span>,
  };
  stream.<span class="hljs-title function_">respondWithFD</span>(fd, headers);
  stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">() =></span> <span class="hljs-title function_">closeSync</span>(fd));
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);

<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
  <span class="hljs-keyword">const</span> fd = fs.<span class="hljs-title function_">openSync</span>(<span class="hljs-string">'/some/file'</span>, <span class="hljs-string">'r'</span>);

  <span class="hljs-keyword">const</span> stat = fs.<span class="hljs-title function_">fstatSync</span>(fd);
  <span class="hljs-keyword">const</span> headers = {
    <span class="hljs-string">'content-length'</span>: stat.<span class="hljs-property">size</span>,
    <span class="hljs-string">'last-modified'</span>: stat.<span class="hljs-property">mtime</span>.<span class="hljs-title function_">toUTCString</span>(),
    <span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/plain; charset=utf-8'</span>,
  };
  stream.<span class="hljs-title function_">respondWithFD</span>(fd, headers);
  stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">() =></span> fs.<span class="hljs-title function_">closeSync</span>(fd));
});</code><button class="copy-button">copy</button></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 class="with-57-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">import</span> { openSync, fstatSync, closeSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
  <span class="hljs-keyword">const</span> fd = <span class="hljs-title function_">openSync</span>(<span class="hljs-string">'/some/file'</span>, <span class="hljs-string">'r'</span>);

  <span class="hljs-keyword">const</span> stat = <span class="hljs-title function_">fstatSync</span>(fd);
  <span class="hljs-keyword">const</span> headers = {
    <span class="hljs-string">'content-length'</span>: stat.<span class="hljs-property">size</span>,
    <span class="hljs-string">'last-modified'</span>: stat.<span class="hljs-property">mtime</span>.<span class="hljs-title function_">toUTCString</span>(),
    <span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/plain; charset=utf-8'</span>,
  };
  stream.<span class="hljs-title function_">respondWithFD</span>(fd, headers, { <span class="hljs-attr">waitForTrailers</span>: <span class="hljs-literal">true</span> });
  stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'wantTrailers'</span>, <span class="hljs-function">() =></span> {
    stream.<span class="hljs-title function_">sendTrailers</span>({ <span class="hljs-attr">ABC</span>: <span class="hljs-string">'some value to send'</span> });
  });

  stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">() =></span> <span class="hljs-title function_">closeSync</span>(fd));
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);

<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
  <span class="hljs-keyword">const</span> fd = fs.<span class="hljs-title function_">openSync</span>(<span class="hljs-string">'/some/file'</span>, <span class="hljs-string">'r'</span>);

  <span class="hljs-keyword">const</span> stat = fs.<span class="hljs-title function_">fstatSync</span>(fd);
  <span class="hljs-keyword">const</span> headers = {
    <span class="hljs-string">'content-length'</span>: stat.<span class="hljs-property">size</span>,
    <span class="hljs-string">'last-modified'</span>: stat.<span class="hljs-property">mtime</span>.<span class="hljs-title function_">toUTCString</span>(),
    <span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/plain; charset=utf-8'</span>,
  };
  stream.<span class="hljs-title function_">respondWithFD</span>(fd, headers, { <span class="hljs-attr">waitForTrailers</span>: <span class="hljs-literal">true</span> });
  stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'wantTrailers'</span>, <span class="hljs-function">() =></span> {
    stream.<span class="hljs-title function_">sendTrailers</span>({ <span class="hljs-attr">ABC</span>: <span class="hljs-string">'some value to send'</span> });
  });

  stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">() =></span> fs.<span class="hljs-title function_">closeSync</span>(fd));
});</code><button class="copy-button">copy</button></pre>
<h5><code>http2stream.respondWithFile(path[, headers[, options]])</code><span><a class="mark" href="#all_http2_http2streamrespondwithfilepath-headers-options" id="all_http2_http2streamrespondwithfilepath-headers-options">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2stream_respondwithfile_path_headers_options"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.5.0, v12.19.0</td>
<td><p>Allow explicitly setting date headers.</p></td></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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></a></li>
<li><code>headers</code> <a href="#all_http2_headers-object" class="type">&#x3C;HTTP/2 Headers Object></a></li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
  <span class="hljs-keyword">function</span> <span class="hljs-title function_">statCheck</span>(<span class="hljs-params">stat, headers</span>) {
    headers[<span class="hljs-string">'last-modified'</span>] = stat.<span class="hljs-property">mtime</span>.<span class="hljs-title function_">toUTCString</span>();
  }

  <span class="hljs-keyword">function</span> <span class="hljs-title function_">onError</span>(<span class="hljs-params">err</span>) {
    <span class="hljs-comment">// stream.respond() can throw if the stream has been destroyed by</span>
    <span class="hljs-comment">// the other side.</span>
    <span class="hljs-keyword">try</span> {
      <span class="hljs-keyword">if</span> (err.<span class="hljs-property">code</span> === <span class="hljs-string">'ENOENT'</span>) {
        stream.<span class="hljs-title function_">respond</span>({ <span class="hljs-string">':status'</span>: <span class="hljs-number">404</span> });
      } <span class="hljs-keyword">else</span> {
        stream.<span class="hljs-title function_">respond</span>({ <span class="hljs-string">':status'</span>: <span class="hljs-number">500</span> });
      }
    } <span class="hljs-keyword">catch</span> (err) {
      <span class="hljs-comment">// Perform actual error handling.</span>
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err);
    }
    stream.<span class="hljs-title function_">end</span>();
  }

  stream.<span class="hljs-title function_">respondWithFile</span>(<span class="hljs-string">'/some/file'</span>,
                         { <span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/plain; charset=utf-8'</span> },
                         { statCheck, onError });
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
  <span class="hljs-keyword">function</span> <span class="hljs-title function_">statCheck</span>(<span class="hljs-params">stat, headers</span>) {
    headers[<span class="hljs-string">'last-modified'</span>] = stat.<span class="hljs-property">mtime</span>.<span class="hljs-title function_">toUTCString</span>();
  }

  <span class="hljs-keyword">function</span> <span class="hljs-title function_">onError</span>(<span class="hljs-params">err</span>) {
    <span class="hljs-comment">// stream.respond() can throw if the stream has been destroyed by</span>
    <span class="hljs-comment">// the other side.</span>
    <span class="hljs-keyword">try</span> {
      <span class="hljs-keyword">if</span> (err.<span class="hljs-property">code</span> === <span class="hljs-string">'ENOENT'</span>) {
        stream.<span class="hljs-title function_">respond</span>({ <span class="hljs-string">':status'</span>: <span class="hljs-number">404</span> });
      } <span class="hljs-keyword">else</span> {
        stream.<span class="hljs-title function_">respond</span>({ <span class="hljs-string">':status'</span>: <span class="hljs-number">500</span> });
      }
    } <span class="hljs-keyword">catch</span> (err) {
      <span class="hljs-comment">// Perform actual error handling.</span>
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err);
    }
    stream.<span class="hljs-title function_">end</span>();
  }

  stream.<span class="hljs-title function_">respondWithFile</span>(<span class="hljs-string">'/some/file'</span>,
                         { <span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/plain; charset=utf-8'</span> },
                         { statCheck, onError });
});</code><button class="copy-button">copy</button></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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
  <span class="hljs-keyword">function</span> <span class="hljs-title function_">statCheck</span>(<span class="hljs-params">stat, headers</span>) {
    <span class="hljs-comment">// Check the stat here...</span>
    stream.<span class="hljs-title function_">respond</span>({ <span class="hljs-string">':status'</span>: <span class="hljs-number">304</span> });
    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>; <span class="hljs-comment">// Cancel the send operation</span>
  }
  stream.<span class="hljs-title function_">respondWithFile</span>(<span class="hljs-string">'/some/file'</span>,
                         { <span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/plain; charset=utf-8'</span> },
                         { statCheck });
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
  <span class="hljs-keyword">function</span> <span class="hljs-title function_">statCheck</span>(<span class="hljs-params">stat, headers</span>) {
    <span class="hljs-comment">// Check the stat here...</span>
    stream.<span class="hljs-title function_">respond</span>({ <span class="hljs-string">':status'</span>: <span class="hljs-number">304</span> });
    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>; <span class="hljs-comment">// Cancel the send operation</span>
  }
  stream.<span class="hljs-title function_">respondWithFile</span>(<span class="hljs-string">'/some/file'</span>,
                         { <span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/plain; charset=utf-8'</span> },
                         { statCheck });
});</code><button class="copy-button">copy</button></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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
  stream.<span class="hljs-title function_">respondWithFile</span>(<span class="hljs-string">'/some/file'</span>,
                         { <span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/plain; charset=utf-8'</span> },
                         { <span class="hljs-attr">waitForTrailers</span>: <span class="hljs-literal">true</span> });
  stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'wantTrailers'</span>, <span class="hljs-function">() =></span> {
    stream.<span class="hljs-title function_">sendTrailers</span>({ <span class="hljs-attr">ABC</span>: <span class="hljs-string">'some value to send'</span> });
  });
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream</span>) =></span> {
  stream.<span class="hljs-title function_">respondWithFile</span>(<span class="hljs-string">'/some/file'</span>,
                         { <span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/plain; charset=utf-8'</span> },
                         { <span class="hljs-attr">waitForTrailers</span>: <span class="hljs-literal">true</span> });
  stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'wantTrailers'</span>, <span class="hljs-function">() =></span> {
    stream.<span class="hljs-title function_">sendTrailers</span>({ <span class="hljs-attr">ABC</span>: <span class="hljs-string">'some value to send'</span> });
  });
});</code><button class="copy-button">copy</button></pre>
<h4>Class: <code>Http2Server</code><span><a class="mark" href="#all_http2_class-http2server" id="all_http2_class-http2server">#</a></span><a aria-hidden="true" class="legacy" id="http2_class_http2server"></a></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li>Extends: <a href="#all_net_class-netserver" 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>node:http2</code> module.</p>
<h5>Event: <code>'checkContinue'</code><span><a class="mark" href="#all_http2_event-checkcontinue" id="all_http2_event-checkcontinue">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_checkcontinue"></a></h5>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div>
<ul>
<li><code>request</code> <a href="#all_http2_class-http2http2serverrequest" class="type">&#x3C;http2.Http2ServerRequest></a></li>
<li><code>response</code> <a href="#all_http2_class-http2http2serverresponse" class="type">&#x3C;http2.Http2ServerResponse></a></li>
</ul>
<p>If a <a href="#all_http2_event-request"><code>'request'</code></a> listener is registered or <a href="#all_http2_http2createserveroptions-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="#all_http2_responsewritecontinue"><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="#all_http2_event-request"><code>'request'</code></a> event will
not be emitted.</p>
<h5>Event: <code>'connection'</code><span><a class="mark" href="#all_http2_event-connection" id="all_http2_event-connection">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_connection"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>socket</code> <a href="#all_stream_class-streamduplex" 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="#all_net_class-netsocket"><code>net.Socket</code></a>. Usually users will not want to
access this event.</p>
<p>This event can also be explicitly emitted by users to inject connections
into the HTTP server. In that case, any <a href="#all_stream_class-streamduplex"><code>Duplex</code></a> stream can be passed.</p>
<h5>Event: <code>'request'</code><span><a class="mark" href="#all_http2_event-request" id="all_http2_event-request">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_request"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>request</code> <a href="#all_http2_class-http2http2serverrequest" class="type">&#x3C;http2.Http2ServerRequest></a></li>
<li><code>response</code> <a href="#all_http2_class-http2http2serverresponse" 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="#all_http2_compatibility-api">Compatibility API</a>.</p>
<h5>Event: <code>'session'</code><span><a class="mark" href="#all_http2_event-session" id="all_http2_event-session">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_session"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>session</code> <a href="#all_http2_class-serverhttp2session" class="type">&#x3C;ServerHttp2Session></a></li>
</ul>
<p>The <code>'session'</code> event is emitted when a new <code>Http2Session</code> is created by the
<code>Http2Server</code>.</p>
<h5>Event: <code>'sessionError'</code><span><a class="mark" href="#all_http2_event-sessionerror" id="all_http2_event-sessionerror">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_sessionerror"></a></h5>
<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>
<li><code>session</code> <a href="#all_http2_class-serverhttp2session" class="type">&#x3C;ServerHttp2Session></a></li>
</ul>
<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>
<h5>Event: <code>'stream'</code><span><a class="mark" href="#all_http2_event-stream_1" id="all_http2_event-stream_1">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_stream_1"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>stream</code> <a href="#all_http2_class-http2stream" class="type">&#x3C;Http2Stream></a> A reference to the stream</li>
<li><code>headers</code> <a href="#all_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 <code>'stream'</code> event has been emitted by
an <code>Http2Session</code> associated with the server.</p>
<p>See also <a href="#all_http2_event-stream"><code>Http2Session</code>'s <code>'stream'</code> event</a>.</p>

<pre class="with-53-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createServer, constants } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> {
  <span class="hljs-title class_">HTTP2</span>_HEADER_METHOD,
  <span class="hljs-title class_">HTTP2</span>_HEADER_PATH,
  <span class="hljs-title class_">HTTP2</span>_HEADER_STATUS,
  <span class="hljs-title class_">HTTP2</span>_HEADER_CONTENT_TYPE,
} = constants;

<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream, headers, flags</span>) =></span> {
  <span class="hljs-keyword">const</span> method = headers[<span class="hljs-title class_">HTTP2</span>_HEADER_METHOD];
  <span class="hljs-keyword">const</span> path = headers[<span class="hljs-title class_">HTTP2</span>_HEADER_PATH];
  <span class="hljs-comment">// ...</span>
  stream.<span class="hljs-title function_">respond</span>({
    [<span class="hljs-title class_">HTTP2</span>_HEADER_STATUS]: <span class="hljs-number">200</span>,
    [<span class="hljs-title class_">HTTP2</span>_HEADER_CONTENT_TYPE]: <span class="hljs-string">'text/plain; charset=utf-8'</span>,
  });
  stream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello '</span>);
  stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'world'</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> {
  <span class="hljs-title class_">HTTP2</span>_HEADER_METHOD,
  <span class="hljs-title class_">HTTP2</span>_HEADER_PATH,
  <span class="hljs-title class_">HTTP2</span>_HEADER_STATUS,
  <span class="hljs-title class_">HTTP2</span>_HEADER_CONTENT_TYPE,
} = http2.<span class="hljs-property">constants</span>;

<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream, headers, flags</span>) =></span> {
  <span class="hljs-keyword">const</span> method = headers[<span class="hljs-title class_">HTTP2</span>_HEADER_METHOD];
  <span class="hljs-keyword">const</span> path = headers[<span class="hljs-title class_">HTTP2</span>_HEADER_PATH];
  <span class="hljs-comment">// ...</span>
  stream.<span class="hljs-title function_">respond</span>({
    [<span class="hljs-title class_">HTTP2</span>_HEADER_STATUS]: <span class="hljs-number">200</span>,
    [<span class="hljs-title class_">HTTP2</span>_HEADER_CONTENT_TYPE]: <span class="hljs-string">'text/plain; charset=utf-8'</span>,
  });
  stream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello '</span>);
  stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'world'</span>);
});</code><button class="copy-button">copy</button></pre>
<h5>Event: <code>'timeout'</code><span><a class="mark" href="#all_http2_event-timeout_2" id="all_http2_event-timeout_2">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_timeout_2"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.0.0</td>
<td><p>The default timeout changed from 120s to 0 (no timeout).</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>'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> 0 (no timeout)</p>
<h5><code>server.close([callback])</code><span><a class="mark" href="#all_http2_serverclosecallback" id="all_http2_serverclosecallback">#</a></span><a aria-hidden="true" class="legacy" id="http2_server_close_callback"></a></h5>
<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="#all_http2_http2sessionclosecallback"><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="#all_net_serverclosecallback"><code>net.Server.close()</code></a> for more details.</p>
<h5><code>server[Symbol.asyncDispose]()</code><span><a class="mark" href="#all_http2_serversymbolasyncdispose" id="all_http2_serversymbolasyncdispose">#</a></span><a aria-hidden="true" class="legacy" id="http2_server_symbol_asyncdispose"></a></h5>
<div class="api_metadata">
<span>Added in: v20.4.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Calls <a href="#all_http2_serverclosecallback"><code>server.close()</code></a> and returns a promise that fulfills when the
server has closed.</p>
<h5><code>server.setTimeout([msecs][, callback])</code><span><a class="mark" href="#all_http2_serversettimeoutmsecs-callback" id="all_http2_serversettimeoutmsecs-callback">#</a></span><a aria-hidden="true" class="legacy" id="http2_server_settimeout_msecs_callback"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></tr>
<tr><td>v13.0.0</td>
<td><p>The default timeout changed from 120s to 0 (no timeout).</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>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> 0 (no timeout)</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="#all_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 if <code>callback</code> is not a function, a new <code>ERR_INVALID_ARG_TYPE</code>
error will be thrown.</p>
<h5><code>server.timeout</code><span><a class="mark" href="#all_http2_servertimeout" id="all_http2_servertimeout">#</a></span><a aria-hidden="true" class="legacy" id="http2_server_timeout"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.0.0</td>
<td><p>The default timeout changed from 120s to 0 (no timeout).</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><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> 0 (no timeout)</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>
<h5><code>server.updateSettings([settings])</code><span><a class="mark" href="#all_http2_serverupdatesettingssettings" id="all_http2_serverupdatesettingssettings">#</a></span><a aria-hidden="true" class="legacy" id="http2_server_updatesettings_settings"></a></h5>
<div class="api_metadata">
<span>Added in: v15.1.0, v14.17.0</span>
</div>
<ul>
<li><code>settings</code> <a href="#all_http2_settings-object" class="type">&#x3C;HTTP/2 Settings Object></a></li>
</ul>
<p>Used to update the server with the provided settings.</p>
<p>Throws <code>ERR_HTTP2_INVALID_SETTING_VALUE</code> for invalid <code>settings</code> values.</p>
<p>Throws <code>ERR_INVALID_ARG_TYPE</code> for invalid <code>settings</code> argument.</p>
<h4>Class: <code>Http2SecureServer</code><span><a class="mark" href="#all_http2_class-http2secureserver" id="all_http2_class-http2secureserver">#</a></span><a aria-hidden="true" class="legacy" id="http2_class_http2secureserver"></a></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li>Extends: <a href="#all_tls_class-tlsserver" 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>node:http2</code> module.</p>
<h5>Event: <code>'checkContinue'</code><span><a class="mark" href="#all_http2_event-checkcontinue_1" id="all_http2_event-checkcontinue_1">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_checkcontinue_1"></a></h5>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div>
<ul>
<li><code>request</code> <a href="#all_http2_class-http2http2serverrequest" class="type">&#x3C;http2.Http2ServerRequest></a></li>
<li><code>response</code> <a href="#all_http2_class-http2http2serverresponse" class="type">&#x3C;http2.Http2ServerResponse></a></li>
</ul>
<p>If a <a href="#all_http2_event-request"><code>'request'</code></a> listener is registered or <a href="#all_http2_http2createsecureserveroptions-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="#all_http2_responsewritecontinue"><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="#all_http2_event-request"><code>'request'</code></a> event will
not be emitted.</p>
<h5>Event: <code>'connection'</code><span><a class="mark" href="#all_http2_event-connection_1" id="all_http2_event-connection_1">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_connection_1"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>socket</code> <a href="#all_stream_class-streamduplex" class="type">&#x3C;stream.Duplex></a></li>
</ul>
<p>This event is emitted when a new TCP stream is established, before the TLS
handshake begins. <code>socket</code> is typically an object of type <a href="#all_net_class-netsocket"><code>net.Socket</code></a>.
Usually users will not want to access this event.</p>
<p>This event can also be explicitly emitted by users to inject connections
into the HTTP server. In that case, any <a href="#all_stream_class-streamduplex"><code>Duplex</code></a> stream can be passed.</p>
<h5>Event: <code>'request'</code><span><a class="mark" href="#all_http2_event-request_1" id="all_http2_event-request_1">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_request_1"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>request</code> <a href="#all_http2_class-http2http2serverrequest" class="type">&#x3C;http2.Http2ServerRequest></a></li>
<li><code>response</code> <a href="#all_http2_class-http2http2serverresponse" 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="#all_http2_compatibility-api">Compatibility API</a>.</p>
<h5>Event: <code>'session'</code><span><a class="mark" href="#all_http2_event-session_1" id="all_http2_event-session_1">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_session_1"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>session</code> <a href="#all_http2_class-serverhttp2session" class="type">&#x3C;ServerHttp2Session></a></li>
</ul>
<p>The <code>'session'</code> event is emitted when a new <code>Http2Session</code> is created by the
<code>Http2SecureServer</code>.</p>
<h5>Event: <code>'sessionError'</code><span><a class="mark" href="#all_http2_event-sessionerror_1" id="all_http2_event-sessionerror_1">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_sessionerror_1"></a></h5>
<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>
<li><code>session</code> <a href="#all_http2_class-serverhttp2session" class="type">&#x3C;ServerHttp2Session></a></li>
</ul>
<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>
<h5>Event: <code>'stream'</code><span><a class="mark" href="#all_http2_event-stream_2" id="all_http2_event-stream_2">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_stream_2"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>stream</code> <a href="#all_http2_class-http2stream" class="type">&#x3C;Http2Stream></a> A reference to the stream</li>
<li><code>headers</code> <a href="#all_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 <code>'stream'</code> event has been emitted by
an <code>Http2Session</code> associated with the server.</p>
<p>See also <a href="#all_http2_event-stream"><code>Http2Session</code>'s <code>'stream'</code> event</a>.</p>

<pre class="with-59-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createSecureServer, constants } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> {
  <span class="hljs-title class_">HTTP2</span>_HEADER_METHOD,
  <span class="hljs-title class_">HTTP2</span>_HEADER_PATH,
  <span class="hljs-title class_">HTTP2</span>_HEADER_STATUS,
  <span class="hljs-title class_">HTTP2</span>_HEADER_CONTENT_TYPE,
} = constants;

<span class="hljs-keyword">const</span> options = <span class="hljs-title function_">getOptionsSomehow</span>();

<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createSecureServer</span>(options);
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream, headers, flags</span>) =></span> {
  <span class="hljs-keyword">const</span> method = headers[<span class="hljs-title class_">HTTP2</span>_HEADER_METHOD];
  <span class="hljs-keyword">const</span> path = headers[<span class="hljs-title class_">HTTP2</span>_HEADER_PATH];
  <span class="hljs-comment">// ...</span>
  stream.<span class="hljs-title function_">respond</span>({
    [<span class="hljs-title class_">HTTP2</span>_HEADER_STATUS]: <span class="hljs-number">200</span>,
    [<span class="hljs-title class_">HTTP2</span>_HEADER_CONTENT_TYPE]: <span class="hljs-string">'text/plain; charset=utf-8'</span>,
  });
  stream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello '</span>);
  stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'world'</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> {
  <span class="hljs-title class_">HTTP2</span>_HEADER_METHOD,
  <span class="hljs-title class_">HTTP2</span>_HEADER_PATH,
  <span class="hljs-title class_">HTTP2</span>_HEADER_STATUS,
  <span class="hljs-title class_">HTTP2</span>_HEADER_CONTENT_TYPE,
} = http2.<span class="hljs-property">constants</span>;

<span class="hljs-keyword">const</span> options = <span class="hljs-title function_">getOptionsSomehow</span>();

<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createSecureServer</span>(options);
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream, headers, flags</span>) =></span> {
  <span class="hljs-keyword">const</span> method = headers[<span class="hljs-title class_">HTTP2</span>_HEADER_METHOD];
  <span class="hljs-keyword">const</span> path = headers[<span class="hljs-title class_">HTTP2</span>_HEADER_PATH];
  <span class="hljs-comment">// ...</span>
  stream.<span class="hljs-title function_">respond</span>({
    [<span class="hljs-title class_">HTTP2</span>_HEADER_STATUS]: <span class="hljs-number">200</span>,
    [<span class="hljs-title class_">HTTP2</span>_HEADER_CONTENT_TYPE]: <span class="hljs-string">'text/plain; charset=utf-8'</span>,
  });
  stream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello '</span>);
  stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'world'</span>);
});</code><button class="copy-button">copy</button></pre>
<h5>Event: <code>'timeout'</code><span><a class="mark" href="#all_http2_event-timeout_3" id="all_http2_event-timeout_3">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_timeout_3"></a></h5>
<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>
<h5>Event: <code>'unknownProtocol'</code><span><a class="mark" href="#all_http2_event-unknownprotocol" id="all_http2_event-unknownprotocol">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_unknownprotocol"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>This event will only be emitted if the client did not transmit an ALPN extension during the TLS handshake.</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>socket</code> <a href="#all_stream_class-streamduplex" class="type">&#x3C;stream.Duplex></a></li>
</ul>
<p>The <code>'unknownProtocol'</code> event is emitted when a connecting client fails to
negotiate an allowed protocol (i.e. HTTP/2 or HTTP/1.1). The event handler
receives the socket for handling. If no listener is registered for this event,
the connection is terminated. A timeout may be specified using the
<code>'unknownProtocolTimeout'</code> option passed to <a href="#all_http2_http2createsecureserveroptions-onrequesthandler"><code>http2.createSecureServer()</code></a>.</p>
<p>In earlier versions of Node.js, this event would be emitted if <code>allowHTTP1</code> is
<code>false</code> and, during the TLS handshake, the client either does not send an ALPN
extension or sends an ALPN extension that does not include HTTP/2 (<code>h2</code>). Newer
versions of Node.js only emit this event if <code>allowHTTP1</code> is <code>false</code> and the
client does not send an ALPN extension. If the client sends an ALPN extension
that does not include HTTP/2 (or HTTP/1.1 if <code>allowHTTP1</code> is <code>true</code>), the TLS
handshake will fail and no secure connection will be established.</p>
<p>See the <a href="#all_http2_compatibility-api">Compatibility API</a>.</p>
<h5><code>server.close([callback])</code><span><a class="mark" href="#all_http2_serverclosecallback_1" id="all_http2_serverclosecallback_1">#</a></span><a aria-hidden="true" class="legacy" id="http2_server_close_callback_1"></a></h5>
<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="#all_http2_http2sessionclosecallback"><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="#all_tls_serverclosecallback"><code>tls.Server.close()</code></a> for more details.</p>
<h5><code>server.setTimeout([msecs][, callback])</code><span><a class="mark" href="#all_http2_serversettimeoutmsecs-callback_1" id="all_http2_serversettimeoutmsecs-callback_1">#</a></span><a aria-hidden="true" class="legacy" id="http2_server_settimeout_msecs_callback_1"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</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>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="#all_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 if <code>callback</code> is not a function, a new <code>ERR_INVALID_ARG_TYPE</code>
error will be thrown.</p>
<h5><code>server.timeout</code><span><a class="mark" href="#all_http2_servertimeout_1" id="all_http2_servertimeout_1">#</a></span><a aria-hidden="true" class="legacy" id="http2_server_timeout_1"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.0.0</td>
<td><p>The default timeout changed from 120s to 0 (no timeout).</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><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> 0 (no timeout)</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>
<h5><code>server.updateSettings([settings])</code><span><a class="mark" href="#all_http2_serverupdatesettingssettings_1" id="all_http2_serverupdatesettingssettings_1">#</a></span><a aria-hidden="true" class="legacy" id="http2_server_updatesettings_settings_1"></a></h5>
<div class="api_metadata">
<span>Added in: v15.1.0, v14.17.0</span>
</div>
<ul>
<li><code>settings</code> <a href="#all_http2_settings-object" class="type">&#x3C;HTTP/2 Settings Object></a></li>
</ul>
<p>Used to update the server with the provided settings.</p>
<p>Throws <code>ERR_HTTP2_INVALID_SETTING_VALUE</code> for invalid <code>settings</code> values.</p>
<p>Throws <code>ERR_INVALID_ARG_TYPE</code> for invalid <code>settings</code> argument.</p>
<h4><code>http2.createServer([options][, onRequestHandler])</code><span><a class="mark" href="#all_http2_http2createserveroptions-onrequesthandler" id="all_http2_http2createserveroptions-onrequesthandler">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2_createserver_options_onrequesthandler"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.0.0</td>
<td><p>The <code>PADDING_STRATEGY_CALLBACK</code> has been made equivalent to providing <code>PADDING_STRATEGY_ALIGNED</code> and <code>selectPadding</code> has been removed.</p></td></tr>
<tr><td>v13.3.0, v12.16.0</td>
<td><p>Added <code>maxSessionRejectedStreams</code> option with a default of 100.</p></td></tr>
<tr><td>v13.3.0, 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>v15.10.0, v14.16.0, v12.21.0, v10.24.0</td>
<td><p>Added <code>unknownProtocolTimeout</code> option with a default of 10000.</p></td></tr>
<tr><td>v14.4.0, v12.18.0, v10.21.0</td>
<td><p>Added <code>maxSettings</code> option with a default of 32.</p></td></tr>
<tr><td>v9.6.0</td>
<td><p>Added the <code>Http1IncomingMessage</code> and <code>Http1ServerResponse</code> option.</p></td></tr>
<tr><td>v8.9.3</td>
<td><p>Added the <code>maxOutstandingPings</code> option with a default limit of 10.</p></td></tr>
<tr><td>v8.9.3</td>
<td><p>Added the <code>maxHeaderListPairs</code> option with a default limit of 128 header pairs.</p></td></tr>
<tr><td>v8.4.0</td>
<td><p><span>Added in: v8.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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="#all_http_servermaxheaderscount"><code>server.maxHeadersCount</code></a> or
<a href="#all_http_requestmaxheaderscount"><code>request.maxHeadersCount</code></a> in the <code>node:http</code> module. 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.
While this sets the maximum allowed size to the entire block of headers,
<code>nghttp2</code> (the internal http2 library) has a limit of <code>65536</code>
for each decompressed key/value pair.</li>
<li><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:
<ul>
<li><code>http2.constants.PADDING_STRATEGY_NONE</code>: No padding is applied.</li>
<li><code>http2.constants.PADDING_STRATEGY_MAX</code>: The maximum amount of padding,
determined by the internal implementation, is applied.</li>
<li><code>http2.constants.PADDING_STRATEGY_ALIGNED</code>: Attempts to apply enough
padding to ensure that the total frame length, including the 9-byte
header, is a multiple of 8. For each frame, 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 is used and the total frame length is not
necessarily 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>settings</code> <a href="#all_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>remoteCustomSettings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type">&#x3C;Array></a> The array of integer values determines the
settings types, which are included in the <code>CustomSettings</code>-property of
the received remoteSettings. Please see the <code>CustomSettings</code>-property of
the <code>Http2Settings</code> object for more information,
on the allowed setting types.</li>
<li><code>Http1IncomingMessage</code> <a href="#all_http_class-httpincomingmessage" 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="#all_http_class-httpserverresponse" 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="#all_http2_class-http2http2serverrequest" 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="#all_http2_class-http2http2serverresponse" 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><code>unknownProtocolTimeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Specifies a timeout in milliseconds that
a server should wait when an <a href="#all_http2_event-unknownprotocol"><code>'unknownProtocol'</code></a> is emitted. If the
socket has not been destroyed by that time the server will destroy it.
<strong>Default:</strong> <code>10000</code>.</li>
<li>...: Any <a href="#all_net_netcreateserveroptions-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="#all_http2_compatibility-api">Compatibility API</a></li>
<li>Returns: <a href="#all_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="#all_http2_http2createsecureserveroptions-onrequesthandler"><code>http2.createSecureServer()</code></a> is necessary when communicating
with browser clients.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;

<span class="hljs-comment">// Create an unencrypted HTTP/2 server.</span>
<span class="hljs-comment">// Since there are no browsers known that support</span>
<span class="hljs-comment">// unencrypted HTTP/2, the use of `createSecureServer()`</span>
<span class="hljs-comment">// is necessary when communicating with browser clients.</span>
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>();

server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream, headers</span>) =></span> {
  stream.<span class="hljs-title function_">respond</span>({
    <span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/html; charset=utf-8'</span>,
    <span class="hljs-string">':status'</span>: <span class="hljs-number">200</span>,
  });
  stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'&#x3C;h1>Hello World&#x3C;/h1>'</span>);
});

server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);

<span class="hljs-comment">// Create an unencrypted HTTP/2 server.</span>
<span class="hljs-comment">// Since there are no browsers known that support</span>
<span class="hljs-comment">// unencrypted HTTP/2, the use of `http2.createSecureServer()`</span>
<span class="hljs-comment">// is necessary when communicating with browser clients.</span>
<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createServer</span>();

server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream, headers</span>) =></span> {
  stream.<span class="hljs-title function_">respond</span>({
    <span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/html; charset=utf-8'</span>,
    <span class="hljs-string">':status'</span>: <span class="hljs-number">200</span>,
  });
  stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'&#x3C;h1>Hello World&#x3C;/h1>'</span>);
});

server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);</code><button class="copy-button">copy</button></pre>
<h4><code>http2.createSecureServer(options[, onRequestHandler])</code><span><a class="mark" href="#all_http2_http2createsecureserveroptions-onrequesthandler" id="all_http2_http2createsecureserveroptions-onrequesthandler">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2_createsecureserver_options_onrequesthandler"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.0.0</td>
<td><p>The <code>PADDING_STRATEGY_CALLBACK</code> has been made equivalent to providing <code>PADDING_STRATEGY_ALIGNED</code> and <code>selectPadding</code> has been removed.</p></td></tr>
<tr><td>v13.3.0, v12.16.0</td>
<td><p>Added <code>maxSessionRejectedStreams</code> option with a default of 100.</p></td></tr>
<tr><td>v13.3.0, v12.16.0</td>
<td><p>Added <code>maxSessionInvalidFrames</code> option with a default of 1000.</p></td></tr>
<tr><td>v15.10.0, v14.16.0, v12.21.0, v10.24.0</td>
<td><p>Added <code>unknownProtocolTimeout</code> option with a default of 10000.</p></td></tr>
<tr><td>v14.4.0, v12.18.0, v10.21.0</td>
<td><p>Added <code>maxSettings</code> option with a default of 32.</p></td></tr>
<tr><td>v10.12.0</td>
<td><p>Added the <code>origins</code> option to automatically send an <code>ORIGIN</code> frame on <code>Http2Session</code> startup.</p></td></tr>
<tr><td>v8.9.3</td>
<td><p>Added the <code>maxOutstandingPings</code> option with a default limit of 10.</p></td></tr>
<tr><td>v8.9.3</td>
<td><p>Added the <code>maxHeaderListPairs</code> option with a default limit of 128 header pairs.</p></td></tr>
<tr><td>v8.4.0</td>
<td><p><span>Added in: v8.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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="#all_http2_event-unknownprotocol"><code>'unknownProtocol'</code></a> event. See <a href="#all_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="#all_http_servermaxheaderscount"><code>server.maxHeadersCount</code></a> or
<a href="#all_http_requestmaxheaderscount"><code>request.maxHeadersCount</code></a> in the <code>node:http</code> module. 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><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:
<ul>
<li><code>http2.constants.PADDING_STRATEGY_NONE</code>: No padding is applied.</li>
<li><code>http2.constants.PADDING_STRATEGY_MAX</code>: The maximum amount of padding,
determined by the internal implementation, is applied.</li>
<li><code>http2.constants.PADDING_STRATEGY_ALIGNED</code>: Attempts to apply enough
padding to ensure that the total frame length, including the
9-byte header, is a multiple of 8. For each frame, 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 is used and the total frame length
is not necessarily 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>settings</code> <a href="#all_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>remoteCustomSettings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type">&#x3C;Array></a> The array of integer values determines the
settings types, which are included in the <code>customSettings</code>-property of the
received remoteSettings. Please see the <code>customSettings</code>-property of the
<code>Http2Settings</code> object for more information, on the allowed setting types.</li>
<li>...: Any <a href="#all_tls_tlscreateserveroptions-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>
<li><code>unknownProtocolTimeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Specifies a timeout in milliseconds that
a server should wait when an <a href="#all_http2_event-unknownprotocol"><code>'unknownProtocol'</code></a> event is emitted. If
the socket has not been destroyed by that time the server will destroy it.
<strong>Default:</strong> <code>10000</code>.</li>
</ul>
</li>
<li><code>onRequestHandler</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> See <a href="#all_http2_compatibility-api">Compatibility API</a></li>
<li>Returns: <a href="#all_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 class="with-48-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createSecureServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">import</span> { readFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-keyword">const</span> options = {
  <span class="hljs-attr">key</span>: <span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'server-key.pem'</span>),
  <span class="hljs-attr">cert</span>: <span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'server-cert.pem'</span>),
};

<span class="hljs-comment">// Create a secure HTTP/2 server</span>
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createSecureServer</span>(options);

server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream, headers</span>) =></span> {
  stream.<span class="hljs-title function_">respond</span>({
    <span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/html; charset=utf-8'</span>,
    <span class="hljs-string">':status'</span>: <span class="hljs-number">200</span>,
  });
  stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'&#x3C;h1>Hello World&#x3C;/h1>'</span>);
});

server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8443</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);

<span class="hljs-keyword">const</span> options = {
  <span class="hljs-attr">key</span>: fs.<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'server-key.pem'</span>),
  <span class="hljs-attr">cert</span>: fs.<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'server-cert.pem'</span>),
};

<span class="hljs-comment">// Create a secure HTTP/2 server</span>
<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createSecureServer</span>(options);

server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream, headers</span>) =></span> {
  stream.<span class="hljs-title function_">respond</span>({
    <span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text/html; charset=utf-8'</span>,
    <span class="hljs-string">':status'</span>: <span class="hljs-number">200</span>,
  });
  stream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'&#x3C;h1>Hello World&#x3C;/h1>'</span>);
});

server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8443</span>);</code><button class="copy-button">copy</button></pre>
<h4><code>http2.connect(authority[, options][, listener])</code><span><a class="mark" href="#all_http2_http2connectauthority-options-listener" id="all_http2_http2connectauthority-options-listener">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2_connect_authority_options_listener"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.0.0</td>
<td><p>The <code>PADDING_STRATEGY_CALLBACK</code> has been made equivalent to providing <code>PADDING_STRATEGY_ALIGNED</code> and <code>selectPadding</code> has been removed.</p></td></tr>
<tr><td>v15.10.0, v14.16.0, v12.21.0, v10.24.0</td>
<td><p>Added <code>unknownProtocolTimeout</code> option with a default of 10000.</p></td></tr>
<tr><td>v14.4.0, v12.18.0, v10.21.0</td>
<td><p>Added <code>maxSettings</code> option with a default of 32.</p></td></tr>
<tr><td>v8.9.3</td>
<td><p>Added the <code>maxOutstandingPings</code> option with a default limit of 10.</p></td></tr>
<tr><td>v8.9.3</td>
<td><p>Added the <code>maxHeaderListPairs</code> option with a default limit of 128 header pairs.</p></td></tr>
<tr><td>v8.4.0</td>
<td><p><span>Added in: v8.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>authority</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#all_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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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="#all_http_servermaxheaderscount"><code>server.maxHeadersCount</code></a> or
<a href="#all_http_requestmaxheaderscount"><code>request.maxHeadersCount</code></a> in the <code>node:http</code> module. 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><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:
<ul>
<li><code>http2.constants.PADDING_STRATEGY_NONE</code>: No padding is applied.</li>
<li><code>http2.constants.PADDING_STRATEGY_MAX</code>: The maximum amount of padding,
determined by the internal implementation, is applied.</li>
<li><code>http2.constants.PADDING_STRATEGY_ALIGNED</code>: Attempts to apply enough
padding to ensure that the total frame length, including the
9-byte header, is a multiple of 8. For each frame, 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 is used and the total frame length
is not necessarily 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>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="#all_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>remoteCustomSettings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type">&#x3C;Array></a> The array of integer values determines the
settings types, which are included in the <code>CustomSettings</code>-property of the
received remoteSettings. Please see the <code>CustomSettings</code>-property of the
<code>Http2Settings</code> object for more information, on the allowed setting types.</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="#all_stream_class-streamduplex"><code>Duplex</code></a> stream that is to be used as the connection for this session.</li>
<li>...: Any <a href="#all_net_netconnect"><code>net.connect()</code></a> or <a href="#all_tls_tlsconnectoptions-callback"><code>tls.connect()</code></a> options can be provided.</li>
<li><code>unknownProtocolTimeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Specifies a timeout in milliseconds that
a server should wait when an <a href="#all_http2_event-unknownprotocol"><code>'unknownProtocol'</code></a> event is emitted. If
the socket has not been destroyed by that time the server will destroy it.
<strong>Default:</strong> <code>10000</code>.</li>
</ul>
</li>
<li><code>listener</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Will be registered as a one-time listener of the
<a href="#all_http2_event-connect"><code>'connect'</code></a> event.</li>
<li>Returns: <a href="#all_http2_class-clienthttp2session" class="type">&#x3C;ClientHttp2Session></a></li>
</ul>
<p>Returns a <code>ClientHttp2Session</code> instance.</p>

<pre class="with-55-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { connect } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> client = <span class="hljs-title function_">connect</span>(<span class="hljs-string">'https://localhost:1234'</span>);

<span class="hljs-comment">/* Use the client */</span>

client.<span class="hljs-title function_">close</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> client = http2.<span class="hljs-title function_">connect</span>(<span class="hljs-string">'https://localhost:1234'</span>);

<span class="hljs-comment">/* Use the client */</span>

client.<span class="hljs-title function_">close</span>();</code><button class="copy-button">copy</button></pre>
<h4><code>http2.constants</code><span><a class="mark" href="#all_http2_http2constants" id="all_http2_http2constants">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2_constants"></a></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<h5>Error codes for <code>RST_STREAM</code> and <code>GOAWAY</code><span><a class="mark" href="#all_http2_error-codes-for-rst_stream-and-goaway" id="all_http2_error-codes-for-rst_stream-and-goaway">#</a></span><a aria-hidden="true" class="legacy" id="http2_error_codes_for_rst_stream_and_goaway"></a></h5>
















































































<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>
<h4><code>http2.getDefaultSettings()</code><span><a class="mark" href="#all_http2_http2getdefaultsettings" id="all_http2_http2getdefaultsettings">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2_getdefaultsettings"></a></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li>Returns: <a href="#all_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>
<h4><code>http2.getPackedSettings([settings])</code><span><a class="mark" href="#all_http2_http2getpackedsettingssettings" id="all_http2_http2getpackedsettingssettings">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2_getpackedsettings_settings"></a></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>settings</code> <a href="#all_http2_settings-object" class="type">&#x3C;HTTP/2 Settings Object></a></li>
<li>Returns: <a href="#all_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 class="with-47-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { getPackedSettings } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;

<span class="hljs-keyword">const</span> packed = <span class="hljs-title function_">getPackedSettings</span>({ <span class="hljs-attr">enablePush</span>: <span class="hljs-literal">false</span> });

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(packed.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'base64'</span>));
<span class="hljs-comment">// Prints: AAIAAAAA</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);

<span class="hljs-keyword">const</span> packed = http2.<span class="hljs-title function_">getPackedSettings</span>({ <span class="hljs-attr">enablePush</span>: <span class="hljs-literal">false</span> });

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(packed.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'base64'</span>));
<span class="hljs-comment">// Prints: AAIAAAAA</span></code><button class="copy-button">copy</button></pre>
<h4><code>http2.getUnpackedSettings(buf)</code><span><a class="mark" href="#all_http2_http2getunpackedsettingsbuf" id="all_http2_http2getunpackedsettingsbuf">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2_getunpackedsettings_buf"></a></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><code>buf</code> <a href="#all_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> The packed settings.</li>
<li>Returns: <a href="#all_http2_settings-object" class="type">&#x3C;HTTP/2 Settings Object></a></li>
</ul>
<p>Returns a <a href="#all_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>
<h4><code>http2.performServerHandshake(socket[, options])</code><span><a class="mark" href="#all_http2_http2performserverhandshakesocket-options" id="all_http2_http2performserverhandshakesocket-options">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2_performserverhandshake_socket_options"></a></h4>
<div class="api_metadata">
<span>Added in: v20.12.0</span>
</div>
<ul>
<li><code>socket</code> <a href="#all_stream_class-streamduplex" class="type">&#x3C;stream.Duplex></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>
<ul>
<li>...: Any <a href="#all_http2_http2createserveroptions-onrequesthandler"><code>http2.createServer()</code></a> option can be provided.</li>
</ul>
</li>
<li>Returns: <a href="#all_http2_class-serverhttp2session" class="type">&#x3C;ServerHttp2Session></a></li>
</ul>
<p>Create an HTTP/2 server session from an existing socket.</p>
<h4><code>http2.sensitiveHeaders</code><span><a class="mark" href="#all_http2_http2sensitiveheaders" id="all_http2_http2sensitiveheaders">#</a></span><a aria-hidden="true" class="legacy" id="http2_http2_sensitiveheaders"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0, v14.18.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>This symbol can be set as a property on the HTTP/2 headers object with an array
value in order to provide a list of headers considered sensitive.
See <a href="#all_http2_sensitive-headers">Sensitive headers</a> for more details.</p>
<h4>Headers object<span><a class="mark" href="#all_http2_headers-object" id="all_http2_headers-object">#</a></span><a aria-hidden="true" class="legacy" id="http2_headers_object"></a></h4>
<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"><span class="hljs-keyword">const</span> headers = {
  <span class="hljs-string">':status'</span>: <span class="hljs-string">'200'</span>,
  <span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text-plain'</span>,
  <span class="hljs-string">'ABC'</span>: [<span class="hljs-string">'has'</span>, <span class="hljs-string">'more'</span>, <span class="hljs-string">'than'</span>, <span class="hljs-string">'one'</span>, <span class="hljs-string">'value'</span>],
};

stream.<span class="hljs-title function_">respond</span>(headers);</code> <button class="copy-button">copy</button></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>host</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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream, headers</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(headers[<span class="hljs-string">':path'</span>]);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(headers.<span class="hljs-property">ABC</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createServer</span>();
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream, headers</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(headers[<span class="hljs-string">':path'</span>]);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(headers.<span class="hljs-property">ABC</span>);
});</code><button class="copy-button">copy</button></pre>
<h5>Sensitive headers<span><a class="mark" href="#all_http2_sensitive-headers" id="all_http2_sensitive-headers">#</a></span><a aria-hidden="true" class="legacy" id="http2_sensitive_headers"></a></h5>
<p>HTTP2 headers can be marked as sensitive, which means that the HTTP/2
header compression algorithm will never index them. This can make sense for
header values with low entropy and that may be considered valuable to an
attacker, for example <code>Cookie</code> or <code>Authorization</code>. To achieve this, add
the header name to the <code>[http2.sensitiveHeaders]</code> property as an array:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> headers = {
  <span class="hljs-string">':status'</span>: <span class="hljs-string">'200'</span>,
  <span class="hljs-string">'content-type'</span>: <span class="hljs-string">'text-plain'</span>,
  <span class="hljs-string">'cookie'</span>: <span class="hljs-string">'some-cookie'</span>,
  <span class="hljs-string">'other-sensitive-header'</span>: <span class="hljs-string">'very secret data'</span>,
  [http2.<span class="hljs-property">sensitiveHeaders</span>]: [<span class="hljs-string">'cookie'</span>, <span class="hljs-string">'other-sensitive-header'</span>],
};

stream.<span class="hljs-title function_">respond</span>(headers);</code> <button class="copy-button">copy</button></pre>
<p>For some headers, such as <code>Authorization</code> and short <code>Cookie</code> headers,
this flag is set automatically.</p>
<p>This property is also set for received headers. It will contain the names of
all headers marked as sensitive, including ones marked that way automatically.</p>
<h4>Settings object<span><a class="mark" href="#all_http2_settings-object" id="all_http2_settings-object">#</a></span><a aria-hidden="true" class="legacy" id="http2_settings_object"></a></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>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>maxHeaderSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Alias for <code>maxHeaderListSize</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>
<li><code>customSettings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Specifies additional settings, yet not implemented
in node and the underlying libraries. The key of the object defines the
numeric value of the settings type (as defined in the "HTTP/2 SETTINGS"
registry established by [RFC 7540]) and the values the actual numeric value
of the settings.
The settings type has to be an integer in the range from 1 to 2^16-1.
It should not be a settings type already handled by node, i.e. currently
it should be greater than 6, although it is not an error.
The values need to be unsigned integers in the range from 0 to 2^32-1.
Currently, a maximum of up 10 custom settings is supported.
It is only supported for sending SETTINGS, or for receiving settings values
specified in the <code>remoteCustomSettings</code> options of the server or client
object. Do not mix the <code>customSettings</code>-mechanism for a settings id with
interfaces for the natively handled settings, in case a setting becomes
natively supported in a future node version.</li>
</ul>
<p>All additional properties on the settings object are ignored.</p>
<h4>Error handling<span><a class="mark" href="#all_http2_error-handling" id="all_http2_error-handling">#</a></span><a aria-hidden="true" class="legacy" id="http2_error_handling"></a></h4>
<p>There are several types of error conditions that may arise when using the
<code>node: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>
<h4>Invalid character handling in header names and values<span><a class="mark" href="#all_http2_invalid-character-handling-in-header-names-and-values" id="all_http2_invalid-character-handling-in-header-names-and-values">#</a></span><a aria-hidden="true" class="legacy" id="http2_invalid_character_handling_in_header_names_and_values"></a></h4>
<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>
<h4>Push streams on the client<span><a class="mark" href="#all_http2_push-streams-on-the-client" id="all_http2_push-streams-on-the-client">#</a></span><a aria-hidden="true" class="legacy" id="http2_push_streams_on_the_client"></a></h4>
<p>To receive pushed streams on the client, set a listener for the <code>'stream'</code>
event on the <code>ClientHttp2Session</code>:</p>

<pre class="with-37-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { connect } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;

<span class="hljs-keyword">const</span> client = <span class="hljs-title function_">connect</span>(<span class="hljs-string">'http://localhost'</span>);

client.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">pushedStream, requestHeaders</span>) =></span> {
  pushedStream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'push'</span>, <span class="hljs-function">(<span class="hljs-params">responseHeaders</span>) =></span> {
    <span class="hljs-comment">// Process response headers</span>
  });
  pushedStream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> { <span class="hljs-comment">/* handle pushed data */</span> });
});

<span class="hljs-keyword">const</span> req = client.<span class="hljs-title function_">request</span>({ <span class="hljs-string">':path'</span>: <span class="hljs-string">'/'</span> });</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);

<span class="hljs-keyword">const</span> client = http2.<span class="hljs-title function_">connect</span>(<span class="hljs-string">'http://localhost'</span>);

client.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">pushedStream, requestHeaders</span>) =></span> {
  pushedStream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'push'</span>, <span class="hljs-function">(<span class="hljs-params">responseHeaders</span>) =></span> {
    <span class="hljs-comment">// Process response headers</span>
  });
  pushedStream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> { <span class="hljs-comment">/* handle pushed data */</span> });
});

<span class="hljs-keyword">const</span> req = client.<span class="hljs-title function_">request</span>({ <span class="hljs-string">':path'</span>: <span class="hljs-string">'/'</span> });</code><button class="copy-button">copy</button></pre>
<h4>Supporting the <code>CONNECT</code> method<span><a class="mark" href="#all_http2_supporting-the-connect-method" id="all_http2_supporting-the-connect-method">#</a></span><a aria-hidden="true" class="legacy" id="http2_supporting_the_connect_method"></a></h4>
<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 class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:net'</span>;

<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">socket</span>) =></span> {
  <span class="hljs-keyword">let</span> name = <span class="hljs-string">''</span>;
  socket.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>);
  socket.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> name += chunk);
  socket.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> socket.<span class="hljs-title function_">end</span>(<span class="hljs-string">`hello <span class="hljs-subst">${name}</span>`</span>));
});

server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> net = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:net'</span>);

<span class="hljs-keyword">const</span> server = net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">socket</span>) =></span> {
  <span class="hljs-keyword">let</span> name = <span class="hljs-string">''</span>;
  socket.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>);
  socket.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> name += chunk);
  socket.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> socket.<span class="hljs-title function_">end</span>(<span class="hljs-string">`hello <span class="hljs-subst">${name}</span>`</span>));
});

server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);</code><button class="copy-button">copy</button></pre>
<p>An HTTP/2 CONNECT proxy:</p>

<pre class="with-68-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createServer, constants } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">NGHTTP2</span>_REFUSED_STREAM, <span class="hljs-title class_">NGHTTP2</span>_CONNECT_ERROR } = constants;
<span class="hljs-keyword">import</span> { connect } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:net'</span>;

<span class="hljs-keyword">const</span> proxy = <span class="hljs-title function_">createServer</span>();
proxy.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream, headers</span>) =></span> {
  <span class="hljs-keyword">if</span> (headers[<span class="hljs-string">':method'</span>] !== <span class="hljs-string">'CONNECT'</span>) {
    <span class="hljs-comment">// Only accept CONNECT requests</span>
    stream.<span class="hljs-title function_">close</span>(<span class="hljs-title class_">NGHTTP2</span>_REFUSED_STREAM);
    <span class="hljs-keyword">return</span>;
  }
  <span class="hljs-keyword">const</span> auth = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">`tcp://<span class="hljs-subst">${headers[<span class="hljs-string">':authority'</span>]}</span>`</span>);
  <span class="hljs-comment">// It's a very good idea to verify that hostname and port are</span>
  <span class="hljs-comment">// things this proxy should be connecting to.</span>
  <span class="hljs-keyword">const</span> socket = <span class="hljs-title function_">connect</span>(auth.<span class="hljs-property">port</span>, auth.<span class="hljs-property">hostname</span>, <span class="hljs-function">() =></span> {
    stream.<span class="hljs-title function_">respond</span>();
    socket.<span class="hljs-title function_">pipe</span>(stream);
    stream.<span class="hljs-title function_">pipe</span>(socket);
  });
  socket.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">error</span>) =></span> {
    stream.<span class="hljs-title function_">close</span>(<span class="hljs-title class_">NGHTTP2</span>_CONNECT_ERROR);
  });
});

proxy.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8001</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">NGHTTP2</span>_REFUSED_STREAM } = http2.<span class="hljs-property">constants</span>;
<span class="hljs-keyword">const</span> net = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:net'</span>);

<span class="hljs-keyword">const</span> proxy = http2.<span class="hljs-title function_">createServer</span>();
proxy.<span class="hljs-title function_">on</span>(<span class="hljs-string">'stream'</span>, <span class="hljs-function">(<span class="hljs-params">stream, headers</span>) =></span> {
  <span class="hljs-keyword">if</span> (headers[<span class="hljs-string">':method'</span>] !== <span class="hljs-string">'CONNECT'</span>) {
    <span class="hljs-comment">// Only accept CONNECT requests</span>
    stream.<span class="hljs-title function_">close</span>(<span class="hljs-title class_">NGHTTP2</span>_REFUSED_STREAM);
    <span class="hljs-keyword">return</span>;
  }
  <span class="hljs-keyword">const</span> auth = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">`tcp://<span class="hljs-subst">${headers[<span class="hljs-string">':authority'</span>]}</span>`</span>);
  <span class="hljs-comment">// It's a very good idea to verify that hostname and port are</span>
  <span class="hljs-comment">// things this proxy should be connecting to.</span>
  <span class="hljs-keyword">const</span> socket = net.<span class="hljs-title function_">connect</span>(auth.<span class="hljs-property">port</span>, auth.<span class="hljs-property">hostname</span>, <span class="hljs-function">() =></span> {
    stream.<span class="hljs-title function_">respond</span>();
    socket.<span class="hljs-title function_">pipe</span>(stream);
    stream.<span class="hljs-title function_">pipe</span>(socket);
  });
  socket.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">error</span>) =></span> {
    stream.<span class="hljs-title function_">close</span>(http2.<span class="hljs-property">constants</span>.<span class="hljs-property">NGHTTP2_CONNECT_ERROR</span>);
  });
});

proxy.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8001</span>);</code><button class="copy-button">copy</button></pre>
<p>An HTTP/2 CONNECT client:</p>

<pre class="with-48-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { connect, constants } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;

<span class="hljs-keyword">const</span> client = <span class="hljs-title function_">connect</span>(<span class="hljs-string">'http://localhost:8001'</span>);

<span class="hljs-comment">// Must not specify the ':path' and ':scheme' headers</span>
<span class="hljs-comment">// for CONNECT requests or an error will be thrown.</span>
<span class="hljs-keyword">const</span> req = client.<span class="hljs-title function_">request</span>({
  <span class="hljs-string">':method'</span>: <span class="hljs-string">'CONNECT'</span>,
  <span class="hljs-string">':authority'</span>: <span class="hljs-string">'localhost:8000'</span>,
});

req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'response'</span>, <span class="hljs-function">(<span class="hljs-params">headers</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(headers[constants.<span class="hljs-property">HTTP2_HEADER_STATUS</span>]);
});
<span class="hljs-keyword">let</span> data = <span class="hljs-string">''</span>;
req.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>);
req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> data += chunk);
req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`The server says: <span class="hljs-subst">${data}</span>`</span>);
  client.<span class="hljs-title function_">close</span>();
});
req.<span class="hljs-title function_">end</span>(<span class="hljs-string">'Jane'</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);

<span class="hljs-keyword">const</span> client = http2.<span class="hljs-title function_">connect</span>(<span class="hljs-string">'http://localhost:8001'</span>);

<span class="hljs-comment">// Must not specify the ':path' and ':scheme' headers</span>
<span class="hljs-comment">// for CONNECT requests or an error will be thrown.</span>
<span class="hljs-keyword">const</span> req = client.<span class="hljs-title function_">request</span>({
  <span class="hljs-string">':method'</span>: <span class="hljs-string">'CONNECT'</span>,
  <span class="hljs-string">':authority'</span>: <span class="hljs-string">'localhost:8000'</span>,
});

req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'response'</span>, <span class="hljs-function">(<span class="hljs-params">headers</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(headers[http2.<span class="hljs-property">constants</span>.<span class="hljs-property">HTTP2_HEADER_STATUS</span>]);
});
<span class="hljs-keyword">let</span> data = <span class="hljs-string">''</span>;
req.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>);
req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> data += chunk);
req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`The server says: <span class="hljs-subst">${data}</span>`</span>);
  client.<span class="hljs-title function_">close</span>();
});
req.<span class="hljs-title function_">end</span>(<span class="hljs-string">'Jane'</span>);</code><button class="copy-button">copy</button></pre>
<h4>The extended <code>CONNECT</code> protocol<span><a class="mark" href="#all_http2_the-extended-connect-protocol" id="all_http2_the-extended-connect-protocol">#</a></span><a aria-hidden="true" class="legacy" id="http2_the_extended_connect_protocol"></a></h4>
<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 class="with-49-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> settings = { <span class="hljs-attr">enableConnectProtocol</span>: <span class="hljs-literal">true</span> };
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>({ settings });</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> settings = { <span class="hljs-attr">enableConnectProtocol</span>: <span class="hljs-literal">true</span> };
<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createServer</span>({ settings });</code><button class="copy-button">copy</button></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 class="with-54-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { connect } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> client = <span class="hljs-title function_">connect</span>(<span class="hljs-string">'http://localhost:8080'</span>);
client.<span class="hljs-title function_">on</span>(<span class="hljs-string">'remoteSettings'</span>, <span class="hljs-function">(<span class="hljs-params">settings</span>) =></span> {
  <span class="hljs-keyword">if</span> (settings.<span class="hljs-property">enableConnectProtocol</span>) {
    <span class="hljs-keyword">const</span> req = client.<span class="hljs-title function_">request</span>({ <span class="hljs-string">':method'</span>: <span class="hljs-string">'CONNECT'</span>, <span class="hljs-string">':protocol'</span>: <span class="hljs-string">'foo'</span> });
    <span class="hljs-comment">// ...</span>
  }
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> client = http2.<span class="hljs-title function_">connect</span>(<span class="hljs-string">'http://localhost:8080'</span>);
client.<span class="hljs-title function_">on</span>(<span class="hljs-string">'remoteSettings'</span>, <span class="hljs-function">(<span class="hljs-params">settings</span>) =></span> {
  <span class="hljs-keyword">if</span> (settings.<span class="hljs-property">enableConnectProtocol</span>) {
    <span class="hljs-keyword">const</span> req = client.<span class="hljs-title function_">request</span>({ <span class="hljs-string">':method'</span>: <span class="hljs-string">'CONNECT'</span>, <span class="hljs-string">':protocol'</span>: <span class="hljs-string">'foo'</span> });
    <span class="hljs-comment">// ...</span>
  }
});</code><button class="copy-button">copy</button></pre>
</section><section><h3>Compatibility API<span><a class="mark" href="#all_http2_compatibility-api" id="all_http2_compatibility-api">#</a></span><a aria-hidden="true" class="legacy" id="http2_compatibility_api"></a></h3>
<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 class="with-49-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
  res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Content-Type'</span>, <span class="hljs-string">'text/html'</span>);
  res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'X-Foo'</span>, <span class="hljs-string">'bar'</span>);
  res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain; charset=utf-8'</span> });
  res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'ok'</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
  res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Content-Type'</span>, <span class="hljs-string">'text/html'</span>);
  res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'X-Foo'</span>, <span class="hljs-string">'bar'</span>);
  res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain; charset=utf-8'</span> });
  res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'ok'</span>);
});</code><button class="copy-button">copy</button></pre>
<p>In order to create a mixed <a href="https.html">HTTPS</a> and HTTP/2 server, refer to the
<a href="#all_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="#all_http2_class-http2http2serverrequest"><code>Http2ServerRequest</code></a> and
<a href="#all_http2_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>
<h4>ALPN negotiation<span><a class="mark" href="#all_http2_alpn-negotiation" id="all_http2_alpn-negotiation">#</a></span><a aria-hidden="true" class="legacy" id="http2_alpn_negotiation"></a></h4>
<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 class="with-53-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createSecureServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">import</span> { readFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-keyword">const</span> cert = <span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'./cert.pem'</span>);
<span class="hljs-keyword">const</span> key = <span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'./key.pem'</span>);

<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createSecureServer</span>(
  { cert, key, <span class="hljs-attr">allowHTTP1</span>: <span class="hljs-literal">true</span> },
  onRequest,
).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);

<span class="hljs-keyword">function</span> <span class="hljs-title function_">onRequest</span>(<span class="hljs-params">req, res</span>) {
  <span class="hljs-comment">// Detects if it is a HTTPS request or HTTP/2</span>
  <span class="hljs-keyword">const</span> { <span class="hljs-attr">socket</span>: { alpnProtocol } } = req.<span class="hljs-property">httpVersion</span> === <span class="hljs-string">'2.0'</span> ?
    req.<span class="hljs-property">stream</span>.<span class="hljs-property">session</span> : req;
  res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'content-type'</span>: <span class="hljs-string">'application/json'</span> });
  res.<span class="hljs-title function_">end</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>({
    alpnProtocol,
    <span class="hljs-attr">httpVersion</span>: req.<span class="hljs-property">httpVersion</span>,
  }));
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { createSecureServer } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> { readFileSync } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);

<span class="hljs-keyword">const</span> cert = <span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'./cert.pem'</span>);
<span class="hljs-keyword">const</span> key = <span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'./key.pem'</span>);

<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createSecureServer</span>(
  { cert, key, <span class="hljs-attr">allowHTTP1</span>: <span class="hljs-literal">true</span> },
  onRequest,
).<span class="hljs-title function_">listen</span>(<span class="hljs-number">4443</span>);

<span class="hljs-keyword">function</span> <span class="hljs-title function_">onRequest</span>(<span class="hljs-params">req, res</span>) {
  <span class="hljs-comment">// Detects if it is a HTTPS request or HTTP/2</span>
  <span class="hljs-keyword">const</span> { <span class="hljs-attr">socket</span>: { alpnProtocol } } = req.<span class="hljs-property">httpVersion</span> === <span class="hljs-string">'2.0'</span> ?
    req.<span class="hljs-property">stream</span>.<span class="hljs-property">session</span> : req;
  res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'content-type'</span>: <span class="hljs-string">'application/json'</span> });
  res.<span class="hljs-title function_">end</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>({
    alpnProtocol,
    <span class="hljs-attr">httpVersion</span>: req.<span class="hljs-property">httpVersion</span>,
  }));
}</code><button class="copy-button">copy</button></pre>
<p>The <code>'request'</code> event works identically on both <a href="https.html">HTTPS</a> and
HTTP/2.</p>
<h4>Class: <code>http2.Http2ServerRequest</code><span><a class="mark" href="#all_http2_class-http2http2serverrequest" id="all_http2_class-http2http2serverrequest">#</a></span><a aria-hidden="true" class="legacy" id="http2_class_http2_http2serverrequest"></a></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li>Extends: <a href="#all_stream_class-streamreadable" class="type">&#x3C;stream.Readable></a></li>
</ul>
<p>A <code>Http2ServerRequest</code> object is created by <a href="#all_http2_class-http2server"><code>http2.Server</code></a> or
<a href="#all_http2_class-http2secureserver"><code>http2.SecureServer</code></a> and passed as the first argument to the
<a href="#all_http2_event-request"><code>'request'</code></a> event. It may be used to access a request status, headers, and
data.</p>
<h5>Event: <code>'aborted'</code><span><a class="mark" href="#all_http2_event-aborted_1" id="all_http2_event-aborted_1">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_aborted_1"></a></h5>
<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>
<h5>Event: <code>'close'</code><span><a class="mark" href="#all_http2_event-close_2" id="all_http2_event-close_2">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_close_2"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<p>Indicates that the underlying <a href="#all_http2_class-http2stream"><code>Http2Stream</code></a> was closed.
Just like <code>'end'</code>, this event occurs only once per response.</p>
<h5><code>request.aborted</code><span><a class="mark" href="#all_http2_requestaborted" id="all_http2_requestaborted">#</a></span><a aria-hidden="true" class="legacy" id="http2_request_aborted"></a></h5>
<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>
<h5><code>request.authority</code><span><a class="mark" href="#all_http2_requestauthority" id="all_http2_requestauthority">#</a></span><a aria-hidden="true" class="legacy" id="http2_request_authority"></a></h5>
<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. Because HTTP/2 allows requests
to set either <code>:authority</code> or <code>host</code>, this value is derived from
<code>req.headers[':authority']</code> if present. Otherwise, it is derived from
<code>req.headers['host']</code>.</p>
<h5><code>request.complete</code><span><a class="mark" href="#all_http2_requestcomplete" id="all_http2_requestcomplete">#</a></span><a aria-hidden="true" class="legacy" id="http2_request_complete"></a></h5>
<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>
<h5><code>request.connection</code><span><a class="mark" href="#all_http2_requestconnection" id="all_http2_requestconnection">#</a></span><a aria-hidden="true" class="legacy" id="http2_request_connection"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span><span>Deprecated since: v13.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated. Use <a href="#all_http2_requestsocket"><code>request.socket</code></a>.</div><p></p>
<ul>
<li><a href="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a> | <a href="#all_tls_class-tlstlssocket" class="type">&#x3C;tls.TLSSocket></a></li>
</ul>
<p>See <a href="#all_http2_requestsocket"><code>request.socket</code></a>.</p>
<h5><code>request.destroy([error])</code><span><a class="mark" href="#all_http2_requestdestroyerror" id="all_http2_requestdestroyerror">#</a></span><a aria-hidden="true" class="legacy" id="http2_request_destroy_error"></a></h5>
<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="#all_http2_class-http2stream"><code>Http2Stream</code></a> that received
the <a href="#all_http2_class-http2http2serverrequest"><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>
<h5><code>request.headers</code><span><a class="mark" href="#all_http2_requestheaders" id="all_http2_requestheaders">#</a></span><a aria-hidden="true" class="legacy" id="http2_request_headers"></a></h5>
<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"><span class="hljs-comment">// Prints something like:</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// { 'user-agent': 'curl/7.22.0',</span>
<span class="hljs-comment">//   host: '127.0.0.1:8000',</span>
<span class="hljs-comment">//   accept: '*/*' }</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(request.<span class="hljs-property">headers</span>);</code> <button class="copy-button">copy</button></pre>
<p>See <a href="#all_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"><span class="hljs-title function_">removeAllHeaders</span>(request.<span class="hljs-property">headers</span>);
<span class="hljs-title function_">assert</span>(request.<span class="hljs-property">url</span>);   <span class="hljs-comment">// Fails because the :path header has been removed</span></code> <button class="copy-button">copy</button></pre>
<h5><code>request.httpVersion</code><span><a class="mark" href="#all_http2_requesthttpversion" id="all_http2_requesthttpversion">#</a></span><a aria-hidden="true" class="legacy" id="http2_request_httpversion"></a></h5>
<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>
<h5><code>request.method</code><span><a class="mark" href="#all_http2_requestmethod" id="all_http2_requestmethod">#</a></span><a aria-hidden="true" class="legacy" id="http2_request_method"></a></h5>
<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>
<h5><code>request.rawHeaders</code><span><a class="mark" href="#all_http2_requestrawheaders" id="all_http2_requestrawheaders">#</a></span><a aria-hidden="true" class="legacy" id="http2_request_rawheaders"></a></h5>
<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"><span class="hljs-comment">// Prints something like:</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// [ 'user-agent',</span>
<span class="hljs-comment">//   'this is invalid because there can be only one',</span>
<span class="hljs-comment">//   'User-Agent',</span>
<span class="hljs-comment">//   'curl/7.22.0',</span>
<span class="hljs-comment">//   'Host',</span>
<span class="hljs-comment">//   '127.0.0.1:8000',</span>
<span class="hljs-comment">//   'ACCEPT',</span>
<span class="hljs-comment">//   '*/*' ]</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(request.<span class="hljs-property">rawHeaders</span>);</code> <button class="copy-button">copy</button></pre>
<h5><code>request.rawTrailers</code><span><a class="mark" href="#all_http2_requestrawtrailers" id="all_http2_requestrawtrailers">#</a></span><a aria-hidden="true" class="legacy" id="http2_request_rawtrailers"></a></h5>
<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>
<h5><code>request.scheme</code><span><a class="mark" href="#all_http2_requestscheme" id="all_http2_requestscheme">#</a></span><a aria-hidden="true" class="legacy" id="http2_request_scheme"></a></h5>
<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>
<h5><code>request.setTimeout(msecs, callback)</code><span><a class="mark" href="#all_http2_requestsettimeoutmsecs-callback" id="all_http2_requestsettimeoutmsecs-callback">#</a></span><a aria-hidden="true" class="legacy" id="http2_request_settimeout_msecs_callback"></a></h5>
<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="#all_http2_class-http2http2serverrequest" class="type">&#x3C;http2.Http2ServerRequest></a></li>
</ul>
<p>Sets the <a href="#all_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="#all_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>
<h5><code>request.socket</code><span><a class="mark" href="#all_http2_requestsocket" id="all_http2_requestsocket">#</a></span><a aria-hidden="true" class="legacy" id="http2_request_socket"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a> | <a href="#all_tls_class-tlstlssocket" 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="#all_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="#all_tls_tlssocketgetpeercertificatedetailed"><code>request.socket.getPeerCertificate()</code></a> to obtain the client's
authentication details.</p>
<h5><code>request.stream</code><span><a class="mark" href="#all_http2_requeststream" id="all_http2_requeststream">#</a></span><a aria-hidden="true" class="legacy" id="http2_request_stream"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="#all_http2_class-http2stream" class="type">&#x3C;Http2Stream></a></li>
</ul>
<p>The <a href="#all_http2_class-http2stream"><code>Http2Stream</code></a> object backing the request.</p>
<h5><code>request.trailers</code><span><a class="mark" href="#all_http2_requesttrailers" id="all_http2_requesttrailers">#</a></span><a aria-hidden="true" class="legacy" id="http2_request_trailers"></a></h5>
<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>
<h5><code>request.url</code><span><a class="mark" href="#all_http2_requesturl" id="all_http2_requesturl">#</a></span><a aria-hidden="true" class="legacy" id="http2_request_url"></a></h5>
<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"><span class="hljs-keyword">GET</span> <span class="hljs-string">/status?name=ryan</span> <span class="hljs-meta">HTTP/1.1</span>
<span class="hljs-attribute">Accept</span><span class="hljs-punctuation">: </span>text/plain</code> <button class="copy-button">copy</button></pre>
<p>Then <code>request.url</code> will be:</p>
<!-- eslint-disable @stylistic/js/semi -->
<pre><code class="language-js"><span class="hljs-string">'/status?name=ryan'</span></code> <button class="copy-button">copy</button></pre>
<p>To parse the url into its parts, <code>new URL()</code> can be used:</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node</span>
<span class="hljs-meta prompt_">> </span><span class="language-bash">new URL(<span class="hljs-string">'/status?name=ryan'</span>, <span class="hljs-string">'http://example.com'</span>)</span>
URL {
  href: 'http://example.com/status?name=ryan',
  origin: 'http://example.com',
  protocol: 'http:',
  username: '',
  password: '',
  host: 'example.com',
  hostname: 'example.com',
  port: '',
  pathname: '/status',
  search: '?name=ryan',
  searchParams: URLSearchParams { 'name' => 'ryan' },
  hash: ''
}</code> <button class="copy-button">copy</button></pre>
<h4>Class: <code>http2.Http2ServerResponse</code><span><a class="mark" href="#all_http2_class-http2http2serverresponse" id="all_http2_class-http2http2serverresponse">#</a></span><a aria-hidden="true" class="legacy" id="http2_class_http2_http2serverresponse"></a></h4>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li>Extends: <a href="#all_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="#all_http2_event-request"><code>'request'</code></a> event.</p>
<h5>Event: <code>'close'</code><span><a class="mark" href="#all_http2_event-close_3" id="all_http2_event-close_3">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_close_3"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<p>Indicates that the underlying <a href="#all_http2_class-http2stream"><code>Http2Stream</code></a> was terminated before
<a href="#all_http2_responseenddata-encoding-callback"><code>response.end()</code></a> was called or able to flush.</p>
<h5>Event: <code>'finish'</code><span><a class="mark" href="#all_http2_event-finish" id="all_http2_event-finish">#</a></span><a aria-hidden="true" class="legacy" id="http2_event_finish"></a></h5>
<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>
<h5><code>response.addTrailers(headers)</code><span><a class="mark" href="#all_http2_responseaddtrailersheaders" id="all_http2_responseaddtrailersheaders">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_addtrailers_headers"></a></h5>
<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="#all_errors_class-typeerror"><code>TypeError</code></a> being thrown.</p>
<h5><code>response.appendHeader(name, value)</code><span><a class="mark" href="#all_http2_responseappendheadername-value" id="all_http2_responseappendheadername-value">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_appendheader_name_value"></a></h5>
<div class="api_metadata">
<span>Added in: v20.12.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>Append a single header value to the header object.</p>
<p>If the value is an array, this is equivalent to calling this method multiple
times.</p>
<p>If there were no previous values for the header, this is equivalent to calling
<a href="#all_http2_responsesetheadername-value"><code>response.setHeader()</code></a>.</p>
<p>Attempting to set a header field name or value that contains invalid characters
will result in a <a href="#all_errors_class-typeerror"><code>TypeError</code></a> being thrown.</p>
<pre><code class="language-js"><span class="hljs-comment">// Returns headers including "set-cookie: a" and "set-cookie: b"</span>
<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
  res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'set-cookie'</span>, <span class="hljs-string">'a'</span>);
  res.<span class="hljs-title function_">appendHeader</span>(<span class="hljs-string">'set-cookie'</span>, <span class="hljs-string">'b'</span>);
  res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>);
  res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'ok'</span>);
});</code> <button class="copy-button">copy</button></pre>
<h5><code>response.connection</code><span><a class="mark" href="#all_http2_responseconnection" id="all_http2_responseconnection">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_connection"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span><span>Deprecated since: v13.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated. Use <a href="#all_http2_responsesocket"><code>response.socket</code></a>.</div><p></p>
<ul>
<li><a href="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a> | <a href="#all_tls_class-tlstlssocket" class="type">&#x3C;tls.TLSSocket></a></li>
</ul>
<p>See <a href="#all_http2_responsesocket"><code>response.socket</code></a>.</p>
<h5><code>response.createPushResponse(headers, callback)</code><span><a class="mark" href="#all_http2_responsecreatepushresponseheaders-callback" id="all_http2_responsecreatepushresponseheaders-callback">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_createpushresponse_headers_callback"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</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>headers</code> <a href="#all_http2_headers-object" class="type">&#x3C;HTTP/2 Headers Object></a> An object describing the headers</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 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
<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>res</code> <a href="#all_http2_class-http2http2serverresponse" class="type">&#x3C;http2.Http2ServerResponse></a> The newly-created <code>Http2ServerResponse</code>
object</li>
</ul>
</li>
</ul>
<p>Call <a href="#all_http2_http2streampushstreamheaders-options-callback"><code>http2stream.pushStream()</code></a> with the given headers, and wrap the
given <a href="#all_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>
<h5><code>response.end([data[, encoding]][, callback])</code><span><a class="mark" href="#all_http2_responseenddata-encoding-callback" id="all_http2_responseenddata-encoding-callback">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_end_data_encoding_callback"></a></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>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="#all_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="#all_http_responsewritechunk-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>
<h5><code>response.finished</code><span><a class="mark" href="#all_http2_responsefinished" id="all_http2_responsefinished">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_finished"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span><span>Deprecated since: v13.4.0, v12.16.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated. Use <a href="#all_http2_responsewritableended"><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="#all_http2_responseenddata-encoding-callback"><code>response.end()</code></a> executes, the value will be <code>true</code>.</p>
<h5><code>response.getHeader(name)</code><span><a class="mark" href="#all_http2_responsegetheadername" id="all_http2_responsegetheadername">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_getheader_name"></a></h5>
<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"><span class="hljs-keyword">const</span> contentType = response.<span class="hljs-title function_">getHeader</span>(<span class="hljs-string">'content-type'</span>);</code> <button class="copy-button">copy</button></pre>
<h5><code>response.getHeaderNames()</code><span><a class="mark" href="#all_http2_responsegetheadernames" id="all_http2_responsegetheadernames">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_getheadernames"></a></h5>
<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.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Foo'</span>, <span class="hljs-string">'bar'</span>);
response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Set-Cookie'</span>, [<span class="hljs-string">'foo=bar'</span>, <span class="hljs-string">'bar=baz'</span>]);

<span class="hljs-keyword">const</span> headerNames = response.<span class="hljs-title function_">getHeaderNames</span>();
<span class="hljs-comment">// headerNames === ['foo', 'set-cookie']</span></code> <button class="copy-button">copy</button></pre>
<h5><code>response.getHeaders()</code><span><a class="mark" href="#all_http2_responsegetheaders" id="all_http2_responsegetheaders">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_getheaders"></a></h5>
<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.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Foo'</span>, <span class="hljs-string">'bar'</span>);
response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Set-Cookie'</span>, [<span class="hljs-string">'foo=bar'</span>, <span class="hljs-string">'bar=baz'</span>]);

<span class="hljs-keyword">const</span> headers = response.<span class="hljs-title function_">getHeaders</span>();
<span class="hljs-comment">// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }</span></code> <button class="copy-button">copy</button></pre>
<h5><code>response.hasHeader(name)</code><span><a class="mark" href="#all_http2_responsehasheadername" id="all_http2_responsehasheadername">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_hasheader_name"></a></h5>
<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"><span class="hljs-keyword">const</span> hasContentType = response.<span class="hljs-title function_">hasHeader</span>(<span class="hljs-string">'content-type'</span>);</code> <button class="copy-button">copy</button></pre>
<h5><code>response.headersSent</code><span><a class="mark" href="#all_http2_responseheaderssent" id="all_http2_responseheaderssent">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_headerssent"></a></h5>
<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>
<h5><code>response.removeHeader(name)</code><span><a class="mark" href="#all_http2_responseremoveheadername" id="all_http2_responseremoveheadername">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_removeheader_name"></a></h5>
<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.<span class="hljs-title function_">removeHeader</span>(<span class="hljs-string">'Content-Encoding'</span>);</code> <button class="copy-button">copy</button></pre>
<h5><code>response.req</code><span><a class="mark" href="#all_http2_responsereq" id="all_http2_responsereq">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_req"></a></h5>
<div class="api_metadata">
<span>Added in: v15.7.0</span>
</div>
<ul>
<li><a href="#all_http2_class-http2http2serverrequest" class="type">&#x3C;http2.Http2ServerRequest></a></li>
</ul>
<p>A reference to the original HTTP2 <code>request</code> object.</p>
<h5><code>response.sendDate</code><span><a class="mark" href="#all_http2_responsesenddate" id="all_http2_responsesenddate">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_senddate"></a></h5>
<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>
<h5><code>response.setHeader(name, value)</code><span><a class="mark" href="#all_http2_responsesetheadername-value" id="all_http2_responsesetheadername-value">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_setheader_name_value"></a></h5>
<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.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Content-Type'</span>, <span class="hljs-string">'text/html; charset=utf-8'</span>);</code> <button class="copy-button">copy</button></pre>
<p>or</p>
<pre><code class="language-js">response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Set-Cookie'</span>, [<span class="hljs-string">'type=ninja'</span>, <span class="hljs-string">'language=javascript'</span>]);</code> <button class="copy-button">copy</button></pre>
<p>Attempting to set a header field name or value that contains invalid characters
will result in a <a href="#all_errors_class-typeerror"><code>TypeError</code></a> being thrown.</p>
<p>When headers have been set with <a href="#all_http2_responsesetheadername-value"><code>response.setHeader()</code></a>, they will be merged
with any headers passed to <a href="#all_http2_responsewriteheadstatuscode-statusmessage-headers"><code>response.writeHead()</code></a>, with the headers passed
to <a href="#all_http2_responsewriteheadstatuscode-statusmessage-headers"><code>response.writeHead()</code></a> given precedence.</p>
<pre><code class="language-js"><span class="hljs-comment">// Returns content-type = text/plain</span>
<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
  res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Content-Type'</span>, <span class="hljs-string">'text/html; charset=utf-8'</span>);
  res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'X-Foo'</span>, <span class="hljs-string">'bar'</span>);
  res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain; charset=utf-8'</span> });
  res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'ok'</span>);
});</code> <button class="copy-button">copy</button></pre>
<h5><code>response.setTimeout(msecs[, callback])</code><span><a class="mark" href="#all_http2_responsesettimeoutmsecs-callback" id="all_http2_responsesettimeoutmsecs-callback">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_settimeout_msecs_callback"></a></h5>
<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="#all_http2_class-http2http2serverresponse" class="type">&#x3C;http2.Http2ServerResponse></a></li>
</ul>
<p>Sets the <a href="#all_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="#all_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>
<h5><code>response.socket</code><span><a class="mark" href="#all_http2_responsesocket" id="all_http2_responsesocket">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_socket"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a> | <a href="#all_tls_class-tlstlssocket" 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="#all_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 class="with-49-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:http2'</span>;
<span class="hljs-keyword">const</span> server = <span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
  <span class="hljs-keyword">const</span> ip = req.<span class="hljs-property">socket</span>.<span class="hljs-property">remoteAddress</span>;
  <span class="hljs-keyword">const</span> port = req.<span class="hljs-property">socket</span>.<span class="hljs-property">remotePort</span>;
  res.<span class="hljs-title function_">end</span>(<span class="hljs-string">`Your IP address is <span class="hljs-subst">${ip}</span> and your source port is <span class="hljs-subst">${port}</span>.`</span>);
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">3000</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> http2 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http2'</span>);
<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
  <span class="hljs-keyword">const</span> ip = req.<span class="hljs-property">socket</span>.<span class="hljs-property">remoteAddress</span>;
  <span class="hljs-keyword">const</span> port = req.<span class="hljs-property">socket</span>.<span class="hljs-property">remotePort</span>;
  res.<span class="hljs-title function_">end</span>(<span class="hljs-string">`Your IP address is <span class="hljs-subst">${ip}</span> and your source port is <span class="hljs-subst">${port}</span>.`</span>);
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">3000</span>);</code><button class="copy-button">copy</button></pre>
<h5><code>response.statusCode</code><span><a class="mark" href="#all_http2_responsestatuscode" id="all_http2_responsestatuscode">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_statuscode"></a></h5>
<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="#all_http2_responsewriteheadstatuscode-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.<span class="hljs-property">statusCode</span> = <span class="hljs-number">404</span>;</code> <button class="copy-button">copy</button></pre>
<p>After response header was sent to the client, this property indicates the
status code which was sent out.</p>
<h5><code>response.statusMessage</code><span><a class="mark" href="#all_http2_responsestatusmessage" id="all_http2_responsestatusmessage">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_statusmessage"></a></h5>
<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>
<h5><code>response.stream</code><span><a class="mark" href="#all_http2_responsestream" id="all_http2_responsestream">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_stream"></a></h5>
<div class="api_metadata">
<span>Added in: v8.4.0</span>
</div>
<ul>
<li><a href="#all_http2_class-http2stream" class="type">&#x3C;Http2Stream></a></li>
</ul>
<p>The <a href="#all_http2_class-http2stream"><code>Http2Stream</code></a> object backing the response.</p>
<h5><code>response.writableEnded</code><span><a class="mark" href="#all_http2_responsewritableended" id="all_http2_responsewritableended">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_writableended"></a></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="#all_http2_responseenddata-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="#all_stream_writablewritablefinished"><code>writable.writableFinished</code></a> instead.</p>
<h5><code>response.write(chunk[, encoding][, callback])</code><span><a class="mark" href="#all_http2_responsewritechunk-encoding-callback" id="all_http2_responsewritechunk-encoding-callback">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_write_chunk_encoding_callback"></a></h5>
<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="#all_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="#all_http2_responsewriteheadstatuscode-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>node: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="#all_http2_responsewritechunk-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="#all_http2_responsewritechunk-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>
<h5><code>response.writeContinue()</code><span><a class="mark" href="#all_http2_responsewritecontinue" id="all_http2_responsewritecontinue">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_writecontinue"></a></h5>
<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="#all_http2_event-checkcontinue"><code>'checkContinue'</code></a> event on <code>Http2Server</code> and
<code>Http2SecureServer</code>.</p>
<h5><code>response.writeEarlyHints(hints)</code><span><a class="mark" href="#all_http2_responsewriteearlyhintshints" id="all_http2_responsewriteearlyhintshints">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_writeearlyhints_hints"></a></h5>
<div class="api_metadata">
<span>Added in: v18.11.0</span>
</div>
<ul>
<li><code>hints</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 status <code>103 Early Hints</code> to the client with a Link header,
indicating that the user agent can preload/preconnect the linked resources.
The <code>hints</code> is an object containing the values of headers to be sent with
early hints message.</p>
<p><strong>Example</strong></p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> earlyHintsLink = <span class="hljs-string">'&#x3C;/styles.css>; rel=preload; as=style'</span>;
response.<span class="hljs-title function_">writeEarlyHints</span>({
  <span class="hljs-string">'link'</span>: earlyHintsLink,
});

<span class="hljs-keyword">const</span> earlyHintsLinks = [
  <span class="hljs-string">'&#x3C;/styles.css>; rel=preload; as=style'</span>,
  <span class="hljs-string">'&#x3C;/scripts.js>; rel=preload; as=script'</span>,
];
response.<span class="hljs-title function_">writeEarlyHints</span>({
  <span class="hljs-string">'link'</span>: earlyHintsLinks,
});</code> <button class="copy-button">copy</button></pre>
<h5><code>response.writeHead(statusCode[, statusMessage][, headers])</code><span><a class="mark" href="#all_http2_responsewriteheadstatuscode-statusmessage-headers" id="all_http2_responsewriteheadstatuscode-statusmessage-headers">#</a></span><a aria-hidden="true" class="legacy" id="http2_response_writehead_statuscode_statusmessage_headers"></a></h5>
<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, v10.17.0</td>
<td><p>Return <code>this</code> from <code>writeHead()</code> to allow chaining with <code>end()</code>.</p></td></tr>
<tr><td>v8.4.0</td>
<td><p><span>Added in: v8.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>statusCode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type">&#x3C;Array></a></li>
<li>Returns: <a href="#all_http2_class-http2http2serverresponse" 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"><span class="hljs-keyword">const</span> body = <span class="hljs-string">'hello world'</span>;
response.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, {
  <span class="hljs-string">'Content-Length'</span>: <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">byteLength</span>(body),
  <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain; charset=utf-8'</span>,
});</code> <button class="copy-button">copy</button></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="#all_http2_responseenddata-encoding-callback"><code>response.end()</code></a> is called.</p>
<p>If <a href="#all_http2_responsewritechunk-encoding-callback"><code>response.write()</code></a> or <a href="#all_http2_responseenddata-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="#all_http2_responsesetheadername-value"><code>response.setHeader()</code></a>, they will be merged
with any headers passed to <a href="#all_http2_responsewriteheadstatuscode-statusmessage-headers"><code>response.writeHead()</code></a>, with the headers passed
to <a href="#all_http2_responsewriteheadstatuscode-statusmessage-headers"><code>response.writeHead()</code></a> given precedence.</p>
<pre><code class="language-js"><span class="hljs-comment">// Returns content-type = text/plain</span>
<span class="hljs-keyword">const</span> server = http2.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
  res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Content-Type'</span>, <span class="hljs-string">'text/html; charset=utf-8'</span>);
  res.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'X-Foo'</span>, <span class="hljs-string">'bar'</span>);
  res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain; charset=utf-8'</span> });
  res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'ok'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>Attempting to set a header field name or value that contains invalid characters
will result in a <a href="#all_errors_class-typeerror"><code>TypeError</code></a> being thrown.</p>
</section><section><h3>Collecting HTTP/2 performance metrics<span><a class="mark" href="#all_http2_collecting-http2-performance-metrics" id="all_http2_collecting-http2-performance-metrics">#</a></span><a aria-hidden="true" class="legacy" id="http2_collecting_http_2_performance_metrics"></a></h3>
<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 class="with-59-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">PerformanceObserver</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:perf_hooks'</span>;

<span class="hljs-keyword">const</span> obs = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PerformanceObserver</span>(<span class="hljs-function">(<span class="hljs-params">items</span>) =></span> {
  <span class="hljs-keyword">const</span> entry = items.<span class="hljs-title function_">getEntries</span>()[<span class="hljs-number">0</span>];
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(entry.<span class="hljs-property">entryType</span>);  <span class="hljs-comment">// prints 'http2'</span>
  <span class="hljs-keyword">if</span> (entry.<span class="hljs-property">name</span> === <span class="hljs-string">'Http2Session'</span>) {
    <span class="hljs-comment">// Entry contains statistics about the Http2Session</span>
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (entry.<span class="hljs-property">name</span> === <span class="hljs-string">'Http2Stream'</span>) {
    <span class="hljs-comment">// Entry contains statistics about the Http2Stream</span>
  }
});
obs.<span class="hljs-title function_">observe</span>({ <span class="hljs-attr">entryTypes</span>: [<span class="hljs-string">'http2'</span>] });</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">PerformanceObserver</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:perf_hooks'</span>);

<span class="hljs-keyword">const</span> obs = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PerformanceObserver</span>(<span class="hljs-function">(<span class="hljs-params">items</span>) =></span> {
  <span class="hljs-keyword">const</span> entry = items.<span class="hljs-title function_">getEntries</span>()[<span class="hljs-number">0</span>];
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(entry.<span class="hljs-property">entryType</span>);  <span class="hljs-comment">// prints 'http2'</span>
  <span class="hljs-keyword">if</span> (entry.<span class="hljs-property">name</span> === <span class="hljs-string">'Http2Session'</span>) {
    <span class="hljs-comment">// Entry contains statistics about the Http2Session</span>
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (entry.<span class="hljs-property">name</span> === <span class="hljs-string">'Http2Stream'</span>) {
    <span class="hljs-comment">// Entry contains statistics about the Http2Stream</span>
  }
});
obs.<span class="hljs-title function_">observe</span>({ <span class="hljs-attr">entryTypes</span>: [<span class="hljs-string">'http2'</span>] });</code><button class="copy-button">copy</button></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>
</section><section><h3>Note on <code>:authority</code> and <code>host</code><span><a class="mark" href="#all_http2_note-on-authority-and-host" id="all_http2_note-on-authority-and-host">#</a></span><a aria-hidden="true" class="legacy" id="http2_note_on_authority_and_host"></a></h3>
<p>HTTP/2 requires requests to have either the <code>:authority</code> pseudo-header
or the <code>host</code> header. Prefer <code>:authority</code> when constructing an HTTP/2
request directly, and <code>host</code> when converting from HTTP/1 (in proxies,
for instance).</p>
<p>The compatibility API falls back to <code>host</code> if <code>:authority</code> is not
present. See <a href="#all_http2_requestauthority"><code>request.authority</code></a> for more information. However,
if you don't use the compatibility API (or use <code>req.headers</code> directly),
you need to implement any fall-back behavior yourself.</p></section>
        </section>
<section><h2>HTTPS<span><a class="mark" href="#all_https_https" id="all_https_https">#</a></span><a aria-hidden="true" class="legacy" id="https_https"></a></h2>

<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/https.js">lib/https.js</a></p>
<p>HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a
separate module.</p>
<section><h3>Determining if crypto support is unavailable<span><a class="mark" href="#all_https_determining-if-crypto-support-is-unavailable" id="all_https_determining-if-crypto-support-is-unavailable">#</a></span><a aria-hidden="true" class="legacy" id="https_determining_if_crypto_support_is_unavailable"></a></h3>
<p>It is possible for Node.js to be built without including support for the
<code>node:crypto</code> module. In such cases, attempting to <code>import</code> from <code>https</code> or
calling <code>require('node:https')</code> will result in an error being thrown.</p>
<p>When using CommonJS, the error thrown can be caught using try/catch:</p>
<pre><code class="language-js cjs"><span class="hljs-keyword">let</span> https;
<span class="hljs-keyword">try</span> {
  https = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:https'</span>);
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'https support is disabled!'</span>);
}</code> <button class="copy-button">copy</button></pre>
<p>When using the lexical ESM <code>import</code> keyword, the error can only be
caught if a handler for <code>process.on('uncaughtException')</code> is registered
<em>before</em> any attempt to load the module is made (using, for instance,
a preload module).</p>
<p>When using ESM, if there is a chance that the code may be run on a build
of Node.js where crypto support is not enabled, consider using the
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import"><code>import()</code></a> function instead of the lexical <code>import</code> keyword:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">let</span> https;
<span class="hljs-keyword">try</span> {
  https = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:https'</span>);
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'https support is disabled!'</span>);
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>https.Agent</code><span><a class="mark" href="#all_https_class-httpsagent" id="all_https_class-httpsagent">#</a></span><a aria-hidden="true" class="legacy" id="https_class_https_agent"></a></h3>
<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="#all_https_class-httpsagent"><code>Agent</code></a> object for HTTPS similar to <a href="#all_http_class-httpagent"><code>http.Agent</code></a>. See
<a href="#all_https_httpsrequestoptions-callback"><code>https.request()</code></a> for more information.</p>
<h4><code>new Agent([options])</code><span><a class="mark" href="#all_https_new-agentoptions" id="all_https_new-agentoptions">#</a></span><a aria-hidden="true" class="legacy" id="https_new_agent_options"></a></h4>
<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><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="#all_http_new-agentoptions"><code>http.Agent(options)</code></a>, and
<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="#all_tls_session-resumption"><code>Session Resumption</code></a> for information about TLS session reuse.</p>
</li>
</ul>
</li>
</ul>
<h5>Event: <code>'keylog'</code><span><a class="mark" href="#all_https_event-keylog" id="all_https_event-keylog">#</a></span><a aria-hidden="true" class="legacy" id="https_event_keylog"></a></h5>
<div class="api_metadata">
<span>Added in: v13.2.0, v12.16.0</span>
</div>
<ul>
<li><code>line</code> <a href="#all_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="#all_tls_class-tlstlssocket" 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"><span class="hljs-comment">// ...</span>
https.<span class="hljs-property">globalAgent</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'keylog'</span>, <span class="hljs-function">(<span class="hljs-params">line, tlsSocket</span>) =></span> {
  fs.<span class="hljs-title function_">appendFileSync</span>(<span class="hljs-string">'/tmp/ssl-keys.log'</span>, line, { <span class="hljs-attr">mode</span>: <span class="hljs-number">0o600</span> });
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>https.Server</code><span><a class="mark" href="#all_https_class-httpsserver" id="all_https_class-httpsserver">#</a></span><a aria-hidden="true" class="legacy" id="https_class_https_server"></a></h3>
<div class="api_metadata">
<span>Added in: v0.3.4</span>
</div>
<ul>
<li>Extends: <a href="#all_tls_class-tlsserver" class="type">&#x3C;tls.Server></a></li>
</ul>
<p>See <a href="#all_http_class-httpserver"><code>http.Server</code></a> for more information.</p>
<h4><code>server.close([callback])</code><span><a class="mark" href="#all_https_serverclosecallback" id="all_https_serverclosecallback">#</a></span><a aria-hidden="true" class="legacy" id="https_server_close_callback"></a></h4>
<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="#all_https_class-httpsserver" class="type">&#x3C;https.Server></a></li>
</ul>
<p>See <a href="#all_http_serverclosecallback"><code>server.close()</code></a> in the <code>node:http</code> module.</p>
<h4><code>server[Symbol.asyncDispose]()</code><span><a class="mark" href="#all_https_serversymbolasyncdispose" id="all_https_serversymbolasyncdispose">#</a></span><a aria-hidden="true" class="legacy" id="https_server_symbol_asyncdispose"></a></h4>
<div class="api_metadata">
<span>Added in: v20.4.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Calls <a href="#all_https_serverclosecallback"><code>server.close()</code></a> and returns a promise that
fulfills when the server has closed.</p>
<h4><code>server.closeAllConnections()</code><span><a class="mark" href="#all_https_servercloseallconnections" id="all_https_servercloseallconnections">#</a></span><a aria-hidden="true" class="legacy" id="https_server_closeallconnections"></a></h4>
<div class="api_metadata">
<span>Added in: v18.2.0</span>
</div>
<p>See <a href="#all_http_servercloseallconnections"><code>server.closeAllConnections()</code></a> in the <code>node:http</code> module.</p>
<h4><code>server.closeIdleConnections()</code><span><a class="mark" href="#all_https_servercloseidleconnections" id="all_https_servercloseidleconnections">#</a></span><a aria-hidden="true" class="legacy" id="https_server_closeidleconnections"></a></h4>
<div class="api_metadata">
<span>Added in: v18.2.0</span>
</div>
<p>See <a href="#all_http_servercloseidleconnections"><code>server.closeIdleConnections()</code></a> in the <code>node:http</code> module.</p>
<h4><code>server.headersTimeout</code><span><a class="mark" href="#all_https_serverheaderstimeout" id="all_https_serverheaderstimeout">#</a></span><a aria-hidden="true" class="legacy" id="https_server_headerstimeout"></a></h4>
<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="#all_http_serverheaderstimeout"><code>server.headersTimeout</code></a> in the <code>node:http</code> module.</p>
<h4><code>server.listen()</code><span><a class="mark" href="#all_https_serverlisten" id="all_https_serverlisten">#</a></span><a aria-hidden="true" class="legacy" id="https_server_listen"></a></h4>
<p>Starts the HTTPS server listening for encrypted connections.
This method is identical to <a href="#all_net_serverlisten"><code>server.listen()</code></a> from <a href="#all_net_class-netserver"><code>net.Server</code></a>.</p>
<h4><code>server.maxHeadersCount</code><span><a class="mark" href="#all_https_servermaxheaderscount" id="all_https_servermaxheaderscount">#</a></span><a aria-hidden="true" class="legacy" id="https_server_maxheaderscount"></a></h4>
<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="#all_http_servermaxheaderscount"><code>server.maxHeadersCount</code></a> in the <code>node:http</code> module.</p>
<h4><code>server.requestTimeout</code><span><a class="mark" href="#all_https_serverrequesttimeout" id="all_https_serverrequesttimeout">#</a></span><a aria-hidden="true" class="legacy" id="https_server_requesttimeout"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>The default request timeout changed from no timeout to 300s (5 minutes).</p></td></tr>
<tr><td>v14.11.0</td>
<td><p><span>Added in: v14.11.0</span></p></td></tr>
</tbody></table>
</details>
</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>300000</code></li>
</ul>
<p>See <a href="#all_http_serverrequesttimeout"><code>server.requestTimeout</code></a> in the <code>node:http</code> module.</p>
<h4><code>server.setTimeout([msecs][, callback])</code><span><a class="mark" href="#all_https_serversettimeoutmsecs-callback" id="all_https_serversettimeoutmsecs-callback">#</a></span><a aria-hidden="true" class="legacy" id="https_server_settimeout_msecs_callback"></a></h4>
<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="#all_https_class-httpsserver" class="type">&#x3C;https.Server></a></li>
</ul>
<p>See <a href="#all_http_serversettimeoutmsecs-callback"><code>server.setTimeout()</code></a> in the <code>node:http</code> module.</p>
<h4><code>server.timeout</code><span><a class="mark" href="#all_https_servertimeout" id="all_https_servertimeout">#</a></span><a aria-hidden="true" class="legacy" id="https_server_timeout"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.0.0</td>
<td><p>The default timeout changed from 120s to 0 (no timeout).</p></td></tr>
<tr><td>v0.11.2</td>
<td><p><span>Added in: v0.11.2</span></p></td></tr>
</tbody></table>
</details>
</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> 0 (no timeout)</li>
</ul>
<p>See <a href="#all_http_servertimeout"><code>server.timeout</code></a> in the <code>node:http</code> module.</p>
<h4><code>server.keepAliveTimeout</code><span><a class="mark" href="#all_https_serverkeepalivetimeout" id="all_https_serverkeepalivetimeout">#</a></span><a aria-hidden="true" class="legacy" id="https_server_keepalivetimeout"></a></h4>
<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="#all_http_serverkeepalivetimeout"><code>server.keepAliveTimeout</code></a> in the <code>node:http</code> module.</p>
</section><section><h3><code>https.createServer([options][, requestListener])</code><span><a class="mark" href="#all_https_httpscreateserveroptions-requestlistener" id="all_https_httpscreateserveroptions-requestlistener">#</a></span><a aria-hidden="true" class="legacy" id="https_https_createserver_options_requestlistener"></a></h3>
<div class="api_metadata">
<span>Added in: v0.3.4</span>
</div>
<ul>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Accepts <code>options</code> from <a href="#all_tls_tlscreateserveroptions-secureconnectionlistener"><code>tls.createServer()</code></a>,
<a href="#all_tls_tlscreatesecurecontextoptions"><code>tls.createSecureContext()</code></a> and <a href="#all_http_httpcreateserveroptions-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="#all_https_class-httpsserver" class="type">&#x3C;https.Server></a></li>
</ul>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// curl -k https://localhost:8000/</span>
<span class="hljs-keyword">import</span> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:https'</span>;
<span class="hljs-keyword">import</span> { readFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-keyword">const</span> options = {
  <span class="hljs-attr">key</span>: <span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'private-key.pem'</span>),
  <span class="hljs-attr">cert</span>: <span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'certificate.pem'</span>),
};

<span class="hljs-title function_">createServer</span>(options, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
  res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>);
  res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'hello world\n'</span>);
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);</code><code class="language-js cjs"><span class="hljs-comment">// curl -k https://localhost:8000/</span>
<span class="hljs-keyword">const</span> https = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:https'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);

<span class="hljs-keyword">const</span> options = {
  <span class="hljs-attr">key</span>: fs.<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'private-key.pem'</span>),
  <span class="hljs-attr">cert</span>: fs.<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'certificate.pem'</span>),
};

https.<span class="hljs-title function_">createServer</span>(options, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
  res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>);
  res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'hello world\n'</span>);
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);</code><button class="copy-button">copy</button></pre>
<p>Or</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:https'</span>;
<span class="hljs-keyword">import</span> { readFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-keyword">const</span> options = {
  <span class="hljs-attr">pfx</span>: <span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'test_cert.pfx'</span>),
  <span class="hljs-attr">passphrase</span>: <span class="hljs-string">'sample'</span>,
};

<span class="hljs-title function_">createServer</span>(options, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
  res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>);
  res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'hello world\n'</span>);
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> https = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:https'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);

<span class="hljs-keyword">const</span> options = {
  <span class="hljs-attr">pfx</span>: fs.<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'test_cert.pfx'</span>),
  <span class="hljs-attr">passphrase</span>: <span class="hljs-string">'sample'</span>,
};

https.<span class="hljs-title function_">createServer</span>(options, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
  res.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>);
  res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'hello world\n'</span>);
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>);</code><button class="copy-button">copy</button></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 <span class="hljs-string">'/CN=localhost'</span> \
  -keyout private-key.pem -out certificate.pem</code> <button class="copy-button">copy</button></pre>
<p>Then, to generate the <code>pfx</code> certificate for this example, run:</p>
<pre><code class="language-bash">openssl pkcs12 -certpbe AES-256-CBC -<span class="hljs-built_in">export</span> -out test_cert.pfx \
  -inkey private-key.pem -<span class="hljs-keyword">in</span> certificate.pem -passout pass:sample</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>https.get(options[, callback])</code><span><a class="mark" href="#all_https_httpsgetoptions-callback" id="all_https_httpsgetoptions-callback">#</a></span><a aria-hidden="true" class="legacy" id="https_https_get_options_callback"></a></h3>
</section><section><h3><code>https.get(url[, options][, callback])</code><span><a class="mark" href="#all_https_httpsgeturl-options-callback" id="all_https_httpsgeturl-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="https_https_get_url_options_callback"></a></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>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="#all_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="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></a> Accepts the same <code>options</code> as
<a href="#all_https_httpsrequestoptions-callback"><code>https.request()</code></a>, with the method set to GET by default.</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="#all_http_httpgetoptions-callback"><code>http.get()</code></a> but for HTTPS.</p>
<p><code>options</code> can be an object, a string, or a <a href="#all_url_the-whatwg-url-api"><code>URL</code></a> object. If <code>options</code> is a
string, it is automatically parsed with <a href="#all_url_new-urlinput-base"><code>new URL()</code></a>. If it is a <a href="#all_url_the-whatwg-url-api"><code>URL</code></a>
object, it will be automatically converted to an ordinary <code>options</code> object.</p>

<pre class="with-36-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { get } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:https'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-title function_">get</span>(<span class="hljs-string">'https://encrypted.google.com/'</span>, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'statusCode:'</span>, res.<span class="hljs-property">statusCode</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'headers:'</span>, res.<span class="hljs-property">headers</span>);

  res.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">d</span>) =></span> {
    process.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">write</span>(d);
  });

}).<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(e);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> https = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:https'</span>);

https.<span class="hljs-title function_">get</span>(<span class="hljs-string">'https://encrypted.google.com/'</span>, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'statusCode:'</span>, res.<span class="hljs-property">statusCode</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'headers:'</span>, res.<span class="hljs-property">headers</span>);

  res.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">d</span>) =></span> {
    process.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">write</span>(d);
  });

}).<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(e);
});</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>https.globalAgent</code><span><a class="mark" href="#all_https_httpsglobalagent" id="all_https_httpsglobalagent">#</a></span><a aria-hidden="true" class="legacy" id="https_https_globalagent"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>The agent now uses HTTP Keep-Alive and a 5 second timeout by default.</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>
<p>Global instance of <a href="#all_https_class-httpsagent"><code>https.Agent</code></a> for all HTTPS client requests. Diverges
from a default <a href="#all_https_class-httpsagent"><code>https.Agent</code></a> configuration by having <code>keepAlive</code> enabled and
a <code>timeout</code> of 5 seconds.</p>
</section><section><h3><code>https.request(options[, callback])</code><span><a class="mark" href="#all_https_httpsrequestoptions-callback" id="all_https_httpsrequestoptions-callback">#</a></span><a aria-hidden="true" class="legacy" id="https_https_request_options_callback"></a></h3>
</section><section><h3><code>https.request(url[, options][, callback])</code><span><a class="mark" href="#all_https_httpsrequesturl-options-callback" id="all_https_httpsrequesturl-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="https_https_request_url_options_callback"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.16.0</td>
<td><p>The <code>clientCertEngine</code> option depends on custom engine support in OpenSSL which is deprecated in OpenSSL 3.</p></td></tr>
<tr><td>v16.7.0, v14.18.0</td>
<td><p>When using a <code>URL</code> object parsed username and password will now be properly URI decoded.</p></td></tr>
<tr><td>v14.1.0, v13.14.0</td>
<td><p>The <code>highWaterMark</code> option is accepted 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>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="#all_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="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></a> Accepts all <code>options</code> from
<a href="#all_http_httprequestoptions-callback"><code>http.request()</code></a>, with some differences in default values:
<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>
<li>Returns: <a href="#all_http_class-httpclientrequest" class="type">&#x3C;http.ClientRequest></a></li>
</ul>
<p>Makes a request to a secure web server.</p>
<p>The following additional <code>options</code> from <a href="#all_tls_tlsconnectoptions-callback"><code>tls.connect()</code></a> are also accepted:
<code>ca</code>, <code>cert</code>, <code>ciphers</code>, <code>clientCertEngine</code> (deprecated), <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>,
<code>highWaterMark</code>.</p>
<p><code>options</code> can be an object, a string, or a <a href="#all_url_the-whatwg-url-api"><code>URL</code></a> object. If <code>options</code> is a
string, it is automatically parsed with <a href="#all_url_new-urlinput-base"><code>new URL()</code></a>. If it is a <a href="#all_url_the-whatwg-url-api"><code>URL</code></a>
object, it will be automatically converted to an ordinary <code>options</code> object.</p>
<p><code>https.request()</code> returns an instance of the <a href="#all_http_class-httpclientrequest"><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 class="with-37-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { request } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:https'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-keyword">const</span> options = {
  <span class="hljs-attr">hostname</span>: <span class="hljs-string">'encrypted.google.com'</span>,
  <span class="hljs-attr">port</span>: <span class="hljs-number">443</span>,
  <span class="hljs-attr">path</span>: <span class="hljs-string">'/'</span>,
  <span class="hljs-attr">method</span>: <span class="hljs-string">'GET'</span>,
};

<span class="hljs-keyword">const</span> req = <span class="hljs-title function_">request</span>(options, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'statusCode:'</span>, res.<span class="hljs-property">statusCode</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'headers:'</span>, res.<span class="hljs-property">headers</span>);

  res.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">d</span>) =></span> {
    process.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">write</span>(d);
  });
});

req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(e);
});
req.<span class="hljs-title function_">end</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> https = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:https'</span>);

<span class="hljs-keyword">const</span> options = {
  <span class="hljs-attr">hostname</span>: <span class="hljs-string">'encrypted.google.com'</span>,
  <span class="hljs-attr">port</span>: <span class="hljs-number">443</span>,
  <span class="hljs-attr">path</span>: <span class="hljs-string">'/'</span>,
  <span class="hljs-attr">method</span>: <span class="hljs-string">'GET'</span>,
};

<span class="hljs-keyword">const</span> req = https.<span class="hljs-title function_">request</span>(options, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'statusCode:'</span>, res.<span class="hljs-property">statusCode</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'headers:'</span>, res.<span class="hljs-property">headers</span>);

  res.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">d</span>) =></span> {
    process.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">write</span>(d);
  });
});

req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(e);
});
req.<span class="hljs-title function_">end</span>();</code><button class="copy-button">copy</button></pre>
<p>Example using options from <a href="#all_tls_tlsconnectoptions-callback"><code>tls.connect()</code></a>:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> options = {
  <span class="hljs-attr">hostname</span>: <span class="hljs-string">'encrypted.google.com'</span>,
  <span class="hljs-attr">port</span>: <span class="hljs-number">443</span>,
  <span class="hljs-attr">path</span>: <span class="hljs-string">'/'</span>,
  <span class="hljs-attr">method</span>: <span class="hljs-string">'GET'</span>,
  <span class="hljs-attr">key</span>: fs.<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'private-key.pem'</span>),
  <span class="hljs-attr">cert</span>: fs.<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'certificate.pem'</span>),
};
options.<span class="hljs-property">agent</span> = <span class="hljs-keyword">new</span> https.<span class="hljs-title class_">Agent</span>(options);

<span class="hljs-keyword">const</span> req = https.<span class="hljs-title function_">request</span>(options, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
  <span class="hljs-comment">// ...</span>
});</code> <button class="copy-button">copy</button></pre>
<p>Alternatively, opt out of connection pooling by not using an <a href="#all_https_class-httpsagent"><code>Agent</code></a>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> options = {
  <span class="hljs-attr">hostname</span>: <span class="hljs-string">'encrypted.google.com'</span>,
  <span class="hljs-attr">port</span>: <span class="hljs-number">443</span>,
  <span class="hljs-attr">path</span>: <span class="hljs-string">'/'</span>,
  <span class="hljs-attr">method</span>: <span class="hljs-string">'GET'</span>,
  <span class="hljs-attr">key</span>: fs.<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'private-key.pem'</span>),
  <span class="hljs-attr">cert</span>: fs.<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'certificate.pem'</span>),
  <span class="hljs-attr">agent</span>: <span class="hljs-literal">false</span>,
};

<span class="hljs-keyword">const</span> req = https.<span class="hljs-title function_">request</span>(options, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
  <span class="hljs-comment">// ...</span>
});</code> <button class="copy-button">copy</button></pre>
<p>Example using a <a href="#all_url_the-whatwg-url-api"><code>URL</code></a> as <code>options</code>:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> options = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://abc:xyz@example.com'</span>);

<span class="hljs-keyword">const</span> req = https.<span class="hljs-title function_">request</span>(options, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
  <span class="hljs-comment">// ...</span>
});</code> <button class="copy-button">copy</button></pre>
<p>Example pinning on certificate fingerprint, or the public key (similar to
<code>pin-sha256</code>):</p>

<pre class="with-47-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { checkServerIdentity } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:tls'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Agent</span>, request } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:https'</span>;
<span class="hljs-keyword">import</span> { createHash } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:crypto'</span>;

<span class="hljs-keyword">function</span> <span class="hljs-title function_">sha256</span>(<span class="hljs-params">s</span>) {
  <span class="hljs-keyword">return</span> <span class="hljs-title function_">createHash</span>(<span class="hljs-string">'sha256'</span>).<span class="hljs-title function_">update</span>(s).<span class="hljs-title function_">digest</span>(<span class="hljs-string">'base64'</span>);
}
<span class="hljs-keyword">const</span> options = {
  <span class="hljs-attr">hostname</span>: <span class="hljs-string">'github.com'</span>,
  <span class="hljs-attr">port</span>: <span class="hljs-number">443</span>,
  <span class="hljs-attr">path</span>: <span class="hljs-string">'/'</span>,
  <span class="hljs-attr">method</span>: <span class="hljs-string">'GET'</span>,
  <span class="hljs-attr">checkServerIdentity</span>: <span class="hljs-keyword">function</span>(<span class="hljs-params">host, cert</span>) {
    <span class="hljs-comment">// Make sure the certificate is issued to the host we are connected to</span>
    <span class="hljs-keyword">const</span> err = <span class="hljs-title function_">checkServerIdentity</span>(host, cert);
    <span class="hljs-keyword">if</span> (err) {
      <span class="hljs-keyword">return</span> err;
    }

    <span class="hljs-comment">// Pin the public key, similar to HPKP pin-sha256 pinning</span>
    <span class="hljs-keyword">const</span> pubkey256 = <span class="hljs-string">'SIXvRyDmBJSgatgTQRGbInBaAK+hZOQ18UmrSwnDlK8='</span>;
    <span class="hljs-keyword">if</span> (<span class="hljs-title function_">sha256</span>(cert.<span class="hljs-property">pubkey</span>) !== pubkey256) {
      <span class="hljs-keyword">const</span> msg = <span class="hljs-string">'Certificate verification error: '</span> +
        <span class="hljs-string">`The public key of '<span class="hljs-subst">${cert.subject.CN}</span>' `</span> +
        <span class="hljs-string">'does not match our pinned fingerprint'</span>;
      <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(msg);
    }

    <span class="hljs-comment">// Pin the exact certificate, rather than the pub key</span>
    <span class="hljs-keyword">const</span> cert256 = <span class="hljs-string">'FD:6E:9B:0E:F3:98:BC:D9:04:C3:B2:EC:16:7A:7B:'</span> +
      <span class="hljs-string">'0F:DA:72:01:C9:03:C5:3A:6A:6A:E5:D0:41:43:63:EF:65'</span>;
    <span class="hljs-keyword">if</span> (cert.<span class="hljs-property">fingerprint256</span> !== cert256) {
      <span class="hljs-keyword">const</span> msg = <span class="hljs-string">'Certificate verification error: '</span> +
        <span class="hljs-string">`The certificate of '<span class="hljs-subst">${cert.subject.CN}</span>' `</span> +
        <span class="hljs-string">'does not match our pinned fingerprint'</span>;
      <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(msg);
    }

    <span class="hljs-comment">// This loop is informational only.</span>
    <span class="hljs-comment">// Print the certificate and public key fingerprints of all certs in the</span>
    <span class="hljs-comment">// chain. Its common to pin the public key of the issuer on the public</span>
    <span class="hljs-comment">// internet, while pinning the public key of the service in sensitive</span>
    <span class="hljs-comment">// environments.</span>
    <span class="hljs-keyword">let</span> lastprint256;
    <span class="hljs-keyword">do</span> {
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Subject Common Name:'</span>, cert.<span class="hljs-property">subject</span>.<span class="hljs-property">CN</span>);
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'  Certificate SHA256 fingerprint:'</span>, cert.<span class="hljs-property">fingerprint256</span>);

      <span class="hljs-keyword">const</span> hash = <span class="hljs-title function_">createHash</span>(<span class="hljs-string">'sha256'</span>);
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'  Public key ping-sha256:'</span>, <span class="hljs-title function_">sha256</span>(cert.<span class="hljs-property">pubkey</span>));

      lastprint256 = cert.<span class="hljs-property">fingerprint256</span>;
      cert = cert.<span class="hljs-property">issuerCertificate</span>;
    } <span class="hljs-keyword">while</span> (cert.<span class="hljs-property">fingerprint256</span> !== lastprint256);

  },
};

options.<span class="hljs-property">agent</span> = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Agent</span>(options);
<span class="hljs-keyword">const</span> req = <span class="hljs-title function_">request</span>(options, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'All OK. Server matched our pinned cert or public key'</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'statusCode:'</span>, res.<span class="hljs-property">statusCode</span>);

  res.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">d</span>) =></span> {});
});

req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(e.<span class="hljs-property">message</span>);
});
req.<span class="hljs-title function_">end</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> tls = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:tls'</span>);
<span class="hljs-keyword">const</span> https = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:https'</span>);
<span class="hljs-keyword">const</span> crypto = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);

<span class="hljs-keyword">function</span> <span class="hljs-title function_">sha256</span>(<span class="hljs-params">s</span>) {
  <span class="hljs-keyword">return</span> crypto.<span class="hljs-title function_">createHash</span>(<span class="hljs-string">'sha256'</span>).<span class="hljs-title function_">update</span>(s).<span class="hljs-title function_">digest</span>(<span class="hljs-string">'base64'</span>);
}
<span class="hljs-keyword">const</span> options = {
  <span class="hljs-attr">hostname</span>: <span class="hljs-string">'github.com'</span>,
  <span class="hljs-attr">port</span>: <span class="hljs-number">443</span>,
  <span class="hljs-attr">path</span>: <span class="hljs-string">'/'</span>,
  <span class="hljs-attr">method</span>: <span class="hljs-string">'GET'</span>,
  <span class="hljs-attr">checkServerIdentity</span>: <span class="hljs-keyword">function</span>(<span class="hljs-params">host, cert</span>) {
    <span class="hljs-comment">// Make sure the certificate is issued to the host we are connected to</span>
    <span class="hljs-keyword">const</span> err = tls.<span class="hljs-title function_">checkServerIdentity</span>(host, cert);
    <span class="hljs-keyword">if</span> (err) {
      <span class="hljs-keyword">return</span> err;
    }

    <span class="hljs-comment">// Pin the public key, similar to HPKP pin-sha256 pinning</span>
    <span class="hljs-keyword">const</span> pubkey256 = <span class="hljs-string">'SIXvRyDmBJSgatgTQRGbInBaAK+hZOQ18UmrSwnDlK8='</span>;
    <span class="hljs-keyword">if</span> (<span class="hljs-title function_">sha256</span>(cert.<span class="hljs-property">pubkey</span>) !== pubkey256) {
      <span class="hljs-keyword">const</span> msg = <span class="hljs-string">'Certificate verification error: '</span> +
        <span class="hljs-string">`The public key of '<span class="hljs-subst">${cert.subject.CN}</span>' `</span> +
        <span class="hljs-string">'does not match our pinned fingerprint'</span>;
      <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(msg);
    }

    <span class="hljs-comment">// Pin the exact certificate, rather than the pub key</span>
    <span class="hljs-keyword">const</span> cert256 = <span class="hljs-string">'FD:6E:9B:0E:F3:98:BC:D9:04:C3:B2:EC:16:7A:7B:'</span> +
      <span class="hljs-string">'0F:DA:72:01:C9:03:C5:3A:6A:6A:E5:D0:41:43:63:EF:65'</span>;
    <span class="hljs-keyword">if</span> (cert.<span class="hljs-property">fingerprint256</span> !== cert256) {
      <span class="hljs-keyword">const</span> msg = <span class="hljs-string">'Certificate verification error: '</span> +
        <span class="hljs-string">`The certificate of '<span class="hljs-subst">${cert.subject.CN}</span>' `</span> +
        <span class="hljs-string">'does not match our pinned fingerprint'</span>;
      <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(msg);
    }

    <span class="hljs-comment">// This loop is informational only.</span>
    <span class="hljs-comment">// Print the certificate and public key fingerprints of all certs in the</span>
    <span class="hljs-comment">// chain. Its common to pin the public key of the issuer on the public</span>
    <span class="hljs-comment">// internet, while pinning the public key of the service in sensitive</span>
    <span class="hljs-comment">// environments.</span>
    <span class="hljs-keyword">do</span> {
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Subject Common Name:'</span>, cert.<span class="hljs-property">subject</span>.<span class="hljs-property">CN</span>);
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'  Certificate SHA256 fingerprint:'</span>, cert.<span class="hljs-property">fingerprint256</span>);

      hash = crypto.<span class="hljs-title function_">createHash</span>(<span class="hljs-string">'sha256'</span>);
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'  Public key ping-sha256:'</span>, <span class="hljs-title function_">sha256</span>(cert.<span class="hljs-property">pubkey</span>));

      lastprint256 = cert.<span class="hljs-property">fingerprint256</span>;
      cert = cert.<span class="hljs-property">issuerCertificate</span>;
    } <span class="hljs-keyword">while</span> (cert.<span class="hljs-property">fingerprint256</span> !== lastprint256);

  },
};

options.<span class="hljs-property">agent</span> = <span class="hljs-keyword">new</span> https.<span class="hljs-title class_">Agent</span>(options);
<span class="hljs-keyword">const</span> req = https.<span class="hljs-title function_">request</span>(options, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'All OK. Server matched our pinned cert or public key'</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'statusCode:'</span>, res.<span class="hljs-property">statusCode</span>);

  res.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">d</span>) =></span> {});
});

req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(e.<span class="hljs-property">message</span>);
});
req.<span class="hljs-title function_">end</span>();</code><button class="copy-button">copy</button></pre>
<p>Outputs for example:</p>
<pre><code class="language-text">Subject Common Name: github.com
  Certificate SHA256 fingerprint: FD:6E:9B:0E:F3:98:BC:D9:04:C3:B2:EC:16:7A:7B:0F:DA:72:01:C9:03:C5:3A:6A:6A:E5:D0:41:43:63:EF:65
  Public key ping-sha256: SIXvRyDmBJSgatgTQRGbInBaAK+hZOQ18UmrSwnDlK8=
Subject Common Name: Sectigo ECC Domain Validation Secure Server CA
  Certificate SHA256 fingerprint: 61:E9:73:75:E9:F6:DA:98:2F:F5:C1:9E:2F:94:E6:6C:4E:35:B6:83:7C:E3:B9:14:D2:24:5C:7F:5F:65:82:5F
  Public key ping-sha256: Eep0p/AsSa9lFUH6KT2UY+9s1Z8v7voAPkQ4fGknZ2g=
Subject Common Name: USERTrust ECC Certification Authority
  Certificate SHA256 fingerprint: A6:CF:64:DB:B4:C8:D5:FD:19:CE:48:89:60:68:DB:03:B5:33:A8:D1:33:6C:62:56:A8:7D:00:CB:B3:DE:F3:EA
  Public key ping-sha256: UJM2FOhG9aTNY0Pg4hgqjNzZ/lQBiMGRxPD5Y2/e0bw=
Subject Common Name: AAA Certificate Services
  Certificate SHA256 fingerprint: D7:A7:A0:FB:5D:7E:27:31:D7:71:E9:48:4E:BC:DE:F7:1D:5F:0C:3E:0A:29:48:78:2B:C8:3E:E0:EA:69:9E:F4
  Public key ping-sha256: vRU+17BDT2iGsXvOi76E7TQMcTLXAqj0+jGPdW7L1vM=
All OK. Server matched our pinned cert or public key
statusCode: 200</code> <button class="copy-button">copy</button></pre></section>
        </section>
<section><h2>Inspector<span><a class="mark" href="#all_inspector_inspector" id="all_inspector_inspector">#</a></span><a aria-hidden="true" class="legacy" id="inspector_inspector"></a></h2>

<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/inspector.js">lib/inspector.js</a></p>
<p>The <code>node:inspector</code> module provides an API for interacting with the V8
inspector.</p>
<p>It can be accessed using:</p>

<pre class="with-53-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> inspector <span class="hljs-keyword">from</span> <span class="hljs-string">'node:inspector/promises'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> inspector = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:inspector/promises'</span>);</code><button class="copy-button">copy</button></pre>
<p>or</p>

<pre class="with-44-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> inspector <span class="hljs-keyword">from</span> <span class="hljs-string">'node:inspector'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> inspector = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:inspector'</span>);</code><button class="copy-button">copy</button></pre>
<section><h3>Promises API<span><a class="mark" href="#all_inspector_promises-api" id="all_inspector_promises-api">#</a></span><a aria-hidden="true" class="legacy" id="inspector_promises_api"></a></h3>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<div class="api_metadata">
<span>Added in: v19.0.0</span>
</div>
<h4>Class: <code>inspector.Session</code><span><a class="mark" href="#all_inspector_class-inspectorsession" id="all_inspector_class-inspectorsession">#</a></span><a aria-hidden="true" class="legacy" id="inspector_class_inspector_session"></a></h4>
<ul>
<li>Extends: <a href="#all_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>
<h5><code>new inspector.Session()</code><span><a class="mark" href="#all_inspector_new-inspectorsession" id="all_inspector_new-inspectorsession">#</a></span><a aria-hidden="true" class="legacy" id="inspector_new_inspector_session"></a></h5>
<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="#all_inspector_sessionconnect"><code>session.connect()</code></a> before the messages
can be dispatched to the inspector backend.</p>
<p>When using <code>Session</code>, the object outputted by the console API will not be
released, unless we performed manually <code>Runtime.DiscardConsoleEntries</code>
command.</p>
<h5>Event: <code>'inspectorNotification'</code><span><a class="mark" href="#all_inspector_event-inspectornotification" id="all_inspector_event-inspectornotification">#</a></span><a aria-hidden="true" class="legacy" id="inspector_event_inspectornotification"></a></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/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.<span class="hljs-title function_">on</span>(<span class="hljs-string">'inspectorNotification'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(message.<span class="hljs-property">method</span>));
<span class="hljs-comment">// Debugger.paused</span>
<span class="hljs-comment">// Debugger.resumed</span></code> <button class="copy-button">copy</button></pre>
<blockquote>
<p><strong>Caveat</strong> Breakpoints with same-thread session is not recommended, see
<a href="#all_inspector_support-of-breakpoints">support of breakpoints</a>.</p>
</blockquote>
<p>It is also possible to subscribe only to notifications with specific method:</p>
<h5>Event: <code>&#x3C;inspector-protocol-method></code>;<span><a class="mark" href="#all_inspector_event-inspector-protocol-method" id="all_inspector_event-inspector-protocol-method">#</a></span><a aria-hidden="true" class="legacy" id="inspector_event_inspector_protocol_method"></a></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/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.<span class="hljs-title function_">on</span>(<span class="hljs-string">'Debugger.paused'</span>, <span class="hljs-function">(<span class="hljs-params">{ params }</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(params.<span class="hljs-property">hitBreakpoints</span>);
});
<span class="hljs-comment">// [ '/the/file/that/has/the/breakpoint.js:11:0' ]</span></code> <button class="copy-button">copy</button></pre>
<blockquote>
<p><strong>Caveat</strong> Breakpoints with same-thread session is not recommended, see
<a href="#all_inspector_support-of-breakpoints">support of breakpoints</a>.</p>
</blockquote>
<h5><code>session.connect()</code><span><a class="mark" href="#all_inspector_sessionconnect" id="all_inspector_sessionconnect">#</a></span><a aria-hidden="true" class="legacy" id="inspector_session_connect"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<p>Connects a session to the inspector back-end.</p>
<h5><code>session.connectToMainThread()</code><span><a class="mark" href="#all_inspector_sessionconnecttomainthread" id="all_inspector_sessionconnecttomainthread">#</a></span><a aria-hidden="true" class="legacy" id="inspector_session_connecttomainthread"></a></h5>
<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>
<h5><code>session.disconnect()</code><span><a class="mark" href="#all_inspector_sessiondisconnect" id="all_inspector_sessiondisconnect">#</a></span><a aria-hidden="true" class="legacy" id="inspector_session_disconnect"></a></h5>
<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="#all_inspector_sessionconnect"><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>
<h5><code>session.post(method[, params])</code><span><a class="mark" href="#all_inspector_sessionpostmethod-params" id="all_inspector_sessionpostmethod-params">#</a></span><a aria-hidden="true" class="legacy" id="inspector_session_post_method_params"></a></h5>
<div class="api_metadata">
<span>Added in: v19.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>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></li>
</ul>
<p>Posts a message to the inspector back-end.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Session</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:inspector/promises'</span>;
<span class="hljs-keyword">try</span> {
  <span class="hljs-keyword">const</span> session = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Session</span>();
  session.<span class="hljs-title function_">connect</span>();
  <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> session.<span class="hljs-title function_">post</span>(<span class="hljs-string">'Runtime.evaluate'</span>, { <span class="hljs-attr">expression</span>: <span class="hljs-string">'2 + 2'</span> });
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result);
} <span class="hljs-keyword">catch</span> (error) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(error);
}
<span class="hljs-comment">// Output: { result: { type: 'number', value: 4, description: '4' } }</span></code> <button class="copy-button">copy</button></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>
<h5>Example usage<span><a class="mark" href="#all_inspector_example-usage" id="all_inspector_example-usage">#</a></span><a aria-hidden="true" class="legacy" id="inspector_example_usage"></a></h5>
<p>Apart from the debugger, various V8 Profilers are available through the DevTools
protocol.</p>
<h6>CPU profiler<span><a class="mark" href="#all_inspector_cpu-profiler" id="all_inspector_cpu-profiler">#</a></span><a aria-hidden="true" class="legacy" id="inspector_cpu_profiler"></a></h6>
<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 mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Session</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:inspector/promises'</span>;
<span class="hljs-keyword">import</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">const</span> session = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Session</span>();
session.<span class="hljs-title function_">connect</span>();

<span class="hljs-keyword">await</span> session.<span class="hljs-title function_">post</span>(<span class="hljs-string">'Profiler.enable'</span>);
<span class="hljs-keyword">await</span> session.<span class="hljs-title function_">post</span>(<span class="hljs-string">'Profiler.start'</span>);
<span class="hljs-comment">// Invoke business logic under measurement here...</span>

<span class="hljs-comment">// some time later...</span>
<span class="hljs-keyword">const</span> { profile } = <span class="hljs-keyword">await</span> session.<span class="hljs-title function_">post</span>(<span class="hljs-string">'Profiler.stop'</span>);

<span class="hljs-comment">// Write profile to disk, upload, etc.</span>
fs.<span class="hljs-title function_">writeFileSync</span>(<span class="hljs-string">'./profile.cpuprofile'</span>, <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(profile));</code> <button class="copy-button">copy</button></pre>
<h6>Heap profiler<span><a class="mark" href="#all_inspector_heap-profiler" id="all_inspector_heap-profiler">#</a></span><a aria-hidden="true" class="legacy" id="inspector_heap_profiler"></a></h6>
<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 mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Session</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:inspector/promises'</span>;
<span class="hljs-keyword">import</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">const</span> session = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Session</span>();

<span class="hljs-keyword">const</span> fd = fs.<span class="hljs-title function_">openSync</span>(<span class="hljs-string">'profile.heapsnapshot'</span>, <span class="hljs-string">'w'</span>);

session.<span class="hljs-title function_">connect</span>();

session.<span class="hljs-title function_">on</span>(<span class="hljs-string">'HeapProfiler.addHeapSnapshotChunk'</span>, <span class="hljs-function">(<span class="hljs-params">m</span>) =></span> {
  fs.<span class="hljs-title function_">writeSync</span>(fd, m.<span class="hljs-property">params</span>.<span class="hljs-property">chunk</span>);
});

<span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> session.<span class="hljs-title function_">post</span>(<span class="hljs-string">'HeapProfiler.takeHeapSnapshot'</span>, <span class="hljs-literal">null</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'HeapProfiler.takeHeapSnapshot done:'</span>, result);
session.<span class="hljs-title function_">disconnect</span>();
fs.<span class="hljs-title function_">closeSync</span>(fd);</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Callback API<span><a class="mark" href="#all_inspector_callback-api" id="all_inspector_callback-api">#</a></span><a aria-hidden="true" class="legacy" id="inspector_callback_api"></a></h3>
<h4>Class: <code>inspector.Session</code><span><a class="mark" href="#all_inspector_class-inspectorsession_1" id="all_inspector_class-inspectorsession_1">#</a></span><a aria-hidden="true" class="legacy" id="inspector_class_inspector_session_1"></a></h4>
<ul>
<li>Extends: <a href="#all_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>
<h5><code>new inspector.Session()</code><span><a class="mark" href="#all_inspector_new-inspectorsession_1" id="all_inspector_new-inspectorsession_1">#</a></span><a aria-hidden="true" class="legacy" id="inspector_new_inspector_session_1"></a></h5>
<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="#all_inspector_sessionconnect"><code>session.connect()</code></a> before the messages
can be dispatched to the inspector backend.</p>
<p>When using <code>Session</code>, the object outputted by the console API will not be
released, unless we performed manually <code>Runtime.DiscardConsoleEntries</code>
command.</p>
<h5>Event: <code>'inspectorNotification'</code><span><a class="mark" href="#all_inspector_event-inspectornotification_1" id="all_inspector_event-inspectornotification_1">#</a></span><a aria-hidden="true" class="legacy" id="inspector_event_inspectornotification_1"></a></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/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.<span class="hljs-title function_">on</span>(<span class="hljs-string">'inspectorNotification'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(message.<span class="hljs-property">method</span>));
<span class="hljs-comment">// Debugger.paused</span>
<span class="hljs-comment">// Debugger.resumed</span></code> <button class="copy-button">copy</button></pre>
<blockquote>
<p><strong>Caveat</strong> Breakpoints with same-thread session is not recommended, see
<a href="#all_inspector_support-of-breakpoints">support of breakpoints</a>.</p>
</blockquote>
<p>It is also possible to subscribe only to notifications with specific method:</p>
<h5>Event: <code>&#x3C;inspector-protocol-method></code>;<span><a class="mark" href="#all_inspector_event-inspector-protocol-method_1" id="all_inspector_event-inspector-protocol-method_1">#</a></span><a aria-hidden="true" class="legacy" id="inspector_event_inspector_protocol_method_1"></a></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/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.<span class="hljs-title function_">on</span>(<span class="hljs-string">'Debugger.paused'</span>, <span class="hljs-function">(<span class="hljs-params">{ params }</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(params.<span class="hljs-property">hitBreakpoints</span>);
});
<span class="hljs-comment">// [ '/the/file/that/has/the/breakpoint.js:11:0' ]</span></code> <button class="copy-button">copy</button></pre>
<blockquote>
<p><strong>Caveat</strong> Breakpoints with same-thread session is not recommended, see
<a href="#all_inspector_support-of-breakpoints">support of breakpoints</a>.</p>
</blockquote>
<h5><code>session.connect()</code><span><a class="mark" href="#all_inspector_sessionconnect_1" id="all_inspector_sessionconnect_1">#</a></span><a aria-hidden="true" class="legacy" id="inspector_session_connect_1"></a></h5>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<p>Connects a session to the inspector back-end.</p>
<h5><code>session.connectToMainThread()</code><span><a class="mark" href="#all_inspector_sessionconnecttomainthread_1" id="all_inspector_sessionconnecttomainthread_1">#</a></span><a aria-hidden="true" class="legacy" id="inspector_session_connecttomainthread_1"></a></h5>
<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>
<h5><code>session.disconnect()</code><span><a class="mark" href="#all_inspector_sessiondisconnect_1" id="all_inspector_sessiondisconnect_1">#</a></span><a aria-hidden="true" class="legacy" id="inspector_session_disconnect_1"></a></h5>
<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="#all_inspector_sessionconnect"><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>
<h5><code>session.post(method[, params][, callback])</code><span><a class="mark" href="#all_inspector_sessionpostmethod-params-callback" id="all_inspector_sessionpostmethod-params-callback">#</a></span><a aria-hidden="true" class="legacy" id="inspector_session_post_method_params_callback"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</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>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.<span class="hljs-title function_">post</span>(<span class="hljs-string">'Runtime.evaluate'</span>, { <span class="hljs-attr">expression</span>: <span class="hljs-string">'2 + 2'</span> },
             <span class="hljs-function">(<span class="hljs-params">error, { result }</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result));
<span class="hljs-comment">// Output: { type: 'number', value: 4, description: '4' }</span></code> <button class="copy-button">copy</button></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>
<p>You can not set <code>reportProgress</code> to <code>true</code> when sending a
<code>HeapProfiler.takeHeapSnapshot</code> or <code>HeapProfiler.stopTrackingHeapObjects</code>
command to V8.</p>
<h5>Example usage<span><a class="mark" href="#all_inspector_example-usage_1" id="all_inspector_example-usage_1">#</a></span><a aria-hidden="true" class="legacy" id="inspector_example_usage_1"></a></h5>
<p>Apart from the debugger, various V8 Profilers are available through the DevTools
protocol.</p>
<h6>CPU profiler<span><a class="mark" href="#all_inspector_cpu-profiler_1" id="all_inspector_cpu-profiler_1">#</a></span><a aria-hidden="true" class="legacy" id="inspector_cpu_profiler_1"></a></h6>
<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"><span class="hljs-keyword">const</span> inspector = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:inspector'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> session = <span class="hljs-keyword">new</span> inspector.<span class="hljs-title class_">Session</span>();
session.<span class="hljs-title function_">connect</span>();

session.<span class="hljs-title function_">post</span>(<span class="hljs-string">'Profiler.enable'</span>, <span class="hljs-function">() =></span> {
  session.<span class="hljs-title function_">post</span>(<span class="hljs-string">'Profiler.start'</span>, <span class="hljs-function">() =></span> {
    <span class="hljs-comment">// Invoke business logic under measurement here...</span>

    <span class="hljs-comment">// some time later...</span>
    session.<span class="hljs-title function_">post</span>(<span class="hljs-string">'Profiler.stop'</span>, <span class="hljs-function">(<span class="hljs-params">err, { profile }</span>) =></span> {
      <span class="hljs-comment">// Write profile to disk, upload, etc.</span>
      <span class="hljs-keyword">if</span> (!err) {
        fs.<span class="hljs-title function_">writeFileSync</span>(<span class="hljs-string">'./profile.cpuprofile'</span>, <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(profile));
      }
    });
  });
});</code> <button class="copy-button">copy</button></pre>
<h6>Heap profiler<span><a class="mark" href="#all_inspector_heap-profiler_1" id="all_inspector_heap-profiler_1">#</a></span><a aria-hidden="true" class="legacy" id="inspector_heap_profiler_1"></a></h6>
<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"><span class="hljs-keyword">const</span> inspector = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:inspector'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> session = <span class="hljs-keyword">new</span> inspector.<span class="hljs-title class_">Session</span>();

<span class="hljs-keyword">const</span> fd = fs.<span class="hljs-title function_">openSync</span>(<span class="hljs-string">'profile.heapsnapshot'</span>, <span class="hljs-string">'w'</span>);

session.<span class="hljs-title function_">connect</span>();

session.<span class="hljs-title function_">on</span>(<span class="hljs-string">'HeapProfiler.addHeapSnapshotChunk'</span>, <span class="hljs-function">(<span class="hljs-params">m</span>) =></span> {
  fs.<span class="hljs-title function_">writeSync</span>(fd, m.<span class="hljs-property">params</span>.<span class="hljs-property">chunk</span>);
});

session.<span class="hljs-title function_">post</span>(<span class="hljs-string">'HeapProfiler.takeHeapSnapshot'</span>, <span class="hljs-literal">null</span>, <span class="hljs-function">(<span class="hljs-params">err, r</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'HeapProfiler.takeHeapSnapshot done:'</span>, err, r);
  session.<span class="hljs-title function_">disconnect</span>();
  fs.<span class="hljs-title function_">closeSync</span>(fd);
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Common Objects<span><a class="mark" href="#all_inspector_common-objects" id="all_inspector_common-objects">#</a></span><a aria-hidden="true" class="legacy" id="inspector_common_objects"></a></h3>
<h4><code>inspector.close()</code><span><a class="mark" href="#all_inspector_inspectorclose" id="all_inspector_inspectorclose">#</a></span><a aria-hidden="true" class="legacy" id="inspector_inspector_close"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.10.0</td>
<td><p>The API is exposed in the worker threads.</p></td></tr>
<tr><td>v9.0.0</td>
<td><p><span>Added in: v9.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Attempts to close all remaining connections, blocking the event loop until all
are closed. Once all connections are closed, deactivates the inspector.</p>
<h4><code>inspector.console</code><span><a class="mark" href="#all_inspector_inspectorconsole" id="all_inspector_inspectorconsole">#</a></span><a aria-hidden="true" class="legacy" id="inspector_inspector_console"></a></h4>
<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"><span class="hljs-built_in">require</span>(<span class="hljs-string">'node:inspector'</span>).<span class="hljs-property">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'a message'</span>);</code> <button class="copy-button">copy</button></pre>
<p>The inspector console does not have API parity with Node.js
console.</p>
<h4><code>inspector.open([port[, host[, wait]]])</code><span><a class="mark" href="#all_inspector_inspectoropenport-host-wait" id="all_inspector_inspectoropenport-host-wait">#</a></span><a aria-hidden="true" class="legacy" id="inspector_inspector_open_port_host_wait"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.6.0</td>
<td><p>inspector.open() now returns a <code>Disposable</code> object.</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;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>
<li>Returns: <a href="https://tc39.es/proposal-explicit-resource-management/#sec-disposable-interface" class="type">&#x3C;Disposable></a> A Disposable that calls <a href="#all_inspector_inspectorclose"><code>inspector.close()</code></a>.</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="#all_cli_warning-binding-inspector-to-a-public-ipport-combination-is-insecure">security warning</a> regarding the <code>host</code>
parameter usage.</p>
<h4><code>inspector.url()</code><span><a class="mark" href="#all_inspector_inspectorurl" id="all_inspector_inspectorurl">#</a></span><a aria-hidden="true" class="legacy" id="inspector_inspector_url"></a></h4>
<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"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node --inspect -p <span class="hljs-string">'inspector.url()'</span></span>
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
<span class="hljs-meta prompt_">
$ </span><span class="language-bash">node --inspect=localhost:3000 -p <span class="hljs-string">'inspector.url()'</span></span>
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
<span class="hljs-meta prompt_">
$ </span><span class="language-bash">node -p <span class="hljs-string">'inspector.url()'</span></span>
undefined</code> <button class="copy-button">copy</button></pre>
<h4><code>inspector.waitForDebugger()</code><span><a class="mark" href="#all_inspector_inspectorwaitfordebugger" id="all_inspector_inspectorwaitfordebugger">#</a></span><a aria-hidden="true" class="legacy" id="inspector_inspector_waitfordebugger"></a></h4>
<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>
</section><section><h3>Integration with DevTools<span><a class="mark" href="#all_inspector_integration-with-devtools" id="all_inspector_integration-with-devtools">#</a></span><a aria-hidden="true" class="legacy" id="inspector_integration_with_devtools"></a></h3>
<p>The <code>node:inspector</code> module provides an API for integrating with devtools that support Chrome DevTools Protocol.
DevTools frontends connected to a running Node.js instance can capture protocol events emitted from the instance
and display them accordingly to facilitate debugging.
The following methods broadcast a protocol event to all connected frontends.
The <code>params</code> passed to the methods can be optional, depending on the protocol.</p>
<pre><code class="language-js"><span class="hljs-comment">// The `Network.requestWillBeSent` event will be fired.</span>
inspector.<span class="hljs-property">Network</span>.<span class="hljs-title function_">requestWillBeSent</span>({
  <span class="hljs-attr">requestId</span>: <span class="hljs-string">'request-id-1'</span>,
  <span class="hljs-attr">timestamp</span>: <span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>() / <span class="hljs-number">1000</span>,
  <span class="hljs-attr">wallTime</span>: <span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(),
  <span class="hljs-attr">request</span>: {
    <span class="hljs-attr">url</span>: <span class="hljs-string">'https://nodejs.org/en'</span>,
    <span class="hljs-attr">method</span>: <span class="hljs-string">'GET'</span>,
  },
});</code> <button class="copy-button">copy</button></pre>
<h4><code>inspector.Network.requestWillBeSent([params])</code><span><a class="mark" href="#all_inspector_inspectornetworkrequestwillbesentparams" id="all_inspector_inspectornetworkrequestwillbesentparams">#</a></span><a aria-hidden="true" class="legacy" id="inspector_inspector_network_requestwillbesent_params"></a></h4>
<div class="api_metadata">
<span>Added in: v20.18.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<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>
</ul>
<p>This feature is only available with the <code>--experimental-network-inspection</code> flag enabled.</p>
<p>Broadcasts the <code>Network.requestWillBeSent</code> event to connected frontends. This event indicates that
the application is about to send an HTTP request.</p>
<h4><code>inspector.Network.responseReceived([params])</code><span><a class="mark" href="#all_inspector_inspectornetworkresponsereceivedparams" id="all_inspector_inspectornetworkresponsereceivedparams">#</a></span><a aria-hidden="true" class="legacy" id="inspector_inspector_network_responsereceived_params"></a></h4>
<div class="api_metadata">
<span>Added in: v20.18.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<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>
</ul>
<p>This feature is only available with the <code>--experimental-network-inspection</code> flag enabled.</p>
<p>Broadcasts the <code>Network.responseReceived</code> event to connected frontends. This event indicates that
HTTP response is available.</p>
<h4><code>inspector.Network.loadingFinished([params])</code><span><a class="mark" href="#all_inspector_inspectornetworkloadingfinishedparams" id="all_inspector_inspectornetworkloadingfinishedparams">#</a></span><a aria-hidden="true" class="legacy" id="inspector_inspector_network_loadingfinished_params"></a></h4>
<div class="api_metadata">
<span>Added in: v20.18.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<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>
</ul>
<p>This feature is only available with the <code>--experimental-network-inspection</code> flag enabled.</p>
<p>Broadcasts the <code>Network.loadingFinished</code> event to connected frontends. This event indicates that
HTTP request has finished loading.</p>
<h4><code>inspector.Network.loadingFailed([params])</code><span><a class="mark" href="#all_inspector_inspectornetworkloadingfailedparams" id="all_inspector_inspectornetworkloadingfailedparams">#</a></span><a aria-hidden="true" class="legacy" id="inspector_inspector_network_loadingfailed_params"></a></h4>
<div class="api_metadata">
<span>Added in: v20.18.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<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>
</ul>
<p>This feature is only available with the <code>--experimental-network-inspection</code> flag enabled.</p>
<p>Broadcasts the <code>Network.loadingFailed</code> event to connected frontends. This event indicates that
HTTP request has failed to load.</p>
</section><section><h3>Support of breakpoints<span><a class="mark" href="#all_inspector_support-of-breakpoints" id="all_inspector_support-of-breakpoints">#</a></span><a aria-hidden="true" class="legacy" id="inspector_support_of_breakpoints"></a></h3>
<p>The Chrome DevTools Protocol <a href="https://chromedevtools.github.io/devtools-protocol/v8/Debugger"><code>Debugger</code> domain</a> allows an
<code>inspector.Session</code> to attach to a program and set breakpoints to step through
the codes.</p>
<p>However, setting breakpoints with a same-thread <code>inspector.Session</code>, which is
connected by <a href="#all_inspector_sessionconnect"><code>session.connect()</code></a>, should be avoided as the program being
attached and paused is exactly the debugger itself. Instead, try connect to the
main thread by <a href="#all_inspector_sessionconnecttomainthread"><code>session.connectToMainThread()</code></a> and set breakpoints in a
worker thread, or connect with a <a href="debugger.html">Debugger</a> program over WebSocket
connection.</p></section>
        </section>
<section><h2>Internationalization support<span><a class="mark" href="#all_intl_internationalization-support" id="all_intl_internationalization-support">#</a></span><a aria-hidden="true" class="legacy" id="intl_internationalization_support"></a></h2>


<p>Node.js has many features that make it easier to write internationalized
programs. Some of them are:</p>
<ul>
<li>Locale-sensitive or Unicode-aware functions in the <a href="https://tc39.github.io/ecma262/">ECMAScript Language
Specification</a>:
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize"><code>String.prototype.normalize()</code></a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase"><code>String.prototype.toLowerCase()</code></a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase"><code>String.prototype.toUpperCase()</code></a></li>
</ul>
</li>
<li>All functionality described in the <a href="https://tc39.github.io/ecma402/">ECMAScript Internationalization API
Specification</a> (aka ECMA-402):
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl"><code>Intl</code></a> object</li>
<li>Locale-sensitive methods like <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare"><code>String.prototype.localeCompare()</code></a> and
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString"><code>Date.prototype.toLocaleString()</code></a></li>
</ul>
</li>
<li>The <a href="#all_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="#all_buffer_buffertranscodesource-fromenc-toenc"><code>require('node:buffer').transcode()</code></a></li>
<li>More accurate <a href="#all_repl_repl">REPL</a> line editing</li>
<li><a href="#all_util_class-utiltextdecoder"><code>require('node: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 the underlying V8 engine use
<a href="http://site.icu-project.org/">International Components for Unicode (ICU)</a> to implement these features
in native C/C++ code. The full ICU data set is provided by Node.js by default.
However, due to the size of the ICU data file, several
options are provided for customizing the ICU data set either when
building or running Node.js.</p>
<section><h3>Options for building Node.js<span><a class="mark" href="#all_intl_options-for-building-nodejs" id="all_intl_options-for-building-nodejs">#</a></span><a aria-hidden="true" class="legacy" id="intl_options_for_building_node_js"></a></h3>
<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/HEAD/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></li>
<li><code>--with-intl=full-icu</code> (default)</li>
</ul>
<p>An overview of available Node.js and JavaScript features for each <code>configure</code>
option:</p>







































































































<table><thead><tr><th>Feature</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="#all_url_legacy-url-api">Legacy URL Parser</a></td><td>partial (no IDN support)</td><td>full</td><td>full</td><td>full</td></tr><tr><td><a href="#all_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="#all_buffer_buffertranscodesource-fromenc-toenc"><code>require('node: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="#all_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="#all_util_class-utiltextdecoder"><code>require('node: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>
<h4>Disable all internationalization features (<code>none</code>)<span><a class="mark" href="#all_intl_disable-all-internationalization-features-none" id="all_intl_disable-all-internationalization-features-none">#</a></span><a aria-hidden="true" class="legacy" id="intl_disable_all_internationalization_features_none"></a></h4>
<p>If this option is chosen, ICU is disabled and most internationalization
features mentioned above will be <strong>unavailable</strong> in the resulting <code>node</code> binary.</p>
<h4>Build with a pre-installed ICU (<code>system-icu</code>)<span><a class="mark" href="#all_intl_build-with-a-pre-installed-icu-system-icu" id="all_intl_build-with-a-pre-installed-icu-system-icu">#</a></span><a aria-hidden="true" class="legacy" id="intl_build_with_a_pre_installed_icu_system_icu"></a></h4>
<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="#all_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>
<h4>Embed a limited set of ICU data (<code>small-icu</code>)<span><a class="mark" href="#all_intl_embed-a-limited-set-of-icu-data-small-icu" id="all_intl_embed-a-limited-set-of-icu-data-small-icu">#</a></span><a aria-hidden="true" class="legacy" id="intl_embed_a_limited_set_of_icu_data_small_icu"></a></h4>
<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="#all_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"><span class="hljs-keyword">const</span> january = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Date</span>(<span class="hljs-number">9e8</span>);
<span class="hljs-keyword">const</span> english = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Intl</span>.<span class="hljs-title class_">DateTimeFormat</span>(<span class="hljs-string">'en'</span>, { <span class="hljs-attr">month</span>: <span class="hljs-string">'long'</span> });
<span class="hljs-keyword">const</span> spanish = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Intl</span>.<span class="hljs-title class_">DateTimeFormat</span>(<span class="hljs-string">'es'</span>, { <span class="hljs-attr">month</span>: <span class="hljs-string">'long'</span> });

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(english.<span class="hljs-title function_">format</span>(january));
<span class="hljs-comment">// Prints "January"</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(spanish.<span class="hljs-title function_">format</span>(january));
<span class="hljs-comment">// Prints either "M01" or "January" on small-icu, depending on the user’s default locale</span>
<span class="hljs-comment">// Should print "enero"</span></code> <button class="copy-button">copy</button></pre>
<p>This mode provides a balance between features and binary size.</p>
<h5>Providing ICU data at runtime<span><a class="mark" href="#all_intl_providing-icu-data-at-runtime" id="all_intl_providing-icu-data-at-runtime">#</a></span><a aria-hidden="true" class="legacy" id="intl_providing_icu_data_at_runtime"></a></h5>
<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>/runtime/directory/with/dat/file</code>, it can be made
available to ICU through either:</p>
<ul>
<li>
<p>The <code>--with-icu-default-data-dir</code> configure option:</p>
<pre><code class="language-bash">./configure --with-icu-default-data-dir=/runtime/directory/with/dat/file --with-intl=small-icu</code> <button class="copy-button">copy</button></pre>
<p>This only embeds the default data directory path into the binary.
The actual data file is going to be loaded at runtime from this directory
path.</p>
</li>
<li>
<p>The <a href="#all_cli_node_icu_datafile"><code>NODE_ICU_DATA</code></a> environment variable:</p>
<pre><code class="language-bash"><span class="hljs-built_in">env</span> NODE_ICU_DATA=/runtime/directory/with/dat/file node</code> <button class="copy-button">copy</button></pre>
</li>
<li>
<p>The <a href="#all_cli_--icu-data-dirfile"><code>--icu-data-dir</code></a> CLI parameter:</p>
<pre><code class="language-bash">node --icu-data-dir=/runtime/directory/with/dat/file</code> <button class="copy-button">copy</button></pre>
</li>
</ul>
<p>When more than one of them is specified, the <code>--icu-data-dir</code> CLI parameter has
the highest precedence, then the <code>NODE_ICU_DATA</code>  environment variable, then
the <code>--with-icu-default-data-dir</code> configure option.</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>icudtX[bl].dat</code>, where <code>X</code> denotes
the intended ICU version, and <code>b</code> or <code>l</code> indicates the system's endianness.
Node.js would fail to load if the expected data file cannot be read from the
specified directory. The name of the data file corresponding to the current
Node.js version can be computed with:</p>
<pre><code class="language-js"><span class="hljs-string">`icudt<span class="hljs-subst">${process.versions.icu.split(<span class="hljs-string">'.'</span>)[<span class="hljs-number">0</span>]}</span><span class="hljs-subst">${os.endianness()[<span class="hljs-number">0</span>].toLowerCase()}</span>.dat`</span>;</code> <button class="copy-button">copy</button></pre>
<p>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>
<h4>Embed the entire ICU (<code>full-icu</code>)<span><a class="mark" href="#all_intl_embed-the-entire-icu-full-icu" id="all_intl_embed-the-entire-icu-full-icu">#</a></span><a aria-hidden="true" class="legacy" id="intl_embed_the_entire_icu_full_icu"></a></h4>
<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. This is
the default behavior if no <code>--with-intl</code> flag is passed. The official binaries
are also built in this mode.</p>
</section><section><h3>Detecting internationalization support<span><a class="mark" href="#all_intl_detecting-internationalization-support" id="all_intl_detecting-internationalization-support">#</a></span><a aria-hidden="true" class="legacy" id="intl_detecting_internationalization_support"></a></h3>
<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"><span class="hljs-keyword">const</span> hasICU = <span class="hljs-keyword">typeof</span> <span class="hljs-title class_">Intl</span> === <span class="hljs-string">'object'</span>;</code> <button class="copy-button">copy</button></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"><span class="hljs-keyword">const</span> hasICU = <span class="hljs-keyword">typeof</span> process.<span class="hljs-property">versions</span>.<span class="hljs-property">icu</span> === <span class="hljs-string">'string'</span>;</code> <button class="copy-button">copy</button></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"><span class="hljs-keyword">const</span> hasFullICU = (<span class="hljs-function">() =></span> {
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> january = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Date</span>(<span class="hljs-number">9e8</span>);
    <span class="hljs-keyword">const</span> spanish = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Intl</span>.<span class="hljs-title class_">DateTimeFormat</span>(<span class="hljs-string">'es'</span>, { <span class="hljs-attr">month</span>: <span class="hljs-string">'long'</span> });
    <span class="hljs-keyword">return</span> spanish.<span class="hljs-title function_">format</span>(january) === <span class="hljs-string">'enero'</span>;
  } <span class="hljs-keyword">catch</span> (err) {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
  }
})();</code> <button class="copy-button">copy</button></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/HEAD/test/intl402">Test262</a>: ECMAScript's official conformance test suite includes a section
dedicated to ECMA-402.</li>
</ul></section>
        </section>
<section><h2>Modules: CommonJS modules<span><a class="mark" href="#all_modules_modules-commonjs-modules" id="all_modules_modules-commonjs-modules">#</a></span><a aria-hidden="true" class="legacy" id="modules_modules_commonjs_modules"></a></h2>

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

<p>CommonJS modules are the original way to package JavaScript code for Node.js.
Node.js also supports the <a href="esm.html">ECMAScript modules</a> standard used by browsers
and other JavaScript runtimes.</p>
<p>In Node.js, each file is treated as a separate module. For
example, consider a file named <code>foo.js</code>:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> circle = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./circle.js'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`The area of a circle of radius 4 is <span class="hljs-subst">${circle.area(<span class="hljs-number">4</span>)}</span>`</span>);</code> <button class="copy-button">copy</button></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"><span class="hljs-keyword">const</span> { <span class="hljs-variable constant_">PI</span> } = <span class="hljs-title class_">Math</span>;

<span class="hljs-built_in">exports</span>.<span class="hljs-property">area</span> = <span class="hljs-function">(<span class="hljs-params">r</span>) =></span> <span class="hljs-variable constant_">PI</span> * r ** <span class="hljs-number">2</span>;

<span class="hljs-built_in">exports</span>.<span class="hljs-property">circumference</span> = <span class="hljs-function">(<span class="hljs-params">r</span>) =></span> <span class="hljs-number">2</span> * <span class="hljs-variable constant_">PI</span> * r;</code> <button class="copy-button">copy</button></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="#all_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>In the following code, <code>bar.js</code> makes use of the <code>square</code> module, which exports
a Square class:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> <span class="hljs-title class_">Square</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./square.js'</span>);
<span class="hljs-keyword">const</span> mySquare = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Square</span>(<span class="hljs-number">2</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`The area of mySquare is <span class="hljs-subst">${mySquare.area()}</span>`</span>);</code> <button class="copy-button">copy</button></pre>
<p>The <code>square</code> module is defined in <code>square.js</code>:</p>
<pre><code class="language-js"><span class="hljs-comment">// Assigning to exports will not modify module, must use module.exports</span>
<span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = <span class="hljs-keyword">class</span> <span class="hljs-title class_">Square</span> {
  <span class="hljs-title function_">constructor</span>(<span class="hljs-params">width</span>) {
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">width</span> = width;
  }

  <span class="hljs-title function_">area</span>(<span class="hljs-params"></span>) {
    <span class="hljs-keyword">return</span> <span class="hljs-variable language_">this</span>.<span class="hljs-property">width</span> ** <span class="hljs-number">2</span>;
  }
};</code> <button class="copy-button">copy</button></pre>
<p>The CommonJS module system is implemented in the <a href="module.html"><code>module</code> core module</a>.</p>
<section><h3>Enabling<span><a class="mark" href="#all_modules_enabling" id="all_modules_enabling">#</a></span><a aria-hidden="true" class="legacy" id="modules_enabling"></a></h3>

<p>Node.js has two module systems: CommonJS modules and <a href="esm.html">ECMAScript modules</a>.</p>
<p>By default, Node.js will treat the following as CommonJS modules:</p>
<ul>
<li>
<p>Files with a <code>.cjs</code> extension;</p>
</li>
<li>
<p>Files with a <code>.js</code> extension when the nearest parent <code>package.json</code> file
contains a top-level field <a href="#all_packages_type"><code>"type"</code></a> with a value of <code>"commonjs"</code>.</p>
</li>
<li>
<p>Files with a <code>.js</code> extension or without an extension, when the nearest parent
<code>package.json</code> file doesn't contain a top-level field <a href="#all_packages_type"><code>"type"</code></a> or there is
no <code>package.json</code> in any parent folder; unless the file contains syntax that
errors unless it is evaluated as an ES module. Package authors should include
the <a href="#all_packages_type"><code>"type"</code></a> field, even in packages where all sources are CommonJS. Being
explicit about the <code>type</code> of the package will make things easier for build
tools and loaders to determine how the files in the package should be
interpreted.</p>
</li>
<li>
<p>Files with an extension that is not <code>.mjs</code>, <code>.cjs</code>, <code>.json</code>, <code>.node</code>, or <code>.js</code>
(when the nearest parent <code>package.json</code> file contains a top-level field
<a href="#all_packages_type"><code>"type"</code></a> with a value of <code>"module"</code>, those files will be recognized as
CommonJS modules only if they are being included via <code>require()</code>, not when
used as the command-line entry point of the program).</p>
</li>
</ul>
<p>See <a href="#all_packages_determining-module-system">Determining module system</a> for more details.</p>
<p>Calling <code>require()</code> always use the CommonJS module loader. Calling <code>import()</code>
always use the ECMAScript module loader.</p>
</section><section><h3>Accessing the main module<span><a class="mark" href="#all_modules_accessing-the-main-module" id="all_modules_accessing-the-main-module">#</a></span><a aria-hidden="true" class="legacy" id="modules_accessing_the_main_module"></a></h3>

<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>When the entry point is not a CommonJS module, <code>require.main</code> is <code>undefined</code>,
and the main module is out of reach.</p>
</section><section><h3>Package manager tips<span><a class="mark" href="#all_modules_package-manager-tips" id="all_modules_package-manager-tips">#</a></span><a aria-hidden="true" class="legacy" id="modules_package_manager_tips"></a></h3>

<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>In the following, 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>Because Node.js looks up the <code>realpath</code> of any modules it loads (that is, it
resolves symlinks) and then <a href="#all_modules_loading-from-node_modules-folders">looks for their dependencies in <code>node_modules</code> folders</a>,
this situation can be resolved 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>
</section><section><h3>Loading ECMAScript modules using <code>require()</code><span><a class="mark" href="#all_modules_loading-ecmascript-modules-using-require" id="all_modules_loading-ecmascript-modules-using-require">#</a></span><a aria-hidden="true" class="legacy" id="modules_loading_ecmascript_modules_using_require"></a></h3>
<p>The <code>.mjs</code> extension is reserved for <a href="esm.html">ECMAScript Modules</a>.
Currently, if the flag <code>--experimental-require-module</code> is not used, loading
an ECMAScript module using <code>require()</code> will throw a <a href="#all_errors_err_require_esm"><code>ERR_REQUIRE_ESM</code></a>
error, and users need to use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import"><code>import()</code></a> instead. See
<a href="#all_packages_determining-module-system">Determining module system</a> section for more info
regarding which files are parsed as ECMAScript modules.</p>
<p>If <code>--experimental-require-module</code> is enabled, and the ECMAScript module being
loaded by <code>require()</code> meets the following requirements:</p>
<ul>
<li>Explicitly marked as an ES module with a <code>"type": "module"</code> field in
the closest package.json or a <code>.mjs</code> extension.</li>
<li>Fully synchronous (contains no top-level <code>await</code>).</li>
</ul>
<p><code>require()</code> will load the requested module as an ES Module, and return
the module name space object. In this case it is similar to dynamic
<code>import()</code> but is run synchronously and returns the name space object
directly.</p>

<pre class="with-78-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// point.mjs</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">distance</span>(<span class="hljs-params">a, b</span>) { <span class="hljs-keyword">return</span> (b.<span class="hljs-property">x</span> - a.<span class="hljs-property">x</span>) ** <span class="hljs-number">2</span> + (b.<span class="hljs-property">y</span> - a.<span class="hljs-property">y</span>) ** <span class="hljs-number">2</span>; }
<span class="hljs-keyword">class</span> <span class="hljs-title class_">Point</span> {
  <span class="hljs-title function_">constructor</span>(<span class="hljs-params">x, y</span>) { <span class="hljs-variable language_">this</span>.<span class="hljs-property">x</span> = x; <span class="hljs-variable language_">this</span>.<span class="hljs-property">y</span> = y; }
}
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-title class_">Point</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> required = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./point.mjs'</span>);
<span class="hljs-comment">// [Module: null prototype] {</span>
<span class="hljs-comment">//   default: [class Point],</span>
<span class="hljs-comment">//   distance: [Function: distance]</span>
<span class="hljs-comment">// }</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(required);

(<span class="hljs-keyword">async</span> () => {
  <span class="hljs-keyword">const</span> imported = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'./point.mjs'</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(imported === required);  <span class="hljs-comment">// true</span>
})();</code><button class="copy-button">copy</button></pre>
<p>If the module being <code>require()</code>'d contains top-level <code>await</code>, or the module
graph it <code>import</code>s contains top-level <code>await</code>,
<a href="#all_errors_err_require_async_module"><code>ERR_REQUIRE_ASYNC_MODULE</code></a> will be thrown. In this case, users should
load the asynchronous module using <code>import()</code>.</p>
<p>If <code>--experimental-print-required-tla</code> is enabled, instead of throwing
<code>ERR_REQUIRE_ASYNC_MODULE</code> before evaluation, Node.js will evaluate the
module, try to locate the top-level awaits, and print their location to
help users fix them.</p>
</section><section><h3>All together<span><a class="mark" href="#all_modules_all-together" id="all_modules_all-together">#</a></span><a aria-hidden="true" class="legacy" id="modules_all_together"></a></h3>

<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 file system 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. If X begins with '#'
   a. LOAD_PACKAGE_IMPORTS(X, dirname(Y))
5. LOAD_PACKAGE_SELF(X, dirname(Y))
6. LOAD_NODE_MODULES(X, dirname(Y))
7. 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,
    a. Find the closest package scope SCOPE to X.
    b. If no scope was found, load X.js as a CommonJS module. STOP.
    c. If the SCOPE/package.json contains "type" field,
      1. If the "type" field is "module", load X.js as an ECMAScript module. STOP.
      2. Else, load X.js as an CommonJS module. STOP.
3. If X.json is a file, load X.json to a JavaScript Object. STOP
4. If X.node is a file, load X.node as binary addon. STOP
5. If X.mjs is a file, and `--experimental-require-module` is enabled,
   load X.mjs as an ECMAScript module. STOP

LOAD_INDEX(X)
1. If X/index.js is a file
    a. Find the closest package scope SCOPE to X.
    b. If no scope was found, load X/index.js as a CommonJS module. STOP.
    c. If the SCOPE/package.json contains "type" field,
      1. If the "type" field is "module", load X/index.js as an ECMAScript module. STOP.
      2. Else, load X/index.js as an CommonJS module. 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(X, DIR)
   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 = []
4. while I >= 0,
   a. if PARTS[I] = "node_modules" CONTINUE
   b. DIR = path join(PARTS[0 .. I] + "node_modules")
   c. DIRS = DIR + DIRS
   d. let I = I - 1
5. return DIRS + GLOBAL_FOLDERS

LOAD_PACKAGE_IMPORTS(X, DIR)
1. Find the closest package scope SCOPE to DIR.
2. If no scope was found, return.
3. If the SCOPE/package.json "imports" is null or undefined, return.
4. let MATCH = PACKAGE_IMPORTS_RESOLVE(X, pathToFileURL(SCOPE),
  ["node", "require"]) &#x3C;a href="esm.md#resolver-algorithm-specification">defined in the ESM resolver&#x3C;/a>.
5. RESOLVE_ESM_MATCH(MATCH).

LOAD_PACKAGE_EXPORTS(X, DIR)
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. let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(DIR/NAME), "." + SUBPATH,
   `package.json` "exports", ["node", "require"]) &#x3C;a href="esm.md#resolver-algorithm-specification">defined in the ESM resolver&#x3C;/a>.
6. RESOLVE_ESM_MATCH(MATCH)

LOAD_PACKAGE_SELF(X, DIR)
1. Find the closest package scope SCOPE to DIR.
2. If no scope was found, return.
3. If the SCOPE/package.json "exports" is null or undefined, return.
4. If the SCOPE/package.json "name" is not the first segment of X, return.
5. let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(SCOPE),
   "." + X.slice("name".length), `package.json` "exports", ["node", "require"])
   &#x3C;a href="esm.md#resolver-algorithm-specification">defined in the ESM resolver&#x3C;/a>.
6. RESOLVE_ESM_MATCH(MATCH)

RESOLVE_ESM_MATCH(MATCH)
1. let RESOLVED_PATH = fileURLToPath(MATCH)
2. If the file at RESOLVED_PATH exists, load RESOLVED_PATH as its extension
   format. STOP
3. THROW "not found"</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Caching<span><a class="mark" href="#all_modules_caching" id="all_modules_caching">#</a></span><a aria-hidden="true" class="legacy" id="modules_caching"></a></h3>

<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>
<h4>Module caching caveats<span><a class="mark" href="#all_modules_module-caching-caveats" id="all_modules_module-caching-caveats">#</a></span><a aria-hidden="true" class="legacy" id="modules_module_caching_caveats"></a></h4>

<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>
</section><section><h3>Built-in modules<span><a class="mark" href="#all_modules_built-in-modules" id="all_modules_built-in-modules">#</a></span><a aria-hidden="true" class="legacy" id="modules_built_in_modules"></a></h3>

<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0, v14.18.0</td>
<td><p>Added <code>node:</code> import support to <code>require(...)</code>.</p></td></tr>
</tbody></table>
</details>
</div>
<p>Node.js has several modules compiled into the binary. These modules are
described in greater detail elsewhere in this documentation.</p>
<p>The built-in modules are defined within the Node.js source and are located in the
<code>lib/</code> folder.</p>
<p>Built-in modules can be identified using the <code>node:</code> prefix, in which case
it bypasses the <code>require</code> cache. For instance, <code>require('node:http')</code> will
always return the built in HTTP module, even if there is <code>require.cache</code> entry
by that name.</p>
<p>Some built-in 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. The list
of built-in modules that can be loaded without using the <code>node:</code> prefix is exposed
as <a href="#all_module_modulebuiltinmodules"><code>module.builtinModules</code></a>.</p>
<h4>Built-in modules with mandatory <code>node:</code> prefix<span><a class="mark" href="#all_modules_built-in-modules-with-mandatory-node-prefix" id="all_modules_built-in-modules-with-mandatory-node-prefix">#</a></span><a aria-hidden="true" class="legacy" id="modules_built_in_modules_with_mandatory_node_prefix"></a></h4>
<p>When being loaded by <code>require()</code>, some built-in modules must be requested with the
<code>node:</code> prefix. This requirement exists to prevent newly introduced built-in
modules from having a conflict with user land packages that already have
taken the name. Currently the built-in modules that requires the <code>node:</code> prefix are:</p>
<ul>
<li><a href="#all_single-executable-applications_single-executable-application-api"><code>node:sea</code></a></li>
<li><a href="test.html"><code>node:test</code></a></li>
<li><a href="#all_test_test-reporters"><code>node:test/reporters</code></a></li>
</ul>
</section><section><h3>Cycles<span><a class="mark" href="#all_modules_cycles" id="all_modules_cycles">#</a></span><a aria-hidden="true" class="legacy" id="modules_cycles"></a></h3>

<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"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'a starting'</span>);
<span class="hljs-built_in">exports</span>.<span class="hljs-property">done</span> = <span class="hljs-literal">false</span>;
<span class="hljs-keyword">const</span> b = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./b.js'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'in a, b.done = %j'</span>, b.<span class="hljs-property">done</span>);
<span class="hljs-built_in">exports</span>.<span class="hljs-property">done</span> = <span class="hljs-literal">true</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'a done'</span>);</code> <button class="copy-button">copy</button></pre>
<p><code>b.js</code>:</p>
<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'b starting'</span>);
<span class="hljs-built_in">exports</span>.<span class="hljs-property">done</span> = <span class="hljs-literal">false</span>;
<span class="hljs-keyword">const</span> a = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./a.js'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'in b, a.done = %j'</span>, a.<span class="hljs-property">done</span>);
<span class="hljs-built_in">exports</span>.<span class="hljs-property">done</span> = <span class="hljs-literal">true</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'b done'</span>);</code> <button class="copy-button">copy</button></pre>
<p><code>main.js</code>:</p>
<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'main starting'</span>);
<span class="hljs-keyword">const</span> a = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./a.js'</span>);
<span class="hljs-keyword">const</span> b = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./b.js'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'in main, a.done = %j, b.done = %j'</span>, a.<span class="hljs-property">done</span>, b.<span class="hljs-property">done</span>);</code> <button class="copy-button">copy</button></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"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node main.js</span>
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> <button class="copy-button">copy</button></pre>
<p>Careful planning is required to allow cyclic module dependencies to work
correctly within an application.</p>
</section><section><h3>File modules<span><a class="mark" href="#all_modules_file-modules" id="all_modules_file-modules">#</a></span><a aria-hidden="true" class="legacy" id="modules_file_modules"></a></h3>

<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>. When loading a file that has a different extension (e.g. <code>.cjs</code>), its
full name must be passed to <code>require()</code>, including its file extension (e.g.
<code>require('./file.cjs')</code>).</p>
<p><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>. Files using any other
extension (or no extension at all) are parsed as JavaScript text files. Refer to
the <a href="#all_packages_determining-module-system">Determining module system</a> section to understand what parse goal will be
used.</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 a
<a href="#all_errors_module_not_found"><code>MODULE_NOT_FOUND</code></a> error.</p>
</section><section><h3>Folders as modules<span><a class="mark" href="#all_modules_folders-as-modules" id="all_modules_folders-as-modules">#</a></span><a aria-hidden="true" class="legacy" id="modules_folders_as_modules"></a></h3>

<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy: Use <a href="#all_packages_subpath-exports">subpath exports</a> or <a href="#all_packages_subpath-imports">subpath imports</a> instead.</div><p></p>
<p>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 <a href="#all_packages_nodejs-packagejson-field-definitions"><code>package.json</code></a> file in the root of the folder,
which specifies a <code>main</code> module. An example <a href="#all_packages_nodejs-packagejson-field-definitions"><code>package.json</code></a> file might
look like this:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span> <span class="hljs-attr">"name"</span> <span class="hljs-punctuation">:</span> <span class="hljs-string">"some-library"</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"main"</span> <span class="hljs-punctuation">:</span> <span class="hljs-string">"./lib/some-library.js"</span> <span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></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>If there is no <a href="#all_packages_nodejs-packagejson-field-definitions"><code>package.json</code></a> file present in the directory, or if the
<a href="#all_packages_main"><code>"main"</code></a> 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 <a href="#all_packages_nodejs-packagejson-field-definitions"><code>package.json</code></a> file in the previous
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> <button class="copy-button">copy</button></pre>
<p>In all three above cases, an <code>import('./some-library')</code> call would result in a
<a href="#all_errors_err_unsupported_dir_import"><code>ERR_UNSUPPORTED_DIR_IMPORT</code></a> error. Using package <a href="#all_packages_subpath-exports">subpath exports</a> or
<a href="#all_packages_subpath-imports">subpath imports</a> can provide the same containment organization benefits as
folders as modules, and work for both <code>require</code> and <code>import</code>.</p>
</section><section><h3>Loading from <code>node_modules</code> folders<span><a class="mark" href="#all_modules_loading-from-node_modules-folders" id="all_modules_loading-from-node_modules-folders">#</a></span><a aria-hidden="true" class="legacy" id="modules_loading_from_node_modules_folders"></a></h3>

<p>If the module identifier passed to <code>require()</code> is not a
<a href="#all_modules_built-in-modules">built-in</a> module, and does not begin with <code>'/'</code>, <code>'../'</code>, or
<code>'./'</code>, then Node.js starts at the 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>
</section><section><h3>Loading from the global folders<span><a class="mark" href="#all_modules_loading-from-the-global-folders" id="all_modules_loading-from-the-global-folders">#</a></span><a aria-hidden="true" class="legacy" id="modules_loading_from_the_global_folders"></a></h3>

<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="#all_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>
</section><section><h3>The module wrapper<span><a class="mark" href="#all_modules_the-module-wrapper" id="all_modules_the-module-wrapper">#</a></span><a aria-hidden="true" class="legacy" id="modules_the_module_wrapper"></a></h3>

<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">(<span class="hljs-keyword">function</span>(<span class="hljs-params"><span class="hljs-built_in">exports</span>, <span class="hljs-built_in">require</span>, <span class="hljs-variable language_">module</span>, __filename, __dirname</span>) {
<span class="hljs-comment">// Module code actually lives in here</span>
});</code> <button class="copy-button">copy</button></pre>
<p>By doing this, Node.js achieves a few things:</p>
<ul>
<li>It keeps top-level variables (defined with <code>var</code>, <code>const</code>, or <code>let</code>) scoped to
the module rather than the global object.</li>
<li>It helps to provide some global-looking variables that are actually specific
to the module, such as:
<ul>
<li>The <code>module</code> and <code>exports</code> objects that the implementor can use to export
values from the module.</li>
<li>The convenience variables <code>__filename</code> and <code>__dirname</code>, containing the
module's absolute filename and directory path.</li>
</ul>
</li>
</ul>
</section><section><h3>The module scope<span><a class="mark" href="#all_modules_the-module-scope" id="all_modules_the-module-scope">#</a></span><a aria-hidden="true" class="legacy" id="modules_the_module_scope"></a></h3>
<h4><code>__dirname</code><span><a class="mark" href="#all_modules___dirname" id="all_modules___dirname">#</a></span><a aria-hidden="true" class="legacy" id="modules_dirname"></a></h4>
<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="#all_path_pathdirnamepath"><code>path.dirname()</code></a> of the <a href="#all_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"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(__dirname);
<span class="hljs-comment">// Prints: /Users/mjr</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(path.<span class="hljs-title function_">dirname</span>(__filename));
<span class="hljs-comment">// Prints: /Users/mjr</span></code> <button class="copy-button">copy</button></pre>
<h4><code>__filename</code><span><a class="mark" href="#all_modules___filename" id="all_modules___filename">#</a></span><a aria-hidden="true" class="legacy" id="modules_filename"></a></h4>
<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="#all_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"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(__filename);
<span class="hljs-comment">// Prints: /Users/mjr/example.js</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(__dirname);
<span class="hljs-comment">// Prints: /Users/mjr</span></code> <button class="copy-button">copy</button></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>
<h4><code>exports</code><span><a class="mark" href="#all_modules_exports" id="all_modules_exports">#</a></span><a aria-hidden="true" class="legacy" id="modules_exports"></a></h4>
<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="#all_modules_exports-shortcut">exports shortcut</a> for details on when to use
<code>exports</code> and when to use <code>module.exports</code>.</p>
<h4><code>module</code><span><a class="mark" href="#all_modules_module" id="all_modules_module">#</a></span><a aria-hidden="true" class="legacy" id="modules_module"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.16</span>
</div>

<ul>
<li><a href="#all_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="#all_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>
<h4><code>require(id)</code><span><a class="mark" href="#all_modules_requireid" id="all_modules_requireid">#</a></span><a aria-hidden="true" class="legacy" id="modules_require_id"></a></h4>
<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="#all_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"><span class="hljs-comment">// Importing a local module with a path relative to the `__dirname` or current</span>
<span class="hljs-comment">// working directory. (On Windows, this would resolve to .\path\myLocalModule.)</span>
<span class="hljs-keyword">const</span> myLocalModule = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./path/myLocalModule'</span>);

<span class="hljs-comment">// Importing a JSON file:</span>
<span class="hljs-keyword">const</span> jsonData = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./path/filename.json'</span>);

<span class="hljs-comment">// Importing a module from node_modules or Node.js built-in module:</span>
<span class="hljs-keyword">const</span> crypto = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:crypto'</span>);</code> <button class="copy-button">copy</button></pre>
<h5><code>require.cache</code><span><a class="mark" href="#all_modules_requirecache" id="all_modules_requirecache">#</a></span><a aria-hidden="true" class="legacy" id="modules_require_cache"></a></h5>
<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
built-in modules and if a name matching a built-in module is added to the cache,
only <code>node:</code>-prefixed require calls are going to receive the built-in module.
Use with care!</p>
<!-- eslint-disable node-core/no-duplicate-requires -->
<pre><code class="language-js"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> realFs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);

<span class="hljs-keyword">const</span> fakeFs = {};
<span class="hljs-built_in">require</span>.<span class="hljs-property">cache</span>.<span class="hljs-property">fs</span> = { <span class="hljs-attr">exports</span>: fakeFs };

assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>), fakeFs);
assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>), realFs);</code> <button class="copy-button">copy</button></pre>
<h5><code>require.extensions</code><span><a class="mark" href="#all_modules_requireextensions" id="all_modules_requireextensions">#</a></span><a aria-hidden="true" class="legacy" id="modules_require_extensions"></a></h5>
<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="#all_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"><span class="hljs-built_in">require</span>.<span class="hljs-property">extensions</span>[<span class="hljs-string">'.sjs'</span>] = <span class="hljs-built_in">require</span>.<span class="hljs-property">extensions</span>[<span class="hljs-string">'.js'</span>];</code> <button class="copy-button">copy</button></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>
<h5><code>require.main</code><span><a class="mark" href="#all_modules_requiremain" id="all_modules_requiremain">#</a></span><a aria-hidden="true" class="legacy" id="modules_require_main"></a></h5>
<div class="api_metadata">
<span>Added in: v0.1.17</span>
</div>
<ul>
<li><a href="#all_modules_the-module-object" class="type">&#x3C;module></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 <code>Module</code> object representing the entry script loaded when the Node.js
process launched, or <code>undefined</code> if the entry point of the program is not a
CommonJS module.
See <a href="#all_modules_accessing-the-main-module">"Accessing the main module"</a>.</p>
<p>In <code>entry.js</code> script:</p>
<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-built_in">require</span>.<span class="hljs-property">main</span>);</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-bash">node entry.js</code> <button class="copy-button">copy</button></pre>
<!-- eslint-skip -->
<pre><code class="language-js"><span class="hljs-title class_">Module</span> {
  <span class="hljs-attr">id</span>: <span class="hljs-string">'.'</span>,
  <span class="hljs-attr">path</span>: <span class="hljs-string">'/absolute/path/to'</span>,
  <span class="hljs-attr">exports</span>: {},
  <span class="hljs-attr">filename</span>: <span class="hljs-string">'/absolute/path/to/entry.js'</span>,
  <span class="hljs-attr">loaded</span>: <span class="hljs-literal">false</span>,
  <span class="hljs-attr">children</span>: [],
  <span class="hljs-attr">paths</span>:
   [ <span class="hljs-string">'/absolute/path/to/node_modules'</span>,
     <span class="hljs-string">'/absolute/path/node_modules'</span>,
     <span class="hljs-string">'/absolute/node_modules'</span>,
     <span class="hljs-string">'/node_modules'</span> ] }</code> <button class="copy-button">copy</button></pre>
<h5><code>require.resolve(request[, options])</code><span><a class="mark" href="#all_modules_requireresolverequest-options" id="all_modules_requireresolverequest-options">#</a></span><a aria-hidden="true" class="legacy" id="modules_require_resolve_request_options"></a></h5>
<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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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="#all_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>
<h6><code>require.resolve.paths(request)</code><span><a class="mark" href="#all_modules_requireresolvepathsrequest" id="all_modules_requireresolvepathsrequest">#</a></span><a aria-hidden="true" class="legacy" id="modules_require_resolve_paths_request"></a></h6>
<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>
</section><section><h3>The <code>module</code> object<span><a class="mark" href="#all_modules_the-module-object" id="all_modules_the-module-object">#</a></span><a aria-hidden="true" class="legacy" id="modules_the_module_object"></a></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>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>
<h4><code>module.children</code><span><a class="mark" href="#all_modules_modulechildren" id="all_modules_modulechildren">#</a></span><a aria-hidden="true" class="legacy" id="modules_module_children"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.16</span>
</div>
<ul>
<li><a href="#all_modules_the-module-object" class="type">&#x3C;module[]></a></li>
</ul>
<p>The module objects required for the first time by this one.</p>
<h4><code>module.exports</code><span><a class="mark" href="#all_modules_moduleexports" id="all_modules_moduleexports">#</a></span><a aria-hidden="true" class="legacy" id="modules_module_exports"></a></h4>
<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"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);

<span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();

<span class="hljs-comment">// Do some work, and after some time emit</span>
<span class="hljs-comment">// the 'ready' event from the module itself.</span>
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span>.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'ready'</span>);
}, <span class="hljs-number">1000</span>);</code> <button class="copy-button">copy</button></pre>
<p>Then in another file we could do:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> a = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./a'</span>);
a.<span class="hljs-title function_">on</span>(<span class="hljs-string">'ready'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'module "a" is ready'</span>);
});</code> <button class="copy-button">copy</button></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"><span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = { <span class="hljs-attr">a</span>: <span class="hljs-string">'hello'</span> };
}, <span class="hljs-number">0</span>);</code> <button class="copy-button">copy</button></pre>
<p><code>y.js</code>:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> x = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./x'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(x.<span class="hljs-property">a</span>);</code> <button class="copy-button">copy</button></pre>
<h5><code>exports</code> shortcut<span><a class="mark" href="#all_modules_exports-shortcut" id="all_modules_exports-shortcut">#</a></span><a aria-hidden="true" class="legacy" id="modules_exports_shortcut"></a></h5>
<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"><span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span>.<span class="hljs-property">hello</span> = <span class="hljs-literal">true</span>; <span class="hljs-comment">// Exported from require of module</span>
<span class="hljs-built_in">exports</span> = { <span class="hljs-attr">hello</span>: <span class="hljs-literal">false</span> };  <span class="hljs-comment">// Not exported, only available in the module</span></code> <button class="copy-button">copy</button></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"><span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = <span class="hljs-built_in">exports</span> = <span class="hljs-keyword">function</span> <span class="hljs-title function_">Constructor</span>(<span class="hljs-params"></span>) {
  <span class="hljs-comment">// ... etc.</span>
};</code> <button class="copy-button">copy</button></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"><span class="hljs-keyword">function</span> <span class="hljs-title function_">require</span>(<span class="hljs-params"><span class="hljs-comment">/* ... */</span></span>) {
  <span class="hljs-keyword">const</span> <span class="hljs-variable language_">module</span> = { <span class="hljs-attr">exports</span>: {} };
  (<span class="hljs-function">(<span class="hljs-params"><span class="hljs-variable language_">module</span>, <span class="hljs-built_in">exports</span></span>) =></span> {
    <span class="hljs-comment">// Module code here. In this example, define a function.</span>
    <span class="hljs-keyword">function</span> <span class="hljs-title function_">someFunc</span>(<span class="hljs-params"></span>) {}
    <span class="hljs-built_in">exports</span> = someFunc;
    <span class="hljs-comment">// At this point, exports is no longer a shortcut to module.exports, and</span>
    <span class="hljs-comment">// this module will still export an empty default object.</span>
    <span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = someFunc;
    <span class="hljs-comment">// At this point, the module will now export someFunc, instead of the</span>
    <span class="hljs-comment">// default object.</span>
  })(<span class="hljs-variable language_">module</span>, <span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span>);
  <span class="hljs-keyword">return</span> <span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span>;
}</code> <button class="copy-button">copy</button></pre>
<h4><code>module.filename</code><span><a class="mark" href="#all_modules_modulefilename" id="all_modules_modulefilename">#</a></span><a aria-hidden="true" class="legacy" id="modules_module_filename"></a></h4>
<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>
<h4><code>module.id</code><span><a class="mark" href="#all_modules_moduleid" id="all_modules_moduleid">#</a></span><a aria-hidden="true" class="legacy" id="modules_module_id"></a></h4>
<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>
<h4><code>module.isPreloading</code><span><a class="mark" href="#all_modules_moduleispreloading" id="all_modules_moduleispreloading">#</a></span><a aria-hidden="true" class="legacy" id="modules_module_ispreloading"></a></h4>
<div class="api_metadata">
<span>Added in: v15.4.0, v14.17.0</span>
</div>
<ul>
<li>Type: <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 module is running during the Node.js preload
phase.</li>
</ul>
<h4><code>module.loaded</code><span><a class="mark" href="#all_modules_moduleloaded" id="all_modules_moduleloaded">#</a></span><a aria-hidden="true" class="legacy" id="modules_module_loaded"></a></h4>
<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>
<h4><code>module.parent</code><span><a class="mark" href="#all_modules_moduleparent" id="all_modules_moduleparent">#</a></span><a aria-hidden="true" class="legacy" id="modules_module_parent"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.16</span><span>Deprecated since: v14.6.0, v12.19.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Please use <a href="#all_modules_requiremain"><code>require.main</code></a> and
<a href="#all_modules_modulechildren"><code>module.children</code></a> instead.</div><p></p>
<ul>
<li><a href="#all_modules_the-module-object" class="type">&#x3C;module></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>
</ul>
<p>The module that first required this one, or <code>null</code> if the current module is the
entry point of the current process, or <code>undefined</code> if the module was loaded by
something that is not a CommonJS module (E.G.: REPL or <code>import</code>).</p>
<h4><code>module.path</code><span><a class="mark" href="#all_modules_modulepath" id="all_modules_modulepath">#</a></span><a aria-hidden="true" class="legacy" id="modules_module_path"></a></h4>
<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="#all_path_pathdirnamepath"><code>path.dirname()</code></a> of the <a href="#all_modules_moduleid"><code>module.id</code></a>.</p>
<h4><code>module.paths</code><span><a class="mark" href="#all_modules_modulepaths" id="all_modules_modulepaths">#</a></span><a aria-hidden="true" class="legacy" id="modules_module_paths"></a></h4>
<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>
<h4><code>module.require(id)</code><span><a class="mark" href="#all_modules_modulerequireid" id="all_modules_modulerequireid">#</a></span><a aria-hidden="true" class="legacy" id="modules_module_require_id"></a></h4>
<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>
</section><section><h3>The <code>Module</code> object<span><a class="mark" href="#all_modules_the-module-object_1" id="all_modules_the-module-object_1">#</a></span><a aria-hidden="true" class="legacy" id="modules_the_module_object_1"></a></h3>
<p>This section was moved to
<a href="#all_module_the-module-object">Modules: <code>module</code> core module</a>.</p>
<!-- Anchors to make sure old links find a target -->
<ul>
<li><a id="modules_module_builtinmodules" href="module.html#modulebuiltinmodules"><code>module.builtinModules</code></a></li>
<li><a id="modules_module_createrequire_filename" href="module.html#modulecreaterequirefilename"><code>module.createRequire(filename)</code></a></li>
<li><a id="modules_module_syncbuiltinesmexports" href="module.html#modulesyncbuiltinesmexports"><code>module.syncBuiltinESMExports()</code></a></li>
</ul>
</section><section><h3>Source map v3 support<span><a class="mark" href="#all_modules_source-map-v3-support" id="all_modules_source-map-v3-support">#</a></span><a aria-hidden="true" class="legacy" id="modules_source_map_v3_support"></a></h3>
<p>This section was moved to
<a href="#all_module_source-map-v3-support">Modules: <code>module</code> core module</a>.</p>
<!-- Anchors to make sure old links find a target -->
<ul>
<li><a id="modules_module_findsourcemap_path_error" href="module.html#modulefindsourcemappath"><code>module.findSourceMap(path)</code></a></li>
<li><a id="modules_class_module_sourcemap" href="module.html#class-modulesourcemap">Class: <code>module.SourceMap</code></a>
<ul>
<li><a id="modules_new_sourcemap_payload" href="module.html#new-sourcemappayload"><code>new SourceMap(payload)</code></a></li>
<li><a id="modules_sourcemap_payload" href="module.html#sourcemappayload"><code>sourceMap.payload</code></a></li>
<li><a id="modules_sourcemap_findentry_linenumber_columnnumber" href="module.html#sourcemapfindentrylinenumber-columnnumber"><code>sourceMap.findEntry(lineNumber, columnNumber)</code></a></li>
</ul>
</li>
</ul></section>
        </section>
<section><h2>Modules: ECMAScript modules<span><a class="mark" href="#all_esm_modules-ecmascript-modules" id="all_esm_modules-ecmascript-modules">#</a></span><a aria-hidden="true" class="legacy" id="esm_modules_ecmascript_modules"></a></h2>


<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.10.0</td>
<td><p>Add experimental support for import attributes.</p></td></tr>
<tr><td>v20.0.0</td>
<td><p>Module customization hooks are executed off the main thread.</p></td></tr>
<tr><td>v18.6.0, v16.17.0</td>
<td><p>Add support for chaining module customization hooks.</p></td></tr>
<tr><td>v17.1.0, v16.14.0</td>
<td><p>Add experimental support for import assertions.</p></td></tr>
<tr><td>v17.0.0, v16.12.0</td>
<td><p>Consolidate customization hooks, removed <code>getFormat</code>, <code>getSource</code>, <code>transformSource</code>, and <code>getGlobalPreloadCode</code> hooks added <code>load</code> and <code>globalPreload</code> hooks allowed returning <code>format</code> from either <code>resolve</code> or <code>load</code> hooks.</p></td></tr>
<tr><td>v14.8.0</td>
<td><p>Unflag Top-Level Await.</p></td></tr>
<tr><td>v15.3.0, v14.17.0, v12.22.0</td>
<td><p>Stabilize modules implementation.</p></td></tr>
<tr><td>v14.13.0, v12.20.0</td>
<td><p>Support for detection of CommonJS named exports.</p></td></tr>
<tr><td>v14.0.0, v13.14.0, v12.20.0</td>
<td><p>Remove experimental modules warning.</p></td></tr>
<tr><td>v13.2.0, v12.17.0</td>
<td><p>Loading ECMAScript modules no longer requires a command-line flag.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>Add support for ES modules using <code>.js</code> file extension via <code>package.json</code> <code>"type"</code> field.</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>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<section><h3>Introduction<span><a class="mark" href="#all_esm_introduction" id="all_esm_introduction">#</a></span><a aria-hidden="true" class="legacy" id="esm_introduction"></a></h3>

<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"><span class="hljs-comment">// addTwo.mjs</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">addTwo</span>(<span class="hljs-params">num</span>) {
  <span class="hljs-keyword">return</span> num + <span class="hljs-number">2</span>;
}

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

<span class="hljs-comment">// Prints: 6</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">addTwo</span>(<span class="hljs-number">4</span>));</code> <button class="copy-button">copy</button></pre>
<p>Node.js fully supports ECMAScript modules as they are currently specified and
provides interoperability between them and its original module format,
<a href="modules.html">CommonJS</a>.</p>
<!-- Anchors to make sure old links find a target -->
<p><i id="esm_package_json_type_field"></i><i id="esm_package_scope_and_file_extensions"></i><i id="esm_input_type_flag"></i></p>
</section><section><h3>Enabling<span><a class="mark" href="#all_esm_enabling" id="all_esm_enabling">#</a></span><a aria-hidden="true" class="legacy" id="esm_enabling"></a></h3>

<p>Node.js has two module systems: <a href="modules.html">CommonJS</a> modules and ECMAScript modules.</p>
<p>Authors can tell Node.js to interpret JavaScript as an ES module via the <code>.mjs</code>
file extension, the <code>package.json</code> <a href="#all_packages_type"><code>"type"</code></a> field with a value <code>"module"</code>,
the <a href="#all_cli_--input-typetype"><code>--input-type</code></a> flag with a value of <code>"module"</code>, or the
<a href="#all_cli_--experimental-default-typetype"><code>--experimental-default-type</code></a> flag with a value of <code>"module"</code>. These are
explicit markers of code being intended to run as an ES module.</p>
<p>Inversely, authors can tell Node.js to interpret JavaScript as CommonJS via the
<code>.cjs</code> file extension, the <code>package.json</code> <a href="#all_packages_type"><code>"type"</code></a> field with a value
<code>"commonjs"</code>, the <a href="#all_cli_--input-typetype"><code>--input-type</code></a> flag with a value of <code>"commonjs"</code>, or the
<a href="#all_cli_--experimental-default-typetype"><code>--experimental-default-type</code></a> flag with a value of <code>"commonjs"</code>.</p>
<p>When code lacks explicit markers for either module system, Node.js will inspect
the source code of a module to look for ES module syntax. If such syntax is
found, Node.js will run the code as an ES module; otherwise it will run the
module as CommonJS. See <a href="#all_packages_determining-module-system">Determining module system</a> for more details.</p>
<!-- Anchors to make sure old links find a target -->
<p><i id="esm_package_entry_points"></i><i id="esm_main_entry_point_export"></i><i id="esm_subpath_exports"></i><i id="esm_package_exports_fallbacks"></i><i id="esm_exports_sugar"></i><i id="esm_conditional_exports"></i><i id="esm_nested_conditions"></i><i id="esm_self_referencing_a_package_using_its_name"></i><i id="esm_internal_package_imports"></i><i id="esm_dual_commonjs_es_module_packages"></i><i id="esm_dual_package_hazard"></i><i id="esm_writing_dual_packages_while_avoiding_or_minimizing_hazards"></i><i id="esm_approach_1_use_an_es_module_wrapper"></i><i id="esm_approach_2_isolate_state"></i></p>
</section><section><h3>Packages<span><a class="mark" href="#all_esm_packages" id="all_esm_packages">#</a></span><a aria-hidden="true" class="legacy" id="esm_packages"></a></h3>
<p>This section was moved to <a href="packages.html">Modules: Packages</a>.</p>
</section><section><h3><code>import</code> Specifiers<span><a class="mark" href="#all_esm_import-specifiers" id="all_esm_import-specifiers">#</a></span><a aria-hidden="true" class="legacy" id="esm_import_specifiers"></a></h3>
<h4>Terminology<span><a class="mark" href="#all_esm_terminology" id="all_esm_terminology">#</a></span><a aria-hidden="true" class="legacy" id="esm_terminology"></a></h4>
<p>The <em>specifier</em> of an <code>import</code> statement is the string after the <code>from</code> keyword,
e.g. <code>'node:path'</code> in <code>import { sep } from 'node: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 three types of specifiers:</p>
<ul>
<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. <em>The file extension
is always necessary for these.</em></p>
</li>
<li>
<p><em>Bare specifiers</em> like <code>'some-package'</code> or <code>'some-package/shuffle'</code>. They can
refer to the main entry point of a package by the package name, or a
specific feature module within a package prefixed by the package name as per
the examples respectively. <em>Including the file extension is only necessary
for packages without an <a href="#all_packages_exports"><code>"exports"</code></a> field.</em></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 specifier resolutions are handled by the <a href="#all_esm_resolution-algorithm-specification">Node.js module
resolution and loading algorithm</a>.
All other specifier resolutions are always only resolved with
the standard relative <a href="https://url.spec.whatwg.org/">URL</a> resolution semantics.</p>
<p>Like in CommonJS, module files within packages can be accessed by appending a
path to the package name unless the package's <a href="#all_packages_nodejs-packagejson-field-definitions"><code>package.json</code></a> contains an
<a href="#all_packages_exports"><code>"exports"</code></a> field, in which case files within packages can only be accessed
via the paths defined in <a href="#all_packages_exports"><code>"exports"</code></a>.</p>
<p>For details on these package resolution rules that apply to bare specifiers in
the Node.js module resolution, see the <a href="packages.html">packages documentation</a>.</p>
<h4>Mandatory file extensions<span><a class="mark" href="#all_esm_mandatory-file-extensions" id="all_esm_mandatory-file-extensions">#</a></span><a aria-hidden="true" class="legacy" id="esm_mandatory_file_extensions"></a></h4>
<p>A file extension must be provided when using the <code>import</code> keyword to resolve
relative or absolute specifiers. 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>
<h4>URLs<span><a class="mark" href="#all_esm_urls" id="all_esm_urls">#</a></span><a aria-hidden="true" class="legacy" id="esm_urls"></a></h4>
<p>ES modules are resolved and cached as URLs. This means that special characters
must be <a href="#all_url_percent-encoding-in-urls">percent-encoded</a>, such as <code>#</code> with <code>%23</code> and <code>?</code> with <code>%3F</code>.</p>
<p><code>file:</code>, <code>node:</code>, and <code>data:</code> URL schemes are supported. A specifier like
<code>'https://example.com/app.js'</code> is not supported natively in Node.js unless using
a <a href="#all_module_import-from-https">custom HTTPS loader</a>.</p>
<h5><code>file:</code> URLs<span><a class="mark" href="#all_esm_file-urls" id="all_esm_file-urls">#</a></span><a aria-hidden="true" class="legacy" id="esm_file_urls"></a></h5>
<p>Modules are loaded multiple times if the <code>import</code> specifier used to resolve
them has a different query or fragment.</p>
<pre><code class="language-js"><span class="hljs-keyword">import</span> <span class="hljs-string">'./foo.mjs?query=1'</span>; <span class="hljs-comment">// loads ./foo.mjs with query of "?query=1"</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'./foo.mjs?query=2'</span>; <span class="hljs-comment">// loads ./foo.mjs with query of "?query=2"</span></code> <button class="copy-button">copy</button></pre>
<p>The volume root may be referenced via <code>/</code>, <code>//</code>, or <code>file:///</code>. Given the
differences between <a href="https://url.spec.whatwg.org/">URL</a> and path resolution (such as percent encoding
details), it is recommended to use <a href="#all_url_urlpathtofileurlpath-options">url.pathToFileURL</a> when importing a path.</p>
<h5><code>data:</code> imports<span><a class="mark" href="#all_esm_data-imports" id="all_esm_data-imports">#</a></span><a aria-hidden="true" class="legacy" id="esm_data_imports"></a></h5>
<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>
<pre><code class="language-js"><span class="hljs-keyword">import</span> <span class="hljs-string">'data:text/javascript,console.log("hello!");'</span>;
<span class="hljs-keyword">import</span> _ <span class="hljs-keyword">from</span> <span class="hljs-string">'data:application/json,"world!"'</span> <span class="hljs-keyword">with</span> { <span class="hljs-attr">type</span>: <span class="hljs-string">'json'</span> };</code> <button class="copy-button">copy</button></pre>
<p><code>data:</code> URLs only resolve <a href="#all_esm_terminology">bare specifiers</a> for builtin modules
and <a href="#all_esm_terminology">absolute specifiers</a>. Resolving
<a href="#all_esm_terminology">relative specifiers</a> does 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> fails to resolve because there
is no concept of relative resolution for <code>data:</code> URLs.</p>
<h5><code>node:</code> imports<span><a class="mark" href="#all_esm_node-imports" id="all_esm_node-imports">#</a></span><a aria-hidden="true" class="legacy" id="esm_node_imports"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0, v14.18.0</td>
<td><p>Added <code>node:</code> import support to <code>require(...)</code>.</p></td></tr>
<tr><td>v14.13.1, v12.20.0</td>
<td><p><span>Added in: v14.13.1, v12.20.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p><code>node:</code> URLs are supported as an alternative means to load Node.js builtin
modules. This URL scheme allows for builtin modules to be referenced by valid
absolute URL strings.</p>
<pre><code class="language-js"><span class="hljs-keyword">import</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;</code> <button class="copy-button">copy</button></pre>
<p><a id="import-assertions"></a></p>
</section><section><h3>Import attributes<span><a class="mark" href="#all_esm_import-attributes" id="all_esm_import-attributes">#</a></span><a aria-hidden="true" class="legacy" id="esm_import_attributes"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.10.0</td>
<td><p>Switch from Import Assertions to Import Attributes.</p></td></tr>
<tr><td>v17.1.0, v16.14.0</td>
<td><p><span>Added in: v17.1.0, v16.14.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active development</div><p></p>
<blockquote>
<p>This feature was previously named "Import assertions", and using the <code>assert</code>
keyword instead of <code>with</code>. Any uses in code of the prior <code>assert</code> keyword
should be updated to use <code>with</code> instead.</p>
</blockquote>
<p>The <a href="https://github.com/tc39/proposal-import-attributes">Import Attributes proposal</a> adds an inline syntax for module import
statements to pass on more information alongside the module specifier.</p>
<pre><code class="language-js"><span class="hljs-keyword">import</span> fooData <span class="hljs-keyword">from</span> <span class="hljs-string">'./foo.json'</span> <span class="hljs-keyword">with</span> { <span class="hljs-attr">type</span>: <span class="hljs-string">'json'</span> };

<span class="hljs-keyword">const</span> { <span class="hljs-attr">default</span>: barData } =
  <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'./bar.json'</span>, { <span class="hljs-attr">with</span>: { <span class="hljs-attr">type</span>: <span class="hljs-string">'json'</span> } });</code> <button class="copy-button">copy</button></pre>
<p>Node.js supports the following <code>type</code> values, for which the attribute is
mandatory:</p>













<table><thead><tr><th>Attribute <code>type</code></th><th>Needed for</th></tr></thead><tbody><tr><td><code>'json'</code></td><td><a href="#all_esm_json-modules">JSON modules</a></td></tr></tbody></table>
</section><section><h3>Built-in modules<span><a class="mark" href="#all_esm_built-in-modules" id="all_esm_built-in-modules">#</a></span><a aria-hidden="true" class="legacy" id="esm_built_in_modules"></a></h3>
<p><a href="#all_modules_built-in-modules">Built-in modules</a> 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 built-in modules are updated only by calling
<a href="#all_module_modulesyncbuiltinesmexports"><code>module.syncBuiltinESMExports()</code></a>.</p>
<pre><code class="language-js"><span class="hljs-keyword">import</span> <span class="hljs-title class_">EventEmitter</span> <span class="hljs-keyword">from</span> <span class="hljs-string">'node:events'</span>;
<span class="hljs-keyword">const</span> e = <span class="hljs-keyword">new</span> <span class="hljs-title class_">EventEmitter</span>();</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-js"><span class="hljs-keyword">import</span> { readFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-title function_">readFile</span>(<span class="hljs-string">'./foo.txt'</span>, <span class="hljs-function">(<span class="hljs-params">err, source</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err);
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(source);
  }
});</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-js"><span class="hljs-keyword">import</span> fs, { readFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">import</span> { syncBuiltinESMExports } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

fs.<span class="hljs-property">readFileSync</span> = <span class="hljs-function">() =></span> <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'Hello, ESM'</span>);
<span class="hljs-title function_">syncBuiltinESMExports</span>();

fs.<span class="hljs-property">readFileSync</span> === readFileSync;</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>import()</code> expressions<span><a class="mark" href="#all_esm_import-expressions" id="all_esm_import-expressions">#</a></span><a aria-hidden="true" class="legacy" id="esm_import_expressions"></a></h3>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import">Dynamic <code>import()</code></a> is supported in both CommonJS and ES modules. In CommonJS
modules it can be used to load ES modules.</p>
</section><section><h3><code>import.meta</code><span><a class="mark" href="#all_esm_importmeta" id="all_esm_importmeta">#</a></span><a aria-hidden="true" class="legacy" id="esm_import_meta"></a></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 <code>import.meta</code> meta property is an <code>Object</code> that contains the following
properties.</p>
<h4><code>import.meta.dirname</code><span><a class="mark" href="#all_esm_importmetadirname" id="all_esm_importmetadirname">#</a></span><a aria-hidden="true" class="legacy" id="esm_import_meta_dirname"></a></h4>
<div class="api_metadata">
<span>Added in: v20.11.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.2 - Release candidate</div><p></p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The directory name of the current module. This is the same as the
<a href="#all_path_pathdirnamepath"><code>path.dirname()</code></a> of the <a href="#all_esm_importmetafilename"><code>import.meta.filename</code></a>.</li>
</ul>
<blockquote>
<p><strong>Caveat</strong>: only present on <code>file:</code> modules.</p>
</blockquote>
<h4><code>import.meta.filename</code><span><a class="mark" href="#all_esm_importmetafilename" id="all_esm_importmetafilename">#</a></span><a aria-hidden="true" class="legacy" id="esm_import_meta_filename"></a></h4>
<div class="api_metadata">
<span>Added in: v20.11.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.2 - Release candidate</div><p></p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The full absolute path and filename of the current module, with
symlinks resolved.</li>
<li>This is the same as the <a href="#all_url_urlfileurltopathurl-options"><code>url.fileURLToPath()</code></a> of the
<a href="#all_esm_importmetaurl"><code>import.meta.url</code></a>.</li>
</ul>
<blockquote>
<p><strong>Caveat</strong> only local modules support this property. Modules not using the
<code>file:</code> protocol will not provide it.</p>
</blockquote>
<h4><code>import.meta.url</code><span><a class="mark" href="#all_esm_importmetaurl" id="all_esm_importmetaurl">#</a></span><a aria-hidden="true" class="legacy" id="esm_import_meta_url"></a></h4>
<ul>
<li><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>
<p>This is defined exactly the same as it is in browsers providing the URL of the
current module file.</p>
<p>This enables useful patterns such as relative file loading:</p>
<pre><code class="language-js"><span class="hljs-keyword">import</span> { readFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">const</span> buffer = <span class="hljs-title function_">readFileSync</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'./data.proto'</span>, <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>));</code> <button class="copy-button">copy</button></pre>
<h4><code>import.meta.resolve(specifier)</code><span><a class="mark" href="#all_esm_importmetaresolvespecifier" id="all_esm_importmetaresolvespecifier">#</a></span><a aria-hidden="true" class="legacy" id="esm_import_meta_resolve_specifier"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.6.0</td>
<td><p>Unflag <code>import.meta.resolve</code>, with <code>parentURL</code> parameter still flagged.</p></td></tr>
<tr><td>v20.6.0</td>
<td><p>This API no longer throws when targeting <code>file:</code> URLs that do not map to an existing file on the local FS.</p></td></tr>
<tr><td>v20.0.0</td>
<td><p>This API now returns a string synchronously instead of a Promise.</p></td></tr>
<tr><td>v16.2.0, v14.18.0</td>
<td><p>Add support for WHATWG <code>URL</code> object to <code>parentURL</code> parameter.</p></td></tr>
<tr><td>v13.9.0, v12.16.2</td>
<td><p><span>Added in: v13.9.0, v12.16.2</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.2 - Release candidate</div><p></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> The module specifier to resolve relative to the
current module.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The absolute URL string that the specifier would resolve to.</li>
</ul>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import.meta/resolve"><code>import.meta.resolve</code></a> is a module-relative resolution function scoped to
each module, returning the URL string.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> dependencyAsset = <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'component-lib/asset.css'</span>);
<span class="hljs-comment">// file:///app/node_modules/component-lib/asset.css</span>
<span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'./dep.js'</span>);
<span class="hljs-comment">// file:///app/dep.js</span></code> <button class="copy-button">copy</button></pre>
<p>All features of the Node.js module resolution are supported. Dependency
resolutions are subject to the permitted exports resolutions within the package.</p>
<p><strong>Caveats</strong>:</p>
<ul>
<li>This can result in synchronous file-system operations, which
can impact performance similarly to <code>require.resolve</code>.</li>
<li>This feature is not available within custom loaders (it would
create a deadlock).</li>
</ul>
<p><strong>Non-standard API</strong>:</p>
<p>When using the <code>--experimental-import-meta-resolve</code> flag, that function accepts
a second argument:</p>
<ul>
<li><code>parent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></a> An optional absolute parent module URL to resolve from.
<strong>Default:</strong> <code>import.meta.url</code></li>
</ul>
</section><section><h3>Interoperability with CommonJS<span><a class="mark" href="#all_esm_interoperability-with-commonjs" id="all_esm_interoperability-with-commonjs">#</a></span><a aria-hidden="true" class="legacy" id="esm_interoperability_with_commonjs"></a></h3>
<h4><code>import</code> statements<span><a class="mark" href="#all_esm_import-statements" id="all_esm_import-statements">#</a></span><a aria-hidden="true" class="legacy" id="esm_import_statements"></a></h4>
<p>An <code>import</code> statement can reference an ES module or a CommonJS module.
<code>import</code> statements are permitted only in ES modules, but dynamic <a href="#all_esm_import-expressions"><code>import()</code></a>
expressions are supported in CommonJS for loading ES modules.</p>
<p>When importing <a href="#all_esm_commonjs-namespaces">CommonJS modules</a>, the
<code>module.exports</code> object is provided as the default export. Named exports may be
available, provided by static analysis as a convenience for better ecosystem
compatibility.</p>
<h4><code>require</code><span><a class="mark" href="#all_esm_require" id="all_esm_require">#</a></span><a aria-hidden="true" class="legacy" id="esm_require"></a></h4>
<p>The CommonJS module <code>require</code> currently only supports loading synchronous ES
modules when <code>--experimental-require-module</code> is enabled.</p>
<p>See <a href="#all_modules_loading-ecmascript-modules-using-require">Loading ECMAScript modules using <code>require()</code></a> for details.</p>
<h4>CommonJS Namespaces<span><a class="mark" href="#all_esm_commonjs-namespaces" id="all_esm_commonjs-namespaces">#</a></span><a aria-hidden="true" class="legacy" id="esm_commonjs_namespaces"></a></h4>
<p>CommonJS modules consist of a <code>module.exports</code> object which can be of any type.</p>
<p>When importing a CommonJS module, it can be reliably imported using the ES
module default import or its corresponding sugar syntax:</p>
<!-- eslint-disable no-duplicate-imports -->
<pre><code class="language-js"><span class="hljs-keyword">import</span> { <span class="hljs-keyword">default</span> <span class="hljs-keyword">as</span> cjs } <span class="hljs-keyword">from</span> <span class="hljs-string">'cjs'</span>;

<span class="hljs-comment">// The following import statement is "syntax sugar" (equivalent but sweeter)</span>
<span class="hljs-comment">// for `{ default as cjsSugar }` in the above import statement:</span>
<span class="hljs-keyword">import</span> cjsSugar <span class="hljs-keyword">from</span> <span class="hljs-string">'cjs'</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(cjs);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(cjs === cjsSugar);
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   &#x3C;module.exports></span>
<span class="hljs-comment">//   true</span></code> <button class="copy-button">copy</button></pre>
<p>The ECMAScript Module Namespace representation of a CommonJS module is always
a namespace with a <code>default</code> export key pointing to the CommonJS
<code>module.exports</code> value.</p>
<p>This Module Namespace Exotic Object can be directly observed either when using
<code>import * as m from 'cjs'</code> or a dynamic import:</p>
<!-- eslint-skip -->
<pre><code class="language-js"><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> m <span class="hljs-keyword">from</span> <span class="hljs-string">'cjs'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(m);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(m === <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'cjs'</span>));
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   [Module] { default: &#x3C;module.exports> }</span>
<span class="hljs-comment">//   true</span></code> <button class="copy-button">copy</button></pre>
<p>For better compatibility with existing usage in the JS ecosystem, Node.js
in addition attempts to determine the CommonJS named exports of every imported
CommonJS module to provide them as separate ES module exports using a static
analysis process.</p>
<p>For example, consider a CommonJS module written:</p>
<pre><code class="language-js cjs"><span class="hljs-comment">// cjs.cjs</span>
<span class="hljs-built_in">exports</span>.<span class="hljs-property">name</span> = <span class="hljs-string">'exported'</span>;</code> <button class="copy-button">copy</button></pre>
<p>The preceding module supports named imports in ES modules:</p>
<!-- eslint-disable no-duplicate-imports -->
<pre><code class="language-js"><span class="hljs-keyword">import</span> { name } <span class="hljs-keyword">from</span> <span class="hljs-string">'./cjs.cjs'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(name);
<span class="hljs-comment">// Prints: 'exported'</span>

<span class="hljs-keyword">import</span> cjs <span class="hljs-keyword">from</span> <span class="hljs-string">'./cjs.cjs'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(cjs);
<span class="hljs-comment">// Prints: { name: 'exported' }</span>

<span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> m <span class="hljs-keyword">from</span> <span class="hljs-string">'./cjs.cjs'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(m);
<span class="hljs-comment">// Prints: [Module] { default: { name: 'exported' }, name: 'exported' }</span></code> <button class="copy-button">copy</button></pre>
<p>As can be seen from the last example of the Module Namespace Exotic Object being
logged, the <code>name</code> export is copied off of the <code>module.exports</code> object and set
directly on the ES module namespace when the module is imported.</p>
<p>Live binding updates or new exports added to <code>module.exports</code> are not detected
for these named exports.</p>
<p>The detection of named exports is based on common syntax patterns but does not
always correctly detect named exports. In these cases, using the default
import form described above can be a better option.</p>
<p>Named exports detection covers many common export patterns, reexport patterns
and build tool and transpiler outputs. See <a href="https://github.com/nodejs/cjs-module-lexer/tree/1.2.2">cjs-module-lexer</a> for the exact
semantics implemented.</p>
<h4>Differences between ES modules and CommonJS<span><a class="mark" href="#all_esm_differences-between-es-modules-and-commonjs" id="all_esm_differences-between-es-modules-and-commonjs">#</a></span><a aria-hidden="true" class="legacy" id="esm_differences_between_es_modules_and_commonjs"></a></h4>
<h5>No <code>require</code>, <code>exports</code>, or <code>module.exports</code><span><a class="mark" href="#all_esm_no-require-exports-or-moduleexports" id="all_esm_no-require-exports-or-moduleexports">#</a></span><a aria-hidden="true" class="legacy" id="esm_no_require_exports_or_module_exports"></a></h5>
<p>In most cases, the ES module <code>import</code> can be used to load CommonJS modules.</p>
<p>If needed, a <code>require</code> function can be constructed within an ES module using
<a href="#all_module_modulecreaterequirefilename"><code>module.createRequire()</code></a>.</p>
<h5>No <code>__filename</code> or <code>__dirname</code><span><a class="mark" href="#all_esm_no-__filename-or-__dirname" id="all_esm_no-__filename-or-__dirname">#</a></span><a aria-hidden="true" class="legacy" id="esm_no_filename_or_dirname"></a></h5>
<p>These CommonJS variables are not available in ES modules.</p>
<p><code>__filename</code> and <code>__dirname</code> use cases can be replicated via
<a href="#all_esm_importmetafilename"><code>import.meta.filename</code></a> and <a href="#all_esm_importmetadirname"><code>import.meta.dirname</code></a>.</p>
<h5>No Addon Loading<span><a class="mark" href="#all_esm_no-addon-loading" id="all_esm_no-addon-loading">#</a></span><a aria-hidden="true" class="legacy" id="esm_no_addon_loading"></a></h5>
<p><a href="addons.html">Addons</a> are not currently supported with ES module imports.</p>
<p>They can instead be loaded with <a href="#all_module_modulecreaterequirefilename"><code>module.createRequire()</code></a> or
<a href="#all_process_processdlopenmodule-filename-flags"><code>process.dlopen</code></a>.</p>
<h5>No <code>require.resolve</code><span><a class="mark" href="#all_esm_no-requireresolve" id="all_esm_no-requireresolve">#</a></span><a aria-hidden="true" class="legacy" id="esm_no_require_resolve"></a></h5>
<p>Relative resolution can be handled via <code>new URL('./local', import.meta.url)</code>.</p>
<p>For a complete <code>require.resolve</code> replacement, there is the
<a href="#all_esm_importmetaresolvespecifier">import.meta.resolve</a> API.</p>
<p>Alternatively <code>module.createRequire()</code> can be used.</p>
<h5>No <code>NODE_PATH</code><span><a class="mark" href="#all_esm_no-node_path" id="all_esm_no-node_path">#</a></span><a aria-hidden="true" class="legacy" id="esm_no_node_path"></a></h5>
<p><code>NODE_PATH</code> is not part of resolving <code>import</code> specifiers. Please use symlinks
if this behavior is desired.</p>
<h5>No <code>require.extensions</code><span><a class="mark" href="#all_esm_no-requireextensions" id="all_esm_no-requireextensions">#</a></span><a aria-hidden="true" class="legacy" id="esm_no_require_extensions"></a></h5>
<p><code>require.extensions</code> is not used by <code>import</code>. Module customization hooks can
provide a replacement.</p>
<h5>No <code>require.cache</code><span><a class="mark" href="#all_esm_no-requirecache" id="all_esm_no-requirecache">#</a></span><a aria-hidden="true" class="legacy" id="esm_no_require_cache"></a></h5>
<p><code>require.cache</code> is not used by <code>import</code> as the ES module loader has its own
separate cache.</p>
<p><i id="esm_experimental_json_modules"></i></p>
</section><section><h3>JSON modules<span><a class="mark" href="#all_esm_json-modules" id="all_esm_json-modules">#</a></span><a aria-hidden="true" class="legacy" id="esm_json_modules"></a></h3>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>JSON files can be referenced by <code>import</code>:</p>
<pre><code class="language-js"><span class="hljs-keyword">import</span> packageConfig <span class="hljs-keyword">from</span> <span class="hljs-string">'./package.json'</span> <span class="hljs-keyword">with</span> { <span class="hljs-attr">type</span>: <span class="hljs-string">'json'</span> };</code> <button class="copy-button">copy</button></pre>
<p>The <code>with { type: 'json' }</code> syntax is mandatory; see <a href="#all_esm_import-attributes">Import Attributes</a>.</p>
<p>The imported JSON only exposes a <code>default</code> export. There is no support for named
exports. A cache entry is created in the CommonJS cache to avoid duplication.
The same object is returned in CommonJS if the JSON module has already been
imported from the same path.</p>
<p><i id="esm_experimental_wasm_modules"></i></p>
</section><section><h3>Wasm modules<span><a class="mark" href="#all_esm_wasm-modules" id="all_esm_wasm-modules">#</a></span><a aria-hidden="true" class="legacy" id="esm_wasm_modules"></a></h3>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Importing WebAssembly 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 WebAssembly</a>.</p>
<p>For example, an <code>index.mjs</code> containing:</p>
<pre><code class="language-js"><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> M <span class="hljs-keyword">from</span> <span class="hljs-string">'./module.wasm'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(M);</code> <button class="copy-button">copy</button></pre>
<p>executed under:</p>
<pre><code class="language-bash">node --experimental-wasm-modules index.mjs</code> <button class="copy-button">copy</button></pre>
<p>would provide the exports interface for the instantiation of <code>module.wasm</code>.</p>
<p><i id="esm_experimental_top_level_await"></i></p>
</section><section><h3>Top-level <code>await</code><span><a class="mark" href="#all_esm_top-level-await" id="all_esm_top-level-await">#</a></span><a aria-hidden="true" class="legacy" id="esm_top_level_await"></a></h3>
<div class="api_metadata">
<span>Added in: v14.8.0</span>
</div>
<p>The <code>await</code> keyword may be used in the top level body of an ECMAScript module.</p>
<p>Assuming an <code>a.mjs</code> with</p>
<pre><code class="language-js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> five = <span class="hljs-keyword">await</span> <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">resolve</span>(<span class="hljs-number">5</span>);</code> <button class="copy-button">copy</button></pre>
<p>And a <code>b.mjs</code> with</p>
<pre><code class="language-js"><span class="hljs-keyword">import</span> { five } <span class="hljs-keyword">from</span> <span class="hljs-string">'./a.mjs'</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(five); <span class="hljs-comment">// Logs `5`</span></code> <button class="copy-button">copy</button></pre>
<pre><code class="language-bash">node b.mjs <span class="hljs-comment"># works</span></code> <button class="copy-button">copy</button></pre>
<p>If a top level <code>await</code> expression never resolves, the <code>node</code> process will exit
with a <code>13</code> <a href="#all_process_exit-codes">status code</a>.</p>
<pre><code class="language-js"><span class="hljs-keyword">import</span> { spawn } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:child_process'</span>;
<span class="hljs-keyword">import</span> { execPath } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-title function_">spawn</span>(execPath, [
  <span class="hljs-string">'--input-type=module'</span>,
  <span class="hljs-string">'--eval'</span>,
  <span class="hljs-comment">// Never-resolving Promise:</span>
  <span class="hljs-string">'await new Promise(() => {})'</span>,
]).<span class="hljs-title function_">once</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(code); <span class="hljs-comment">// Logs `13`</span>
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3>HTTPS and HTTP imports<span><a class="mark" href="#all_esm_https-and-http-imports" id="all_esm_https-and-http-imports">#</a></span><a aria-hidden="true" class="legacy" id="esm_https_and_http_imports"></a></h3>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Importing network based modules using <code>https:</code> and <code>http:</code> is supported under
the <code>--experimental-network-imports</code> flag. This allows web browser-like imports
to work in Node.js with a few differences due to application stability and
security concerns that are different when running in a privileged environment
instead of a browser sandbox.</p>
<h4>Imports are limited to HTTP/1<span><a class="mark" href="#all_esm_imports-are-limited-to-http1" id="all_esm_imports-are-limited-to-http1">#</a></span><a aria-hidden="true" class="legacy" id="esm_imports_are_limited_to_http_1"></a></h4>
<p>Automatic protocol negotiation for HTTP/2 and HTTP/3 is not yet supported.</p>
<h4>HTTP is limited to loopback addresses<span><a class="mark" href="#all_esm_http-is-limited-to-loopback-addresses" id="all_esm_http-is-limited-to-loopback-addresses">#</a></span><a aria-hidden="true" class="legacy" id="esm_http_is_limited_to_loopback_addresses"></a></h4>
<p><code>http:</code> is vulnerable to man-in-the-middle attacks and is not allowed to be
used for addresses outside of the IPv4 address <code>127.0.0.0/8</code> (<code>127.0.0.1</code> to
<code>127.255.255.255</code>) and the IPv6 address <code>::1</code>. Support for <code>http:</code> is intended
to be used for local development.</p>
<h4>Authentication is never sent to the destination server.<span><a class="mark" href="#all_esm_authentication-is-never-sent-to-the-destination-server" id="all_esm_authentication-is-never-sent-to-the-destination-server">#</a></span><a aria-hidden="true" class="legacy" id="esm_authentication_is_never_sent_to_the_destination_server"></a></h4>
<p><code>Authorization</code>, <code>Cookie</code>, and <code>Proxy-Authorization</code> headers are not sent to the
server. Avoid including user info in parts of imported URLs. A security model
for safely using these on the server is being worked on.</p>
<h4>CORS is never checked on the destination server<span><a class="mark" href="#all_esm_cors-is-never-checked-on-the-destination-server" id="all_esm_cors-is-never-checked-on-the-destination-server">#</a></span><a aria-hidden="true" class="legacy" id="esm_cors_is_never_checked_on_the_destination_server"></a></h4>
<p>CORS is designed to allow a server to limit the consumers of an API to a
specific set of hosts. This is not supported as it does not make sense for a
server-based implementation.</p>
<h4>Cannot load non-network dependencies<span><a class="mark" href="#all_esm_cannot-load-non-network-dependencies" id="all_esm_cannot-load-non-network-dependencies">#</a></span><a aria-hidden="true" class="legacy" id="esm_cannot_load_non_network_dependencies"></a></h4>
<p>These modules cannot access other modules that are not over <code>http:</code> or <code>https:</code>.
To still access local modules while avoiding the security concern, pass in
references to the local dependencies:</p>
<pre><code class="language-js mjs"><span class="hljs-comment">// file.mjs</span>
<span class="hljs-keyword">import</span> worker_threads <span class="hljs-keyword">from</span> <span class="hljs-string">'node:worker_threads'</span>;
<span class="hljs-keyword">import</span> { configure, resize } <span class="hljs-keyword">from</span> <span class="hljs-string">'https://example.com/imagelib.mjs'</span>;
<span class="hljs-title function_">configure</span>({ worker_threads });</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-js mjs"><span class="hljs-comment">// https://example.com/imagelib.mjs</span>
<span class="hljs-keyword">let</span> worker_threads;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">configure</span>(<span class="hljs-params">opts</span>) {
  worker_threads = opts.<span class="hljs-property">worker_threads</span>;
}
<span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">resize</span>(<span class="hljs-params">img, size</span>) {
  <span class="hljs-comment">// Perform resizing in worker_thread to avoid main thread blocking</span>
}</code> <button class="copy-button">copy</button></pre>
<h4>Network-based loading is not enabled by default<span><a class="mark" href="#all_esm_network-based-loading-is-not-enabled-by-default" id="all_esm_network-based-loading-is-not-enabled-by-default">#</a></span><a aria-hidden="true" class="legacy" id="esm_network_based_loading_is_not_enabled_by_default"></a></h4>
<p>For now, the <code>--experimental-network-imports</code> flag is required to enable loading
resources over <code>http:</code> or <code>https:</code>. In the future, a different mechanism will be
used to enforce this. Opt-in is required to prevent transitive dependencies
inadvertently using potentially mutable state that could affect reliability
of Node.js applications.</p>
<p><i id="esm_experimental_loaders"></i></p>
</section><section><h3>Loaders<span><a class="mark" href="#all_esm_loaders" id="all_esm_loaders">#</a></span><a aria-hidden="true" class="legacy" id="esm_loaders"></a></h3>
<p>The former Loaders documentation is now at
<a href="#all_module_customization-hooks">Modules: Customization hooks</a>.</p>
</section><section><h3>Resolution and loading algorithm<span><a class="mark" href="#all_esm_resolution-and-loading-algorithm" id="all_esm_resolution-and-loading-algorithm">#</a></span><a aria-hidden="true" class="legacy" id="esm_resolution_and_loading_algorithm"></a></h3>
<h4>Features<span><a class="mark" href="#all_esm_features" id="all_esm_features">#</a></span><a aria-hidden="true" class="legacy" id="esm_features"></a></h4>
<p>The default resolver has the following properties:</p>
<ul>
<li>FileURL-based resolution as is used by ES modules</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>
<li>Does not fail on unknown extensions or protocols</li>
<li>Can optionally provide a hint of the format to the loading phase</li>
</ul>
<p>The default loader has the following properties</p>
<ul>
<li>Support for builtin module loading via <code>node:</code> URLs</li>
<li>Support for "inline" module loading via <code>data:</code> URLs</li>
<li>Support for <code>file:</code> module loading</li>
<li>Fails on any other URL protocol</li>
<li>Fails on unknown extensions for <code>file:</code> loading
(supports only <code>.cjs</code>, <code>.js</code>, and <code>.mjs</code>)</li>
</ul>
<h4>Resolution algorithm<span><a class="mark" href="#all_esm_resolution-algorithm" id="all_esm_resolution-algorithm">#</a></span><a aria-hidden="true" class="legacy" id="esm_resolution_algorithm"></a></h4>
<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 resolution algorithm determines the full resolved URL for a module
load, along with its suggested module format. The resolution algorithm
does not determine whether the resolved URL protocol can be loaded,
or whether the file extensions are permitted, instead these validations
are applied by Node.js during the load phase
(for example, if it was asked to load a URL that has a protocol that is
not <code>file:</code>, <code>data:</code>, <code>node:</code>, or if <code>--experimental-network-imports</code>
is enabled, <code>https:</code>).</p>
<p>The algorithm also tries to determine the format of the file based
on the extension (see <code>ESM_FILE_FORMAT</code> algorithm below). If it does
not recognize the file extension (eg if it is not <code>.mjs</code>, <code>.cjs</code>, or
<code>.json</code>), then a format of <code>undefined</code> is returned,
which will throw during the load phase.</p>
<p>The algorithm to determine the module format of a resolved URL is
provided by <strong>ESM_FILE_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>defaultConditions</em> is the conditional environment name 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 or imports define a target module
for 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>Package Import Not Defined</em>: Package imports do not define the specifier.</li>
<li><em>Module Not Found</em>: The package or module requested does not exist.</li>
<li><em>Unsupported Directory Import</em>: The resolved path corresponds to a directory,
which is not a supported target for module imports.</li>
</ul>
<h4>Resolution Algorithm Specification<span><a class="mark" href="#all_esm_resolution-algorithm-specification" id="all_esm_resolution-algorithm-specification">#</a></span><a aria-hidden="true" class="legacy" id="esm_resolution_algorithm_specification"></a></h4>
<p><strong>ESM_RESOLVE</strong>(<em>specifier</em>, <em>parentURL</em>)</p>
<blockquote>
<ol>
<li>Let <em>resolved</em> be <strong>undefined</strong>.</li>
<li>If <em>specifier</em> is a valid URL, then
<ol>
<li>Set <em>resolved</em> to the result of parsing and reserializing
<em>specifier</em> as a URL.</li>
</ol>
</li>
<li>Otherwise, if <em>specifier</em> starts with <em>"/"</em>, <em>"./"</em>, or <em>"../"</em>, then
<ol>
<li>Set <em>resolved</em> to the URL resolution of <em>specifier</em> relative to
<em>parentURL</em>.</li>
</ol>
</li>
<li>Otherwise, if <em>specifier</em> starts with <em>"#"</em>, then
<ol>
<li>Set <em>resolved</em> to the result of
<strong>PACKAGE_IMPORTS_RESOLVE</strong>(<em>specifier</em>,
<em>parentURL</em>, <em>defaultConditions</em>).</li>
</ol>
</li>
<li>Otherwise,
<ol>
<li>Note: <em>specifier</em> is now a bare specifier.</li>
<li>Set <em>resolved</em> the result of
<strong>PACKAGE_RESOLVE</strong>(<em>specifier</em>, <em>parentURL</em>).</li>
</ol>
</li>
<li>Let <em>format</em> be <strong>undefined</strong>.</li>
<li>If <em>resolved</em> is a <em>"file:"</em> URL, then
<ol>
<li>If <em>resolved</em> contains any percent encodings of <em>"/"</em> or <em>"\"</em> (<em>"%2F"</em>
and <em>"%5C"</em> respectively), then
<ol>
<li>Throw an <em>Invalid Module Specifier</em> error.</li>
</ol>
</li>
<li>If the file at <em>resolved</em> is a directory, then
<ol>
<li>Throw an <em>Unsupported Directory Import</em> error.</li>
</ol>
</li>
<li>If the file at <em>resolved</em> does not exist, then
<ol>
<li>Throw a <em>Module Not Found</em> error.</li>
</ol>
</li>
<li>Set <em>resolved</em> to the real path of <em>resolved</em>, maintaining the
same URL querystring and fragment components.</li>
<li>Set <em>format</em> to the result of <strong>ESM_FILE_FORMAT</strong>(<em>resolved</em>).</li>
</ol>
</li>
<li>Otherwise,
<ol>
<li>Set <em>format</em> the module format of the content type associated with the
URL <em>resolved</em>.</li>
</ol>
</li>
<li>Return <em>format</em> and <em>resolved</em> to the loading phase</li>
</ol>
</blockquote>
<p><strong>PACKAGE_RESOLVE</strong>(<em>packageSpecifier</em>, <em>parentURL</em>)</p>
<blockquote>
<ol>
<li>Let <em>packageName</em> be <strong>undefined</strong>.</li>
<li>If <em>packageSpecifier</em> is an empty string, then
<ol>
<li>Throw an <em>Invalid Module Specifier</em> error.</li>
</ol>
</li>
<li>If <em>packageSpecifier</em> is a Node.js builtin module name, then
<ol>
<li>Return the string <em>"node:"</em> concatenated with <em>packageSpecifier</em>.</li>
</ol>
</li>
<li>If <em>packageSpecifier</em> does not start with <em>"@"</em>, then
<ol>
<li>Set <em>packageName</em> to the substring of <em>packageSpecifier</em> until the first
<em>"/"</em> separator or the end of the string.</li>
</ol>
</li>
<li>Otherwise,
<ol>
<li>If <em>packageSpecifier</em> does not contain a <em>"/"</em> separator, then
<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>If <em>packageName</em> starts with <em>"."</em> or contains <em>"\"</em> or <em>"%"</em>, then
<ol>
<li>Throw an <em>Invalid Module Specifier</em> error.</li>
</ol>
</li>
<li>Let <em>packageSubpath</em> be <em>"."</em> concatenated with the substring of
<em>packageSpecifier</em> from the position at the length of <em>packageName</em>.</li>
<li>If <em>packageSubpath</em> ends in <em>"/"</em>, then
<ol>
<li>Throw an <em>Invalid Module Specifier</em> error.</li>
</ol>
</li>
<li>Let <em>selfUrl</em> be the result of
<strong>PACKAGE_SELF_RESOLVE</strong>(<em>packageName</em>, <em>packageSubpath</em>, <em>parentURL</em>).</li>
<li>If <em>selfUrl</em> is not <strong>undefined</strong>, return <em>selfUrl</em>.</li>
<li>While <em>parentURL</em> is not the file system root,
<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>If the folder at <em>packageURL</em> does not exist, then
<ol>
<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>If <em>pjson</em> is not <strong>null</strong> and <em>pjson</em>.<em>exports</em> is not <strong>null</strong> or
<strong>undefined</strong>, then
<ol>
<li>Return the result of <strong>PACKAGE_EXPORTS_RESOLVE</strong>(<em>packageURL</em>,
<em>packageSubpath</em>, <em>pjson.exports</em>, <em>defaultConditions</em>).</li>
</ol>
</li>
<li>Otherwise, if <em>packageSubpath</em> is equal to <em>"."</em>, then
<ol>
<li>If <em>pjson.main</em> is a string, then
<ol>
<li>Return the URL resolution of <em>main</em> in <em>packageURL</em>.</li>
</ol>
</li>
</ol>
</li>
<li>Otherwise,
<ol>
<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>PACKAGE_SELF_RESOLVE</strong>(<em>packageName</em>, <em>packageSubpath</em>, <em>parentURL</em>)</p>
<blockquote>
<ol>
<li>Let <em>packageURL</em> be the result of <strong>LOOKUP_PACKAGE_SCOPE</strong>(<em>parentURL</em>).</li>
<li>If <em>packageURL</em> is <strong>null</strong>, then
<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>If <em>pjson</em> is <strong>null</strong> or if <em>pjson</em>.<em>exports</em> is <strong>null</strong> or
<strong>undefined</strong>, then
<ol>
<li>Return <strong>undefined</strong>.</li>
</ol>
</li>
<li>If <em>pjson.name</em> is equal to <em>packageName</em>, then
<ol>
<li>Return the result of <strong>PACKAGE_EXPORTS_RESOLVE</strong>(<em>packageURL</em>,
<em>packageSubpath</em>, <em>pjson.exports</em>, <em>defaultConditions</em>).</li>
</ol>
</li>
<li>Otherwise, return <strong>undefined</strong>.</li>
</ol>
</blockquote>
<p><strong>PACKAGE_EXPORTS_RESOLVE</strong>(<em>packageURL</em>, <em>subpath</em>, <em>exports</em>, <em>conditions</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>If <em>subpath</em> is equal to <em>"."</em>, then
<ol>
<li>Let <em>mainExport</em> be <strong>undefined</strong>.</li>
<li>If <em>exports</em> is a String or Array, or an Object containing no keys
starting with <em>"."</em>, then
<ol>
<li>Set <em>mainExport</em> to <em>exports</em>.</li>
</ol>
</li>
<li>Otherwise if <em>exports</em> is an Object containing a <em>"."</em> property, then
<ol>
<li>Set <em>mainExport</em> to <em>exports</em>[<em>"."</em>].</li>
</ol>
</li>
<li>If <em>mainExport</em> is not <strong>undefined</strong>, then
<ol>
<li>Let <em>resolved</em> be the result of <strong>PACKAGE_TARGET_RESOLVE</strong>(
<em>packageURL</em>, <em>mainExport</em>, <strong>null</strong>, <strong>false</strong>, <em>conditions</em>).</li>
<li>If <em>resolved</em> is not <strong>null</strong> or <strong>undefined</strong>, return <em>resolved</em>.</li>
</ol>
</li>
</ol>
</li>
<li>Otherwise, if <em>exports</em> is an Object and all keys of <em>exports</em> start with
<em>"."</em>, then
<ol>
<li>Assert: <em>subpath</em> begins with <em>"./"</em>.</li>
<li>Let <em>resolved</em> be the result of <strong>PACKAGE_IMPORTS_EXPORTS_RESOLVE</strong>(
<em>subpath</em>, <em>exports</em>, <em>packageURL</em>, <strong>false</strong>, <em>conditions</em>).</li>
<li>If <em>resolved</em> is not <strong>null</strong> or <strong>undefined</strong>, return <em>resolved</em>.</li>
</ol>
</li>
<li>Throw a <em>Package Path Not Exported</em> error.</li>
</ol>
</blockquote>
<p><strong>PACKAGE_IMPORTS_RESOLVE</strong>(<em>specifier</em>, <em>parentURL</em>, <em>conditions</em>)</p>
<blockquote>
<ol>
<li>Assert: <em>specifier</em> begins with <em>"#"</em>.</li>
<li>If <em>specifier</em> is exactly equal to <em>"#"</em> or starts with <em>"#/"</em>, then
<ol>
<li>Throw an <em>Invalid Module Specifier</em> error.</li>
</ol>
</li>
<li>Let <em>packageURL</em> be the result of <strong>LOOKUP_PACKAGE_SCOPE</strong>(<em>parentURL</em>).</li>
<li>If <em>packageURL</em> is not <strong>null</strong>, then
<ol>
<li>Let <em>pjson</em> be the result of <strong>READ_PACKAGE_JSON</strong>(<em>packageURL</em>).</li>
<li>If <em>pjson.imports</em> is a non-null Object, then
<ol>
<li>Let <em>resolved</em> be the result of
<strong>PACKAGE_IMPORTS_EXPORTS_RESOLVE</strong>(
<em>specifier</em>, <em>pjson.imports</em>, <em>packageURL</em>, <strong>true</strong>, <em>conditions</em>).</li>
<li>If <em>resolved</em> is not <strong>null</strong> or <strong>undefined</strong>, return <em>resolved</em>.</li>
</ol>
</li>
</ol>
</li>
<li>Throw a <em>Package Import Not Defined</em> error.</li>
</ol>
</blockquote>
<p><strong>PACKAGE_IMPORTS_EXPORTS_RESOLVE</strong>(<em>matchKey</em>, <em>matchObj</em>, <em>packageURL</em>,
<em>isImports</em>, <em>conditions</em>)</p>
<blockquote>
<ol>
<li>If <em>matchKey</em> is a key of <em>matchObj</em> and does not contain <em>"*"</em>, then
<ol>
<li>Let <em>target</em> be the value of <em>matchObj</em>[<em>matchKey</em>].</li>
<li>Return the result of <strong>PACKAGE_TARGET_RESOLVE</strong>(<em>packageURL</em>,
<em>target</em>, <strong>null</strong>, <em>isImports</em>, <em>conditions</em>).</li>
</ol>
</li>
<li>Let <em>expansionKeys</em> be the list of keys of <em>matchObj</em> containing only a
single <em>"*"</em>, sorted by the sorting function <strong>PATTERN_KEY_COMPARE</strong>
which orders in descending order of specificity.</li>
<li>For each key <em>expansionKey</em> in <em>expansionKeys</em>, do
<ol>
<li>Let <em>patternBase</em> be the substring of <em>expansionKey</em> up to but excluding
the first <em>"*"</em> character.</li>
<li>If <em>matchKey</em> starts with but is not equal to <em>patternBase</em>, then
<ol>
<li>Let <em>patternTrailer</em> be the substring of <em>expansionKey</em> from the
index after the first <em>"*"</em> character.</li>
<li>If <em>patternTrailer</em> has zero length, or if <em>matchKey</em> ends with
<em>patternTrailer</em> and the length of <em>matchKey</em> is greater than or
equal to the length of <em>expansionKey</em>, then
<ol>
<li>Let <em>target</em> be the value of <em>matchObj</em>[<em>expansionKey</em>].</li>
<li>Let <em>patternMatch</em> be the substring of <em>matchKey</em> starting at the
index of the length of <em>patternBase</em> up to the length of
<em>matchKey</em> minus the length of <em>patternTrailer</em>.</li>
<li>Return the result of <strong>PACKAGE_TARGET_RESOLVE</strong>(<em>packageURL</em>,
<em>target</em>, <em>patternMatch</em>, <em>isImports</em>, <em>conditions</em>).</li>
</ol>
</li>
</ol>
</li>
</ol>
</li>
<li>Return <strong>null</strong>.</li>
</ol>
</blockquote>
<p><strong>PATTERN_KEY_COMPARE</strong>(<em>keyA</em>, <em>keyB</em>)</p>
<blockquote>
<ol>
<li>Assert: <em>keyA</em> contains only a single <em>"*"</em>.</li>
<li>Assert: <em>keyB</em> contains only a single <em>"*"</em>.</li>
<li>Let <em>baseLengthA</em> be the index of <em>"*"</em> in <em>keyA</em>.</li>
<li>Let <em>baseLengthB</em> be the index of <em>"*"</em> in <em>keyB</em>.</li>
<li>If <em>baseLengthA</em> is greater than <em>baseLengthB</em>, return -1.</li>
<li>If <em>baseLengthB</em> is greater than <em>baseLengthA</em>, return 1.</li>
<li>If the length of <em>keyA</em> is greater than the length of <em>keyB</em>, return -1.</li>
<li>If the length of <em>keyB</em> is greater than the length of <em>keyA</em>, return 1.</li>
<li>Return 0.</li>
</ol>
</blockquote>
<p><strong>PACKAGE_TARGET_RESOLVE</strong>(<em>packageURL</em>, <em>target</em>, <em>patternMatch</em>,
<em>isImports</em>, <em>conditions</em>)</p>
<blockquote>
<ol>
<li>If <em>target</em> is a String, then
<ol>
<li>If <em>target</em> does not start with <em>"./"</em>, then
<ol>
<li>If <em>isImports</em> is <strong>false</strong>, or if <em>target</em> starts with <em>"../"</em> or
<em>"/"</em>, or if <em>target</em> is a valid URL, then
<ol>
<li>Throw an <em>Invalid Package Target</em> error.</li>
</ol>
</li>
<li>If <em>patternMatch</em> is a String, then
<ol>
<li>Return <strong>PACKAGE_RESOLVE</strong>(<em>target</em> with every instance of <em>"*"</em>
replaced by <em>patternMatch</em>, <em>packageURL</em> + <em>"/"</em>).</li>
</ol>
</li>
<li>Return <strong>PACKAGE_RESOLVE</strong>(<em>target</em>, <em>packageURL</em> + <em>"/"</em>).</li>
</ol>
</li>
<li>If <em>target</em> split on <em>"/"</em> or <em>"\"</em> contains any <em>""</em>, <em>"."</em>, <em>".."</em>,
or <em>"node_modules"</em> segments after the first <em>"."</em> segment, case
insensitive and including percent encoded variants, 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>Assert: <em>packageURL</em> is contained in <em>resolvedTarget</em>.</li>
<li>If <em>patternMatch</em> is <strong>null</strong>, then
<ol>
<li>Return <em>resolvedTarget</em>.</li>
</ol>
</li>
<li>If <em>patternMatch</em> split on <em>"/"</em> or <em>"\"</em> contains any <em>""</em>, <em>"."</em>,
<em>".."</em>, or <em>"node_modules"</em> segments, case insensitive and including
percent encoded variants, throw an <em>Invalid Module Specifier</em> error.</li>
<li>Return the URL resolution of <em>resolvedTarget</em> with every instance of
<em>"*"</em> replaced with <em>patternMatch</em>.</li>
</ol>
</li>
<li>Otherwise, if <em>target</em> is a non-null Object, then
<ol>
<li>If <em>target</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>For each property <em>p</em> of <em>target</em>, in object insertion order as,
<ol>
<li>If <em>p</em> equals <em>"default"</em> or <em>conditions</em> contains an entry for <em>p</em>,
then
<ol>
<li>Let <em>targetValue</em> be the value of the <em>p</em> property in <em>target</em>.</li>
<li>Let <em>resolved</em> be the result of <strong>PACKAGE_TARGET_RESOLVE</strong>(
<em>packageURL</em>, <em>targetValue</em>, <em>patternMatch</em>, <em>isImports</em>,
<em>conditions</em>).</li>
<li>If <em>resolved</em> is equal to <strong>undefined</strong>, continue the loop.</li>
<li>Return <em>resolved</em>.</li>
</ol>
</li>
</ol>
</li>
<li>Return <strong>undefined</strong>.</li>
</ol>
</li>
<li>Otherwise, if <em>target</em> is an Array, then
<ol>
<li>If _target.length is zero, return <strong>null</strong>.</li>
<li>For each item <em>targetValue</em> in <em>target</em>, do
<ol>
<li>Let <em>resolved</em> be the result of <strong>PACKAGE_TARGET_RESOLVE</strong>(
<em>packageURL</em>, <em>targetValue</em>, <em>patternMatch</em>, <em>isImports</em>,
<em>conditions</em>), continuing the loop on any <em>Invalid Package Target</em>
error.</li>
<li>If <em>resolved</em> is <strong>undefined</strong>, continue the loop.</li>
<li>Return <em>resolved</em>.</li>
</ol>
</li>
<li>Return or throw the last fallback resolution <strong>null</strong> return or error.</li>
</ol>
</li>
<li>Otherwise, if <em>target</em> is <em>null</em>, return <strong>null</strong>.</li>
<li>Otherwise throw an <em>Invalid Package Target</em> error.</li>
</ol>
</blockquote>
<p><strong>ESM_FILE_FORMAT</strong>(<em>url</em>)</p>
<blockquote>
<ol>
<li>Assert: <em>url</em> corresponds to an existing file.</li>
<li>If <em>url</em> ends in <em>".mjs"</em>, then
<ol>
<li>Return <em>"module"</em>.</li>
</ol>
</li>
<li>If <em>url</em> ends in <em>".cjs"</em>, then
<ol>
<li>Return <em>"commonjs"</em>.</li>
</ol>
</li>
<li>If <em>url</em> ends in <em>".json"</em>, then
<ol>
<li>Return <em>"json"</em>.</li>
</ol>
</li>
<li>If <code>--experimental-wasm-modules</code> is enabled and <em>url</em> ends in
<em>".wasm"</em>, then
<ol>
<li>Return <em>"wasm"</em>.</li>
</ol>
</li>
<li>Let <em>packageURL</em> be the result of <strong>LOOKUP_PACKAGE_SCOPE</strong>(<em>url</em>).</li>
<li>Let <em>pjson</em> be the result of <strong>READ_PACKAGE_JSON</strong>(<em>packageURL</em>).</li>
<li>Let <em>packageType</em> be <strong>null</strong>.</li>
<li>If <em>pjson?.type</em> is <em>"module"</em> or <em>"commonjs"</em>, then
<ol>
<li>Set <em>packageType</em> to <em>pjson.type</em>.</li>
</ol>
</li>
<li>If <em>url</em> ends in <em>".js"</em>, then
<ol>
<li>If <em>packageType</em> is not <strong>null</strong>, then
<ol>
<li>Return <em>packageType</em>.</li>
</ol>
</li>
<li>If <code>--experimental-detect-module</code> is enabled and the result of
<strong>DETECT_MODULE_SYNTAX</strong>(<em>source</em>) is true, then
<ol>
<li>Return <em>"module"</em>.</li>
</ol>
</li>
<li>Return <em>"commonjs"</em>.</li>
</ol>
</li>
<li>If <em>url</em> does not have any extension, then
<ol>
<li>If <em>packageType</em> is <em>"module"</em> and <code>--experimental-wasm-modules</code> is
enabled and the file at <em>url</em> contains the header for a WebAssembly
module, then
<ol>
<li>Return <em>"wasm"</em>.</li>
</ol>
</li>
<li>If <em>packageType</em> is not <strong>null</strong>, then
<ol>
<li>Return <em>packageType</em>.</li>
</ol>
</li>
<li>If <code>--experimental-detect-module</code> is enabled and the source of
module contains static import or export syntax, then
<ol>
<li>Return <em>"module"</em>.</li>
</ol>
</li>
<li>Return <em>"commonjs"</em>.</li>
</ol>
</li>
<li>Return <strong>undefined</strong> (will throw during load phase).</li>
</ol>
</blockquote>
<p><strong>LOOKUP_PACKAGE_SCOPE</strong>(<em>url</em>)</p>
<blockquote>
<ol>
<li>Let <em>scopeURL</em> be <em>url</em>.</li>
<li>While <em>scopeURL</em> is not the file system root,
<ol>
<li>Set <em>scopeURL</em> to the parent URL of <em>scopeURL</em>.</li>
<li>If <em>scopeURL</em> ends in a <em>"node_modules"</em> path segment, return <strong>null</strong>.</li>
<li>Let <em>pjsonURL</em> be the resolution of <em>"package.json"</em> within
<em>scopeURL</em>.</li>
<li>if the file at <em>pjsonURL</em> exists, then
<ol>
<li>Return <em>scopeURL</em>.</li>
</ol>
</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>If the file at <em>pjsonURL</em> does not exist, then
<ol>
<li>Return <strong>null</strong>.</li>
</ol>
</li>
<li>If the file at <em>packageURL</em> does not parse as valid JSON, then
<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>
<p><strong>DETECT_MODULE_SYNTAX</strong>(<em>source</em>)</p>
<blockquote>
<ol>
<li>Parse <em>source</em> as an ECMAScript module.</li>
<li>If the parse is successful, then
<ol>
<li>If <em>source</em> contains top-level <code>await</code>, static <code>import</code> or <code>export</code>
statements, or <code>import.meta</code>, return <strong>true</strong>.</li>
<li>If <em>source</em> contains a top-level lexical declaration (<code>const</code>, <code>let</code>,
or <code>class</code>) of any of the CommonJS wrapper variables (<code>require</code>,
<code>exports</code>, <code>module</code>, <code>__filename</code>, or <code>__dirname</code>) then return <strong>true</strong>.</li>
</ol>
</li>
<li>Else return <strong>false</strong>.</li>
</ol>
</blockquote>
<h4>Customizing ESM specifier resolution algorithm<span><a class="mark" href="#all_esm_customizing-esm-specifier-resolution-algorithm" id="all_esm_customizing-esm-specifier-resolution-algorithm">#</a></span><a aria-hidden="true" class="legacy" id="esm_customizing_esm_specifier_resolution_algorithm"></a></h4>
<p><a href="#all_module_customization-hooks">Module customization hooks</a> provide a mechanism for customizing the ESM
specifier resolution algorithm. An example that provides CommonJS-style
resolution for ESM specifiers is <a href="https://github.com/nodejs/loaders-test/tree/main/commonjs-extension-resolution-loader">commonjs-extension-resolution-loader</a>.</p>
<!-- Note: The cjs-module-lexer link should be kept in-sync with the deps version --></section>
        </section>
<section><h2>Modules: <code>node:module</code> API<span><a class="mark" href="#all_module_modules-nodemodule-api" id="all_module_modules-nodemodule-api">#</a></span><a aria-hidden="true" class="legacy" id="module_modules_node_module_api"></a></h2>

<div class="api_metadata">
<span>Added in: v0.3.7</span>
</div>
<section><h3>The <code>Module</code> object<span><a class="mark" href="#all_module_the-module-object" id="all_module_the-module-object">#</a></span><a aria-hidden="true" class="legacy" id="module_the_module_object"></a></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>Provides general utility methods when interacting with instances of
<code>Module</code>, the <a href="#all_modules_the-module-object"><code>module</code></a> variable often seen in <a href="modules.html">CommonJS</a> modules. Accessed
via <code>import 'node:module'</code> or <code>require('node:module')</code>.</p>
<h4><code>module.builtinModules</code><span><a class="mark" href="#all_module_modulebuiltinmodules" id="all_module_modulebuiltinmodules">#</a></span><a aria-hidden="true" class="legacy" id="module_module_builtinmodules"></a></h4>
<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>Note: the list doesn't contain <a href="#all_modules_built-in-modules-with-mandatory-node-prefix">prefix-only modules</a> like <code>node:test</code>.</p>
<p><code>module</code> in this context isn't the same object that's provided
by the <a href="#all_modules_the-module-wrapper">module wrapper</a>. To access it, require the <code>Module</code> module:</p>

<pre class="with-26-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// module.mjs</span>
<span class="hljs-comment">// In an ECMAScript module</span>
<span class="hljs-keyword">import</span> { builtinModules <span class="hljs-keyword">as</span> builtin } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>;</code><code class="language-js cjs"><span class="hljs-comment">// module.cjs</span>
<span class="hljs-comment">// In a CommonJS module</span>
<span class="hljs-keyword">const</span> builtin = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>).<span class="hljs-property">builtinModules</span>;</code><button class="copy-button">copy</button></pre>
<h4><code>module.createRequire(filename)</code><span><a class="mark" href="#all_module_modulecreaterequirefilename" id="all_module_modulecreaterequirefilename">#</a></span><a aria-hidden="true" class="legacy" id="module_module_createrequire_filename"></a></h4>
<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="#all_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="#all_modules_requireid" class="type">&#x3C;require></a> Require function</li>
</ul>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { createRequire } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>;
<span class="hljs-keyword">const</span> <span class="hljs-built_in">require</span> = <span class="hljs-title function_">createRequire</span>(<span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>);

<span class="hljs-comment">// sibling-module.js is a CommonJS module.</span>
<span class="hljs-keyword">const</span> siblingModule = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./sibling-module'</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>module.isBuiltin(moduleName)</code><span><a class="mark" href="#all_module_moduleisbuiltinmodulename" id="all_module_moduleisbuiltinmodulename">#</a></span><a aria-hidden="true" class="legacy" id="module_module_isbuiltin_modulename"></a></h4>
<div class="api_metadata">
<span>Added in: v18.6.0, v16.17.0</span>
</div>
<ul>
<li><code>moduleName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> name of the module</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> returns true if the module is builtin else returns false</li>
</ul>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { isBuiltin } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>;
<span class="hljs-title function_">isBuiltin</span>(<span class="hljs-string">'node:fs'</span>); <span class="hljs-comment">// true</span>
<span class="hljs-title function_">isBuiltin</span>(<span class="hljs-string">'fs'</span>); <span class="hljs-comment">// true</span>
<span class="hljs-title function_">isBuiltin</span>(<span class="hljs-string">'wss'</span>); <span class="hljs-comment">// false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>module.register(specifier[, parentURL][, options])</code><span><a class="mark" href="#all_module_moduleregisterspecifier-parenturl-options" id="all_module_moduleregisterspecifier-parenturl-options">#</a></span><a aria-hidden="true" class="legacy" id="module_module_register_specifier_parenturl_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.8.0</td>
<td><p>Add support for WHATWG URL instances.</p></td></tr>
<tr><td>v20.6.0</td>
<td><p><span>Added in: v20.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.2 - Release candidate</div><p></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> | <a href="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></a> Customization hooks to be registered; this should be
the same string that would be passed to <code>import()</code>, except that if it is
relative, it is resolved relative to <code>parentURL</code>.</li>
<li><code>parentURL</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></a> If you want to resolve <code>specifier</code> relative to a base
URL, such as <code>import.meta.url</code>, you can pass that URL here. <strong>Default:</strong>
<code>'data:'</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>
<ul>
<li><code>parentURL</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></a> If you want to resolve <code>specifier</code> relative to a
base URL, such as <code>import.meta.url</code>, you can pass that URL here. This
property is ignored if the <code>parentURL</code> is supplied as the second argument.
<strong>Default:</strong> <code>'data:'</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> Any arbitrary, cloneable JavaScript value to pass into the
<a href="#all_module_initialize"><code>initialize</code></a> hook.</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> <a href="#all_worker_threads_portpostmessagevalue-transferlist">transferrable objects</a> to be passed into the
<code>initialize</code> hook.</li>
</ul>
</li>
</ul>
<p>Register a module that exports <a href="#all_module_customization-hooks">hooks</a> that customize Node.js module
resolution and loading behavior. See <a href="#all_module_customization-hooks">Customization hooks</a>.</p>
<h4><code>module.syncBuiltinESMExports()</code><span><a class="mark" href="#all_module_modulesyncbuiltinesmexports" id="all_module_modulesyncbuiltinesmexports">#</a></span><a aria-hidden="true" class="legacy" id="module_module_syncbuiltinesmexports"></a></h4>
<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 <a href="esm.html">ES Modules</a> to match the properties of the <a href="modules.html">CommonJS</a> exports. It
does not add or remove exported names from the <a href="esm.html">ES Modules</a>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { syncBuiltinESMExports } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>);

fs.<span class="hljs-property">readFile</span> = newAPI;

<span class="hljs-keyword">delete</span> fs.<span class="hljs-property">readFileSync</span>;

<span class="hljs-keyword">function</span> <span class="hljs-title function_">newAPI</span>(<span class="hljs-params"></span>) {
  <span class="hljs-comment">// ...</span>
}

fs.<span class="hljs-property">newAPI</span> = newAPI;

<span class="hljs-title function_">syncBuiltinESMExports</span>();

<span class="hljs-keyword">import</span>(<span class="hljs-string">'node:fs'</span>).<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">esmFS</span>) =></span> {
  <span class="hljs-comment">// It syncs the existing readFile property with the new value</span>
  assert.<span class="hljs-title function_">strictEqual</span>(esmFS.<span class="hljs-property">readFile</span>, newAPI);
  <span class="hljs-comment">// readFileSync has been deleted from the required fs</span>
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-string">'readFileSync'</span> <span class="hljs-keyword">in</span> fs, <span class="hljs-literal">false</span>);
  <span class="hljs-comment">// syncBuiltinESMExports() does not remove readFileSync from esmFS</span>
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-string">'readFileSync'</span> <span class="hljs-keyword">in</span> esmFS, <span class="hljs-literal">true</span>);
  <span class="hljs-comment">// syncBuiltinESMExports() does not add names</span>
  assert.<span class="hljs-title function_">strictEqual</span>(esmFS.<span class="hljs-property">newAPI</span>, <span class="hljs-literal">undefined</span>);
});</code> <button class="copy-button">copy</button></pre>
<p><i id="module_customization_hooks"></i></p>
</section><section><h3>Customization Hooks<span><a class="mark" href="#all_module_customization-hooks" id="all_module_customization-hooks">#</a></span><a aria-hidden="true" class="legacy" id="module_customization_hooks"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.6.0</td>
<td><p>Added <code>initialize</code> hook to replace <code>globalPreload</code>.</p></td></tr>
<tr><td>v18.6.0, v16.17.0</td>
<td><p>Add support for chaining loaders.</p></td></tr>
<tr><td>v16.12.0</td>
<td><p>Removed <code>getFormat</code>, <code>getSource</code>, <code>transformSource</code>, and <code>globalPreload</code>; added <code>load</code> hook and <code>getGlobalPreload</code> hook.</p></td></tr>
<tr><td>v8.8.0</td>
<td><p><span>Added in: v8.8.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.2 - Release candidate</div><p></p>

<p><i id="enabling_module_customization_hooks"></i></p>
<h4>Enabling<span><a class="mark" href="#all_module_enabling" id="all_module_enabling">#</a></span><a aria-hidden="true" class="legacy" id="module_enabling"></a></h4>
<p>Module resolution and loading can be customized by registering a file which
exports a set of hooks. This can be done using the <a href="#all_module_moduleregisterspecifier-parenturl-options"><code>register</code></a> method
from <code>node:module</code>, which you can run before your application code by
using the <code>--import</code> flag:</p>
<pre><code class="language-bash">node --import ./register-hooks.js ./my-app.js</code> <button class="copy-button">copy</button></pre>

<pre class="with-44-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// register-hooks.js</span>
<span class="hljs-keyword">import</span> { register } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>;

<span class="hljs-title function_">register</span>(<span class="hljs-string">'./hooks.mjs'</span>, <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>);</code><code class="language-js cjs"><span class="hljs-comment">// register-hooks.js</span>
<span class="hljs-keyword">const</span> { register } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>);
<span class="hljs-keyword">const</span> { pathToFileURL } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);

<span class="hljs-title function_">register</span>(<span class="hljs-string">'./hooks.mjs'</span>, <span class="hljs-title function_">pathToFileURL</span>(__filename));</code><button class="copy-button">copy</button></pre>
<p>The file passed to <code>--import</code> can also be an export from a dependency:</p>
<pre><code class="language-bash">node --import some-package/register ./my-app.js</code> <button class="copy-button">copy</button></pre>
<p>Where <code>some-package</code> has an <a href="#all_packages_exports"><code>"exports"</code></a> field defining the <code>/register</code>
export to map to a file that calls <code>register()</code>, like the following <code>register-hooks.js</code>
example.</p>
<p>Using <code>--import</code> ensures that the hooks are registered before any application
files are imported, including the entry point of the application. Alternatively,
<code>register</code> can be called from the entry point, but dynamic <code>import()</code> must be
used for any code that should be run after the hooks are registered:</p>

<pre class="with-46-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { register } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>;

<span class="hljs-title function_">register</span>(<span class="hljs-string">'http-to-https'</span>, <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>);

<span class="hljs-comment">// Because this is a dynamic `import()`, the `http-to-https` hooks will run</span>
<span class="hljs-comment">// to handle `./my-app.js` and any other files it imports or requires.</span>
<span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'./my-app.js'</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { register } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>);
<span class="hljs-keyword">const</span> { pathToFileURL } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);

<span class="hljs-title function_">register</span>(<span class="hljs-string">'http-to-https'</span>, <span class="hljs-title function_">pathToFileURL</span>(__filename));

<span class="hljs-comment">// Because this is a dynamic `import()`, the `http-to-https` hooks will run</span>
<span class="hljs-comment">// to handle `./my-app.js` and any other files it imports or requires.</span>
<span class="hljs-keyword">import</span>(<span class="hljs-string">'./my-app.js'</span>);</code><button class="copy-button">copy</button></pre>
<p>In this example, we are registering the <code>http-to-https</code> hooks, but they will
only be available for subsequently imported modules—in this case, <code>my-app.js</code>
and anything it references via <code>import</code> (and optionally <code>require</code>). If the
<code>import('./my-app.js')</code> had instead been a static <code>import './my-app.js'</code>, the
app would have <em>already</em> been loaded <strong>before</strong> the <code>http-to-https</code> hooks were
registered. This due to the ES modules specification, where static imports are
evaluated from the leaves of the tree first, then back to the trunk. There can
be static imports <em>within</em> <code>my-app.js</code>, which will not be evaluated until
<code>my-app.js</code> is dynamically imported.</p>
<p><code>my-app.js</code> can also be CommonJS. Customization hooks will run for any
modules that it references via <code>import</code> (and optionally <code>require</code>).</p>
<p>Finally, if all you want to do is register hooks before your app runs and you
don't want to create a separate file for that purpose, you can pass a <code>data:</code>
URL to <code>--import</code>:</p>
<pre><code class="language-bash">node --import <span class="hljs-string">'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register("http-to-https", pathToFileURL("./"));'</span> ./my-app.js</code> <button class="copy-button">copy</button></pre>
<h4>Chaining<span><a class="mark" href="#all_module_chaining" id="all_module_chaining">#</a></span><a aria-hidden="true" class="legacy" id="module_chaining"></a></h4>
<p>It's possible to call <code>register</code> more than once:</p>

<pre class="with-44-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// entrypoint.mjs</span>
<span class="hljs-keyword">import</span> { register } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>;

<span class="hljs-title function_">register</span>(<span class="hljs-string">'./foo.mjs'</span>, <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>);
<span class="hljs-title function_">register</span>(<span class="hljs-string">'./bar.mjs'</span>, <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>);
<span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'./my-app.mjs'</span>);</code><code class="language-js cjs"><span class="hljs-comment">// entrypoint.cjs</span>
<span class="hljs-keyword">const</span> { register } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>);
<span class="hljs-keyword">const</span> { pathToFileURL } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);

<span class="hljs-keyword">const</span> parentURL = <span class="hljs-title function_">pathToFileURL</span>(__filename);
<span class="hljs-title function_">register</span>(<span class="hljs-string">'./foo.mjs'</span>, parentURL);
<span class="hljs-title function_">register</span>(<span class="hljs-string">'./bar.mjs'</span>, parentURL);
<span class="hljs-keyword">import</span>(<span class="hljs-string">'./my-app.mjs'</span>);</code><button class="copy-button">copy</button></pre>
<p>In this example, the registered hooks will form chains. These chains run
last-in, first out (LIFO). If both <code>foo.mjs</code> and <code>bar.mjs</code> define a <code>resolve</code>
hook, they will be called like so (note the right-to-left):
node's default ← <code>./foo.mjs</code> ← <code>./bar.mjs</code>
(starting with <code>./bar.mjs</code>, then <code>./foo.mjs</code>, then the Node.js default).
The same applies to all the other hooks.</p>
<p>The registered hooks also affect <code>register</code> itself. In this example,
<code>bar.mjs</code> will be resolved and loaded via the hooks registered by <code>foo.mjs</code>
(because <code>foo</code>'s hooks will have already been added to the chain). This allows
for things like writing hooks in non-JavaScript languages, so long as
earlier registered hooks transpile into JavaScript.</p>
<p>The <code>register</code> method cannot be called from within the module that defines the
hooks.</p>
<h4>Communication with module customization hooks<span><a class="mark" href="#all_module_communication-with-module-customization-hooks" id="all_module_communication-with-module-customization-hooks">#</a></span><a aria-hidden="true" class="legacy" id="module_communication_with_module_customization_hooks"></a></h4>
<p>Module customization hooks run on a dedicated thread, separate from the main
thread that runs application code. This means mutating global variables won't
affect the other thread(s), and message channels must be used to communicate
between the threads.</p>
<p>The <code>register</code> method can be used to pass data to an <a href="#all_module_initialize"><code>initialize</code></a> hook. The
data passed to the hook may include transferrable objects like ports.</p>

<pre class="with-53-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { register } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">MessageChannel</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:worker_threads'</span>;

<span class="hljs-comment">// This example demonstrates how a message channel can be used to</span>
<span class="hljs-comment">// communicate with the hooks, by sending `port2` to the hooks.</span>
<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();

port1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(msg);
});
port1.<span class="hljs-title function_">unref</span>();

<span class="hljs-title function_">register</span>(<span class="hljs-string">'./my-hooks.mjs'</span>, {
  <span class="hljs-attr">parentURL</span>: <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>,
  <span class="hljs-attr">data</span>: { <span class="hljs-attr">number</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">port</span>: port2 },
  <span class="hljs-attr">transferList</span>: [port2],
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { register } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>);
<span class="hljs-keyword">const</span> { pathToFileURL } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">MessageChannel</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);

<span class="hljs-comment">// This example showcases how a message channel can be used to</span>
<span class="hljs-comment">// communicate with the hooks, by sending `port2` to the hooks.</span>
<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();

port1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(msg);
});
port1.<span class="hljs-title function_">unref</span>();

<span class="hljs-title function_">register</span>(<span class="hljs-string">'./my-hooks.mjs'</span>, {
  <span class="hljs-attr">parentURL</span>: <span class="hljs-title function_">pathToFileURL</span>(__filename),
  <span class="hljs-attr">data</span>: { <span class="hljs-attr">number</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">port</span>: port2 },
  <span class="hljs-attr">transferList</span>: [port2],
});</code><button class="copy-button">copy</button></pre>
<h4>Hooks<span><a class="mark" href="#all_module_hooks" id="all_module_hooks">#</a></span><a aria-hidden="true" class="legacy" id="module_hooks"></a></h4>
<p>The <a href="#all_module_moduleregisterspecifier-parenturl-options"><code>register</code></a> method can be used to register a module that exports a set of
hooks. The hooks are functions that are called by Node.js to customize the
module resolution and loading process. The exported functions must have specific
names and signatures, and they must be exported as named exports.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">initialize</span>(<span class="hljs-params">{ number, port }</span>) {
  <span class="hljs-comment">// Receives data from `register`.</span>
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">resolve</span>(<span class="hljs-params">specifier, context, nextResolve</span>) {
  <span class="hljs-comment">// Take an `import` or `require` specifier and resolve it to a URL.</span>
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">load</span>(<span class="hljs-params">url, context, nextLoad</span>) {
  <span class="hljs-comment">// Take a resolved URL and return the source code to be evaluated.</span>
}</code> <button class="copy-button">copy</button></pre>
<p>Hooks are part of a <a href="#all_module_chaining">chain</a>, even if that chain consists of only one
custom (user-provided) hook and the default hook, which is always present. Hook
functions nest: each one must always return a plain object, and chaining happens
as a result of each function calling <code>next&#x3C;hookName>()</code>, which is a reference to
the subsequent loader's hook (in LIFO order).</p>
<p>A hook that returns a value lacking a required property triggers an exception. A
hook that returns without calling <code>next&#x3C;hookName>()</code> <em>and</em> without returning
<code>shortCircuit: true</code> also triggers an exception. These errors are to help
prevent unintentional breaks in the chain. Return <code>shortCircuit: true</code> from a
hook to signal that the chain is intentionally ending at your hook.</p>
<p>Hooks are run in a separate thread, isolated from the main thread where
application code runs. That means it is a different <a href="https://tc39.es/ecma262/#realm">realm</a>. The hooks thread
may be terminated by the main thread at any time, so do not depend on
asynchronous operations (like <code>console.log</code>) to complete.</p>
<h5><code>initialize()</code><span><a class="mark" href="#all_module_initialize" id="all_module_initialize">#</a></span><a aria-hidden="true" class="legacy" id="module_initialize"></a></h5>
<div class="api_metadata">
<span>Added in: v20.6.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.2 - Release candidate</div><p></p>
<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> The data from <code>register(loader, import.meta.url, { data })</code>.</li>
</ul>
<p>The <code>initialize</code> hook provides a way to define a custom function that runs in
the hooks thread when the hooks module is initialized. Initialization happens
when the hooks module is registered via <a href="#all_module_moduleregisterspecifier-parenturl-options"><code>register</code></a>.</p>
<p>This hook can receive data from a <a href="#all_module_moduleregisterspecifier-parenturl-options"><code>register</code></a> invocation, including
ports and other transferrable objects. The return value of <code>initialize</code> can be a
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a>, in which case it will be awaited before the main application thread
execution resumes.</p>
<p>Module customization code:</p>
<pre><code class="language-js mjs"><span class="hljs-comment">// path-to-my-hooks.js</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">initialize</span>(<span class="hljs-params">{ number, port }</span>) {
  port.<span class="hljs-title function_">postMessage</span>(<span class="hljs-string">`increment: <span class="hljs-subst">${number + <span class="hljs-number">1</span>}</span>`</span>);
}</code> <button class="copy-button">copy</button></pre>
<p>Caller code:</p>

<pre class="with-44-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> { register } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">MessageChannel</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:worker_threads'</span>;

<span class="hljs-comment">// This example showcases how a message channel can be used to communicate</span>
<span class="hljs-comment">// between the main (application) thread and the hooks running on the hooks</span>
<span class="hljs-comment">// thread, by sending `port2` to the `initialize` hook.</span>
<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();

port1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg</span>) =></span> {
  assert.<span class="hljs-title function_">strictEqual</span>(msg, <span class="hljs-string">'increment: 2'</span>);
});
port1.<span class="hljs-title function_">unref</span>();

<span class="hljs-title function_">register</span>(<span class="hljs-string">'./path-to-my-hooks.js'</span>, {
  <span class="hljs-attr">parentURL</span>: <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>,
  <span class="hljs-attr">data</span>: { <span class="hljs-attr">number</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">port</span>: port2 },
  <span class="hljs-attr">transferList</span>: [port2],
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { register } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>);
<span class="hljs-keyword">const</span> { pathToFileURL } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">MessageChannel</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);

<span class="hljs-comment">// This example showcases how a message channel can be used to communicate</span>
<span class="hljs-comment">// between the main (application) thread and the hooks running on the hooks</span>
<span class="hljs-comment">// thread, by sending `port2` to the `initialize` hook.</span>
<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();

port1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg</span>) =></span> {
  assert.<span class="hljs-title function_">strictEqual</span>(msg, <span class="hljs-string">'increment: 2'</span>);
});
port1.<span class="hljs-title function_">unref</span>();

<span class="hljs-title function_">register</span>(<span class="hljs-string">'./path-to-my-hooks.js'</span>, {
  <span class="hljs-attr">parentURL</span>: <span class="hljs-title function_">pathToFileURL</span>(__filename),
  <span class="hljs-attr">data</span>: { <span class="hljs-attr">number</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">port</span>: port2 },
  <span class="hljs-attr">transferList</span>: [port2],
});</code><button class="copy-button">copy</button></pre>
<h5><code>resolve(specifier, context, nextResolve)</code><span><a class="mark" href="#all_module_resolvespecifier-context-nextresolve" id="all_module_resolvespecifier-context-nextresolve">#</a></span><a aria-hidden="true" class="legacy" id="module_resolve_specifier_context_nextresolve"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.10.0</td>
<td><p>The property <code>context.importAssertions</code> is replaced with <code>context.importAttributes</code>. Using the old name is still supported and will emit an experimental warning.</p></td></tr>
<tr><td>v18.6.0, v16.17.0</td>
<td><p>Add support for chaining resolve hooks. Each hook must either call <code>nextResolve()</code> or include a <code>shortCircuit</code> property set to <code>true</code> in its return.</p></td></tr>
<tr><td>v17.1.0, v16.14.0</td>
<td><p>Add support for import assertions.</p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.2 - Release candidate</div><p></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></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>
<ul>
<li><code>conditions</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> Export conditions of the relevant <code>package.json</code></li>
<li><code>importAttributes</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> An object whose key-value pairs represent the
attributes for the module to import</li>
<li><code>parentURL</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#Undefined_type" class="type">&#x3C;undefined></a> The module importing this one, or undefined
if this is the Node.js entry point</li>
</ul>
</li>
<li><code>nextResolve</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The subsequent <code>resolve</code> hook in the chain, or the
Node.js default <code>resolve</code> hook after the last user-supplied <code>resolve</code> hook
<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></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></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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a>
<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 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> A hint to the load hook (it might be
ignored)
<code>'builtin' | 'commonjs' | 'json' | 'module' | 'wasm'</code></li>
<li><code>importAttributes</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#Undefined_type" class="type">&#x3C;undefined></a> The import attributes to use when
caching the module (optional; if excluded the input will be used)</li>
<li><code>shortCircuit</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/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> A signal that this hook intends to
terminate the chain of <code>resolve</code> hooks. <strong>Default:</strong> <code>false</code></li>
<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 URL to which this input resolves</li>
</ul>
</li>
</ul>
<blockquote>
<p><strong>Warning</strong> Despite support for returning promises and async functions, calls
to <code>resolve</code> may block the main thread which can impact performance.</p>
</blockquote>
<p>The <code>resolve</code> hook chain is responsible for telling Node.js where to find and
how to cache a given <code>import</code> statement or expression, or <code>require</code> call. It can
optionally return a format (such as <code>'module'</code>) as a hint to the <code>load</code> hook. If
a format is specified, the <code>load</code> hook is ultimately responsible for providing
the final <code>format</code> value (and it is free to ignore the hint provided by
<code>resolve</code>); if <code>resolve</code> provides a <code>format</code>, a custom <code>load</code> hook is required
even if only to pass the value to the Node.js default <code>load</code> hook.</p>
<p>Import type attributes are part of the cache key for saving loaded modules into
the internal module cache. The <code>resolve</code> hook is responsible for returning an
<code>importAttributes</code> object if the module should be cached with different
attributes than were present in the source code.</p>
<p>The <code>conditions</code> property in <code>context</code> is an array of conditions for
<a href="#all_packages_conditional-exports">package exports conditions</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 current <a href="#all_packages_conditional-exports">package exports conditions</a> are always in
the <code>context.conditions</code> array passed into the hook. To guarantee <em>default
Node.js module specifier resolution behavior</em> when calling <code>defaultResolve</code>, the
<code>context.conditions</code> array passed to it <em>must</em> include <em>all</em> elements of the
<code>context.conditions</code> array originally passed into the <code>resolve</code> hook.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">resolve</span>(<span class="hljs-params">specifier, context, nextResolve</span>) {
  <span class="hljs-keyword">const</span> { parentURL = <span class="hljs-literal">null</span> } = context;

  <span class="hljs-keyword">if</span> (<span class="hljs-title class_">Math</span>.<span class="hljs-title function_">random</span>() > <span class="hljs-number">0.5</span>) { <span class="hljs-comment">// Some condition.</span>
    <span class="hljs-comment">// For some or all specifiers, do some custom logic for resolving.</span>
    <span class="hljs-comment">// Always return an object of the form {url: &#x3C;string>}.</span>
    <span class="hljs-keyword">return</span> {
      <span class="hljs-attr">shortCircuit</span>: <span class="hljs-literal">true</span>,
      <span class="hljs-attr">url</span>: parentURL ?
        <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(specifier, parentURL).<span class="hljs-property">href</span> :
        <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(specifier).<span class="hljs-property">href</span>,
    };
  }

  <span class="hljs-keyword">if</span> (<span class="hljs-title class_">Math</span>.<span class="hljs-title function_">random</span>() &#x3C; <span class="hljs-number">0.5</span>) { <span class="hljs-comment">// Another condition.</span>
    <span class="hljs-comment">// When calling `defaultResolve`, the arguments can be modified. In this</span>
    <span class="hljs-comment">// case it's adding another value for matching conditional exports.</span>
    <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextResolve</span>(specifier, {
      ...context,
      <span class="hljs-attr">conditions</span>: [...context.<span class="hljs-property">conditions</span>, <span class="hljs-string">'another-condition'</span>],
    });
  }

  <span class="hljs-comment">// Defer to the next hook in the chain, which would be the</span>
  <span class="hljs-comment">// Node.js default resolve if this is the last user-specified loader.</span>
  <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextResolve</span>(specifier);
}</code> <button class="copy-button">copy</button></pre>
<h5><code>load(url, context, nextLoad)</code><span><a class="mark" href="#all_module_loadurl-context-nextload" id="all_module_loadurl-context-nextload">#</a></span><a aria-hidden="true" class="legacy" id="module_load_url_context_nextload"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.6.0</td>
<td><p>Add support for <code>source</code> with format <code>commonjs</code>.</p></td></tr>
<tr><td>v18.6.0, v16.17.0</td>
<td><p>Add support for chaining load hooks. Each hook must either call <code>nextLoad()</code> or include a <code>shortCircuit</code> property set to <code>true</code> in its return.</p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.2 - Release candidate</div><p></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 URL returned by the <code>resolve</code> chain</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>
<ul>
<li><code>conditions</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> Export conditions of the relevant <code>package.json</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> | <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> The format optionally supplied by the
<code>resolve</code> hook chain</li>
<li><code>importAttributes</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
</li>
<li><code>nextLoad</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The subsequent <code>load</code> hook in the chain, or the
Node.js default <code>load</code> hook after the last user-supplied <code>load</code> hook
<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></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></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>
<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></li>
<li><code>shortCircuit</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/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> A signal that this hook intends to
terminate the chain of <code>load</code> hooks. <strong>Default:</strong> <code>false</code></li>
<li><code>source</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/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a> The source for Node.js to evaluate</li>
</ul>
</li>
</ul>
<p>The <code>load</code> hook provides a way to define a custom method of determining how a
URL should be interpreted, retrieved, and parsed. It is also in charge of
validating the import assertion.</p>
<p>The final value of <code>format</code> must 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>load</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>{ <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String"><code>string</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/TypedArray"><code>TypedArray</code></a>, <code>null</code>, <code>undefined</code> }</td></tr><tr><td><code>'json'</code></td><td>Load a JSON file</td><td>{ <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String"><code>string</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/TypedArray"><code>TypedArray</code></a> }</td></tr><tr><td><code>'module'</code></td><td>Load an ES module</td><td>{ <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String"><code>string</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/TypedArray"><code>TypedArray</code></a> }</td></tr><tr><td><code>'wasm'</code></td><td>Load a WebAssembly module</td><td>{ <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/TypedArray"><code>TypedArray</code></a> }</td></tr></tbody></table>
<p>The value of <code>source</code> is ignored for type <code>'builtin'</code> because currently it is
not possible to replace the value of a Node.js builtin (core) module.</p>
<p>Omitting vs providing a <code>source</code> for <code>'commonjs'</code> has very different effects:</p>
<ul>
<li>When a <code>source</code> is provided, all <code>require</code> calls from this module will be
processed by the ESM loader with registered <code>resolve</code> and <code>load</code> hooks; all
<code>require.resolve</code> calls from this module will be processed by the ESM loader
with registered <code>resolve</code> hooks; only a subset of the CommonJS API will be
available (e.g. no <code>require.extensions</code>, no <code>require.cache</code>, no
<code>require.resolve.paths</code>) and monkey-patching on the CommonJS module loader
will not apply.</li>
<li>If <code>source</code> is undefined or <code>null</code>, it will be handled by the CommonJS module
loader and <code>require</code>/<code>require.resolve</code> calls will not go through the
registered hooks. This behavior for nullish <code>source</code> is temporary — in the
future, nullish <code>source</code> will not be supported.</li>
</ul>
<p>When <code>node</code> is run with <code>--experimental-default-type=commonjs</code>, the Node.js
internal <code>load</code> implementation, which is the value of <code>next</code> for the
last hook in the <code>load</code> chain, returns <code>null</code> for <code>source</code> when <code>format</code> is
<code>'commonjs'</code> for backward compatibility. Here is an example hook that would
opt-in to using the non-default behavior:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { readFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">load</span>(<span class="hljs-params">url, context, nextLoad</span>) {
  <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> <span class="hljs-title function_">nextLoad</span>(url, context);
  <span class="hljs-keyword">if</span> (result.<span class="hljs-property">format</span> === <span class="hljs-string">'commonjs'</span>) {
    result.<span class="hljs-property">source</span> ??= <span class="hljs-keyword">await</span> <span class="hljs-title function_">readFile</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(result.<span class="hljs-property">responseURL</span> ?? url));
  }
  <span class="hljs-keyword">return</span> result;
}</code> <button class="copy-button">copy</button></pre>
<blockquote>
<p><strong>Warning</strong>: The ESM <code>load</code> hook and namespaced exports from CommonJS modules
are incompatible. Attempting to use them together will result in an empty
object from the import. This may be addressed in the future.</p>
</blockquote>
<blockquote>
<p>These types all correspond to classes defined in ECMAScript.</p>
</blockquote>
<ul>
<li>The specific <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a> object is a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer"><code>SharedArrayBuffer</code></a>.</li>
<li>The specific <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray"><code>TypedArray</code></a> object is a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array"><code>Uint8Array</code></a>.</li>
</ul>
<p>If the source value of a text-based format (i.e., <code>'json'</code>, <code>'module'</code>)
is not a string, it is converted to a string using <a href="#all_util_class-utiltextdecoder"><code>util.TextDecoder</code></a>.</p>
<p>The <code>load</code> hook provides a way to define a custom method for retrieving the
source code of a resolved URL. This would allow a loader to potentially avoid
reading files from disk. It could also be used to map an unrecognized format to
a supported one, for example <code>yaml</code> to <code>module</code>.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">load</span>(<span class="hljs-params">url, context, nextLoad</span>) {
  <span class="hljs-keyword">const</span> { format } = context;

  <span class="hljs-keyword">if</span> (<span class="hljs-title class_">Math</span>.<span class="hljs-title function_">random</span>() > <span class="hljs-number">0.5</span>) { <span class="hljs-comment">// Some condition</span>
    <span class="hljs-comment">/*
      For some or all URLs, do some custom logic for retrieving the source.
      Always return an object of the form {
        format: &#x3C;string>,
        source: &#x3C;string|buffer>,
      }.
    */</span>
    <span class="hljs-keyword">return</span> {
      format,
      <span class="hljs-attr">shortCircuit</span>: <span class="hljs-literal">true</span>,
      <span class="hljs-attr">source</span>: <span class="hljs-string">'...'</span>,
    };
  }

  <span class="hljs-comment">// Defer to the next hook in the chain.</span>
  <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextLoad</span>(url);
}</code> <button class="copy-button">copy</button></pre>
<p>In a more advanced scenario, this can also be used to transform an unsupported
source to a supported one (see <a href="#all_module_examples">Examples</a> below).</p>
<h5><code>globalPreload()</code><span><a class="mark" href="#all_module_globalpreload" id="all_module_globalpreload">#</a></span><a aria-hidden="true" class="legacy" id="module_globalpreload"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.6.0, v16.17.0</td>
<td><p>Add support for chaining globalPreload hooks.</p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.0 - Early development</div><p></p>
<blockquote>
<p><strong>Warning:</strong> This hook will be removed in a future version. Use
<a href="#all_module_initialize"><code>initialize</code></a> instead. When a hooks module has an <code>initialize</code> export,
<code>globalPreload</code> will be ignored.</p>
</blockquote>
<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> Information to assist the preload code
<ul>
<li><code>port</code> <a href="#all_worker_threads_class-messageport" class="type">&#x3C;MessagePort></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> Code to run before application startup</li>
</ul>
<p>Sometimes it might be necessary to run some code inside of the same global
scope that the application runs in. This hook allows the return of a string
that is run as a 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 has to construct
its own <code>require</code> using  <code>module.createRequire()</code>.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">globalPreload</span>(<span class="hljs-params">context</span>) {
  <span class="hljs-keyword">return</span> <span class="hljs-string">`\
globalThis.someInjectedProperty = 42;
console.log('I just set some globals!');

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

const require = createRequire(cwd() + '/&#x3C;preload>');
// [...]
`</span>;
}</code> <button class="copy-button">copy</button></pre>
<p>Another argument is provided to the preload code: <code>port</code>. This is available as a
parameter to the hook and inside of the source text returned by the hook. This
functionality has been moved to the <code>initialize</code> hook.</p>
<p>Care must be taken in order to properly call <a href="#all_worker_threads_portref"><code>port.ref()</code></a> and
<a href="#all_worker_threads_portunref"><code>port.unref()</code></a> to prevent a process from being in a state where it won't
close normally.</p>
<pre><code class="language-js mjs"><span class="hljs-comment">/**
 * This example has the application context send a message to the hook
 * and sends the message back to the application context
 */</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">globalPreload</span>(<span class="hljs-params">{ port }</span>) {
  port.<span class="hljs-property">onmessage</span> = <span class="hljs-function">(<span class="hljs-params">evt</span>) =></span> {
    port.<span class="hljs-title function_">postMessage</span>(evt.<span class="hljs-property">data</span>);
  };
  <span class="hljs-keyword">return</span> <span class="hljs-string">`\
    port.postMessage('console.log("I went to the hook and back");');
    port.onmessage = (evt) => {
      eval(evt.data);
    };
  `</span>;
}</code> <button class="copy-button">copy</button></pre>
<h4>Examples<span><a class="mark" href="#all_module_examples" id="all_module_examples">#</a></span><a aria-hidden="true" class="legacy" id="module_examples"></a></h4>
<p>The various module customization hooks can be used together to accomplish
wide-ranging customizations of the Node.js code loading and evaluation
behaviors.</p>
<h5>Import from HTTPS<span><a class="mark" href="#all_module_import-from-https" id="all_module_import-from-https">#</a></span><a aria-hidden="true" class="legacy" id="module_import_from_https"></a></h5>
<p>In current Node.js, specifiers starting with <code>https://</code> are experimental (see
<a href="#all_esm_https-and-http-imports">HTTPS and HTTP imports</a>).</p>
<p>The hook 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 these hooks:
performance is much slower than loading files from disk, there is no caching,
and there is no security.</p>
<pre><code class="language-js mjs"><span class="hljs-comment">// https-hooks.mjs</span>
<span class="hljs-keyword">import</span> { get } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:https'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">load</span>(<span class="hljs-params">url, context, nextLoad</span>) {
  <span class="hljs-comment">// For JavaScript to be loaded over the network, we need to fetch and</span>
  <span class="hljs-comment">// return it.</span>
  <span class="hljs-keyword">if</span> (url.<span class="hljs-title function_">startsWith</span>(<span class="hljs-string">'https://'</span>)) {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =></span> {
      <span class="hljs-title function_">get</span>(url, <span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
        <span class="hljs-keyword">let</span> data = <span class="hljs-string">''</span>;
        res.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>);
        res.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> data += chunk);
        res.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> <span class="hljs-title function_">resolve</span>({
          <span class="hljs-comment">// This example assumes all network-provided JavaScript is ES module</span>
          <span class="hljs-comment">// code.</span>
          <span class="hljs-attr">format</span>: <span class="hljs-string">'module'</span>,
          <span class="hljs-attr">shortCircuit</span>: <span class="hljs-literal">true</span>,
          <span class="hljs-attr">source</span>: data,
        }));
      }).<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> <span class="hljs-title function_">reject</span>(err));
    });
  }

  <span class="hljs-comment">// Let Node.js handle all other URLs.</span>
  <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextLoad</span>(url);
}</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-js mjs"><span class="hljs-comment">// main.mjs</span>
<span class="hljs-keyword">import</span> { <span class="hljs-variable constant_">VERSION</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'https://coffeescript.org/browser-compiler-modern/coffeescript.js'</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-variable constant_">VERSION</span>);</code> <button class="copy-button">copy</button></pre>
<p>With the preceding hooks module, running
<code>node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./https-hooks.mjs"));' ./main.mjs</code>
prints the current version of CoffeeScript per the module at the URL in
<code>main.mjs</code>.</p>
<h5>Transpilation<span><a class="mark" href="#all_module_transpilation" id="all_module_transpilation">#</a></span><a aria-hidden="true" class="legacy" id="module_transpilation"></a></h5>
<p>Sources that are in formats Node.js doesn't understand can be converted into
JavaScript using the <a href="#all_module_loadurl-context-nextload"><code>load</code> hook</a>.</p>
<p>This is less performant than transpiling source files before running Node.js;
transpiler hooks should only be used for development and testing purposes.</p>
<pre><code class="language-js mjs"><span class="hljs-comment">// coffeescript-hooks.mjs</span>
<span class="hljs-keyword">import</span> { readFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
<span class="hljs-keyword">import</span> { dirname, extname, resolve <span class="hljs-keyword">as</span> resolvePath } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:path'</span>;
<span class="hljs-keyword">import</span> { cwd } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">import</span> { fileURLToPath, pathToFileURL } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:url'</span>;
<span class="hljs-keyword">import</span> coffeescript <span class="hljs-keyword">from</span> <span class="hljs-string">'coffeescript'</span>;

<span class="hljs-keyword">const</span> extensionsRegex = <span class="hljs-regexp">/\.(coffee|litcoffee|coffee\.md)$/</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">load</span>(<span class="hljs-params">url, context, nextLoad</span>) {
  <span class="hljs-keyword">if</span> (extensionsRegex.<span class="hljs-title function_">test</span>(url)) {
    <span class="hljs-comment">// CoffeeScript files can be either CommonJS or ES modules, so we want any</span>
    <span class="hljs-comment">// CoffeeScript file to be treated by Node.js the same as a .js file at the</span>
    <span class="hljs-comment">// same location. To determine how Node.js would interpret an arbitrary .js</span>
    <span class="hljs-comment">// file, search up the file system for the nearest parent package.json file</span>
    <span class="hljs-comment">// and read its "type" field.</span>
    <span class="hljs-keyword">const</span> format = <span class="hljs-keyword">await</span> <span class="hljs-title function_">getPackageType</span>(url);

    <span class="hljs-keyword">const</span> { <span class="hljs-attr">source</span>: rawSource } = <span class="hljs-keyword">await</span> <span class="hljs-title function_">nextLoad</span>(url, { ...context, format });
    <span class="hljs-comment">// This hook converts CoffeeScript source code into JavaScript source code</span>
    <span class="hljs-comment">// for all imported CoffeeScript files.</span>
    <span class="hljs-keyword">const</span> transformedSource = coffeescript.<span class="hljs-title function_">compile</span>(rawSource.<span class="hljs-title function_">toString</span>(), url);

    <span class="hljs-keyword">return</span> {
      format,
      <span class="hljs-attr">shortCircuit</span>: <span class="hljs-literal">true</span>,
      <span class="hljs-attr">source</span>: transformedSource,
    };
  }

  <span class="hljs-comment">// Let Node.js handle all other URLs.</span>
  <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextLoad</span>(url);
}

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">getPackageType</span>(<span class="hljs-params">url</span>) {
  <span class="hljs-comment">// `url` is only a file path during the first iteration when passed the</span>
  <span class="hljs-comment">// resolved url from the load() hook</span>
  <span class="hljs-comment">// an actual file path from load() will contain a file extension as it's</span>
  <span class="hljs-comment">// required by the spec</span>
  <span class="hljs-comment">// this simple truthy check for whether `url` contains a file extension will</span>
  <span class="hljs-comment">// work for most projects but does not cover some edge-cases (such as</span>
  <span class="hljs-comment">// extensionless files or a url ending in a trailing space)</span>
  <span class="hljs-keyword">const</span> isFilePath = !!<span class="hljs-title function_">extname</span>(url);
  <span class="hljs-comment">// If it is a file path, get the directory it's in</span>
  <span class="hljs-keyword">const</span> dir = isFilePath ?
    <span class="hljs-title function_">dirname</span>(<span class="hljs-title function_">fileURLToPath</span>(url)) :
    url;
  <span class="hljs-comment">// Compose a file path to a package.json in the same directory,</span>
  <span class="hljs-comment">// which may or may not exist</span>
  <span class="hljs-keyword">const</span> packagePath = <span class="hljs-title function_">resolvePath</span>(dir, <span class="hljs-string">'package.json'</span>);
  <span class="hljs-comment">// Try to read the possibly nonexistent package.json</span>
  <span class="hljs-keyword">const</span> type = <span class="hljs-keyword">await</span> <span class="hljs-title function_">readFile</span>(packagePath, { <span class="hljs-attr">encoding</span>: <span class="hljs-string">'utf8'</span> })
    .<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">filestring</span>) =></span> <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(filestring).<span class="hljs-property">type</span>)
    .<span class="hljs-title function_">catch</span>(<span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
      <span class="hljs-keyword">if</span> (err?.<span class="hljs-property">code</span> !== <span class="hljs-string">'ENOENT'</span>) <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err);
    });
  <span class="hljs-comment">// If package.json existed and contained a `type` field with a value, voilà</span>
  <span class="hljs-keyword">if</span> (type) <span class="hljs-keyword">return</span> type;
  <span class="hljs-comment">// Otherwise, (if not at the root) continue checking the next directory up</span>
  <span class="hljs-comment">// If at the root, stop and return false</span>
  <span class="hljs-keyword">return</span> dir.<span class="hljs-property">length</span> > <span class="hljs-number">1</span> &#x26;&#x26; <span class="hljs-title function_">getPackageType</span>(<span class="hljs-title function_">resolvePath</span>(dir, <span class="hljs-string">'..'</span>));
}</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-coffee"><span class="hljs-comment"># main.coffee</span>
<span class="hljs-keyword">import</span> { scream } <span class="hljs-keyword">from</span> <span class="hljs-string">'./scream.coffee'</span>
console.log scream <span class="hljs-string">'hello, world'</span>

<span class="hljs-keyword">import</span> { version } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>
console.log <span class="hljs-string">"Brought to you by Node.js version <span class="hljs-subst">#{version}</span>"</span></code> <button class="copy-button">copy</button></pre>
<pre><code class="language-coffee"><span class="hljs-comment"># scream.coffee</span>
<span class="hljs-keyword">export</span> scream = <span class="hljs-function"><span class="hljs-params">(str)</span> -></span> str.toUpperCase()</code> <button class="copy-button">copy</button></pre>
<p>With the preceding hooks module, running
<code>node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./coffeescript-hooks.mjs"));' ./main.coffee</code>
causes <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>
<h5>Import maps<span><a class="mark" href="#all_module_import-maps" id="all_module_import-maps">#</a></span><a aria-hidden="true" class="legacy" id="module_import_maps"></a></h5>
<p>The previous two examples defined <code>load</code> hooks. This is an example of a
<code>resolve</code> hook. This hooks module reads an <code>import-map.json</code> file that defines
which specifiers to override to other URLs (this is a very simplistic
implementation of a small subset of the "import maps" specification).</p>
<pre><code class="language-js mjs"><span class="hljs-comment">// import-map-hooks.js</span>
<span class="hljs-keyword">import</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;

<span class="hljs-keyword">const</span> { imports } = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(<span class="hljs-keyword">await</span> fs.<span class="hljs-title function_">readFile</span>(<span class="hljs-string">'import-map.json'</span>));

<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">resolve</span>(<span class="hljs-params">specifier, context, nextResolve</span>) {
  <span class="hljs-keyword">if</span> (<span class="hljs-title class_">Object</span>.<span class="hljs-title function_">hasOwn</span>(imports, specifier)) {
    <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextResolve</span>(imports[specifier], context);
  }

  <span class="hljs-keyword">return</span> <span class="hljs-title function_">nextResolve</span>(specifier, context);
}</code> <button class="copy-button">copy</button></pre>
<p>With these files:</p>
<pre><code class="language-js mjs"><span class="hljs-comment">// main.js</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'a-module'</span>;</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-json"><span class="hljs-comment">// import-map.json</span>
<span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"imports"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"a-module"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./some-module.js"</span>
  <span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<pre><code class="language-js mjs"><span class="hljs-comment">// some-module.js</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'some module!'</span>);</code> <button class="copy-button">copy</button></pre>
<p>Running <code>node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./import-map-hooks.js"));' main.js</code>
should print <code>some module!</code>.</p>
</section><section><h3>Source map v3 support<span><a class="mark" href="#all_module_source-map-v3-support" id="all_module_source-map-v3-support">#</a></span><a aria-hidden="true" class="legacy" id="module_source_map_v3_support"></a></h3>
<div class="api_metadata">
<span>Added in: v13.7.0, v12.17.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_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="#all_cli_--enable-source-maps"><code>--enable-source-maps</code></a>, or with code coverage enabled by setting
<a href="#all_cli_node_v8_coveragedir"><code>NODE_V8_COVERAGE=dir</code></a>.</p>

<pre class="with-26-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// module.mjs</span>
<span class="hljs-comment">// In an ECMAScript module</span>
<span class="hljs-keyword">import</span> { findSourceMap, <span class="hljs-title class_">SourceMap</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:module'</span>;</code><code class="language-js cjs"><span class="hljs-comment">// module.cjs</span>
<span class="hljs-comment">// In a CommonJS module</span>
<span class="hljs-keyword">const</span> { findSourceMap, <span class="hljs-title class_">SourceMap</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>);</code><button class="copy-button">copy</button></pre>
<!-- Anchors to make sure old links find a target -->
<p><a id="module_module_findsourcemap_path_error"></a></p>
<h4><code>module.findSourceMap(path)</code><span><a class="mark" href="#all_module_modulefindsourcemappath" id="all_module_modulefindsourcemappath">#</a></span><a aria-hidden="true" class="legacy" id="module_module_findsourcemap_path"></a></h4>
<div class="api_metadata">
<span>Added in: v13.7.0, 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>Returns: <a href="#all_module_class-modulesourcemap" class="type">&#x3C;module.SourceMap></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> Returns <code>module.SourceMap</code> if a source
map is found, <code>undefined</code> otherwise.</li>
</ul>
<p><code>path</code> is the resolved path for the file for which a corresponding source map
should be fetched.</p>
<h4>Class: <code>module.SourceMap</code><span><a class="mark" href="#all_module_class-modulesourcemap" id="all_module_class-modulesourcemap">#</a></span><a aria-hidden="true" class="legacy" id="module_class_module_sourcemap"></a></h4>
<div class="api_metadata">
<span>Added in: v13.7.0, v12.17.0</span>
</div>
<h5><code>new SourceMap(payload[, { lineLengths }])</code><span><a class="mark" href="#all_module_new-sourcemappayload--linelengths-" id="all_module_new-sourcemappayload--linelengths-">#</a></span><a aria-hidden="true" class="legacy" id="module_new_sourcemap_payload_linelengths"></a></h5>
<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>
<li><code>lineLengths</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number[]></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>
<p><code>lineLengths</code> is an optional array of the length of each line in the
generated code.</p>
<h5><code>sourceMap.payload</code><span><a class="mark" href="#all_module_sourcemappayload" id="all_module_sourcemappayload">#</a></span><a aria-hidden="true" class="legacy" id="module_sourcemap_payload"></a></h5>
<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="#all_module_class-modulesourcemap"><code>SourceMap</code></a> instance.</p>
<h5><code>sourceMap.findEntry(lineOffset, columnOffset)</code><span><a class="mark" href="#all_module_sourcemapfindentrylineoffset-columnoffset" id="all_module_sourcemapfindentrylineoffset-columnoffset">#</a></span><a aria-hidden="true" class="legacy" id="module_sourcemap_findentry_lineoffset_columnoffset"></a></h5>
<ul>
<li><code>lineOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The zero-indexed line number offset in
the generated source</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> The zero-indexed column number offset
in the generated source</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 offset and column offset in the generated source
file, returns an object representing the SourceMap range in the
original file if found, or an empty object if not.</p>
<p>The object returned contains 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> The line offset of the start of the
range in the generated source</li>
<li>generatedColumn: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The column offset of start of the
range in the generated source</li>
<li>originalSource: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The file name of the original source,
as reported in the SourceMap</li>
<li>originalLine: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The line offset of the start of the
range in the original source</li>
<li>originalColumn: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The column offset of start of the
range in the original source</li>
<li>name: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<p>The returned value represents the raw range as it appears in the
SourceMap, based on zero-indexed offsets, <em>not</em> 1-indexed line and
column numbers as they appear in Error messages and CallSite
objects.</p>
<p>To get the corresponding 1-indexed line and column numbers from a
lineNumber and columnNumber as they are reported by Error stacks
and CallSite objects, use <code>sourceMap.findOrigin(lineNumber, columnNumber)</code></p>
<h5><code>sourceMap.findOrigin(lineNumber, columnNumber)</code><span><a class="mark" href="#all_module_sourcemapfindoriginlinenumber-columnnumber" id="all_module_sourcemapfindoriginlinenumber-columnnumber">#</a></span><a aria-hidden="true" class="legacy" id="module_sourcemap_findorigin_linenumber_columnnumber"></a></h5>
<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> The 1-indexed line number of the call
site in the generated source</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> The 1-indexed column number
of the call site in the generated source</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 1-indexed <code>lineNumber</code> and <code>columnNumber</code> from a call site in
the generated source, find the corresponding call site location
in the original source.</p>
<p>If the <code>lineNumber</code> and <code>columnNumber</code> provided are not found in any
source map, then an empty object is returned. Otherwise, the
returned object contains the following keys:</p>
<ul>
<li>name: <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> The name of the range in the
source map, if one was provided</li>
<li>fileName: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The file name of the original source, as
reported in the SourceMap</li>
<li>lineNumber: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The 1-indexed lineNumber of the
corresponding call site in the original source</li>
<li>columnNumber: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The 1-indexed columnNumber of the
corresponding call site in the original source</li>
</ul></section>
        </section>
<section><h2>Modules: Packages<span><a class="mark" href="#all_packages_modules-packages" id="all_packages_modules-packages">#</a></span><a aria-hidden="true" class="legacy" id="packages_modules_packages"></a></h2>


<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.13.0, v12.20.0</td>
<td><p>Add support for <code>"exports"</code> patterns.</p></td></tr>
<tr><td>v14.6.0, v12.19.0</td>
<td><p>Add package <code>"imports"</code> field.</p></td></tr>
<tr><td>v13.7.0, v12.17.0</td>
<td><p>Unflag conditional exports.</p></td></tr>
<tr><td>v13.7.0, v12.16.0</td>
<td><p>Remove the <code>--experimental-conditional-exports</code> option. In 12.16.0, conditional exports are still behind <code>--experimental-modules</code>.</p></td></tr>
<tr><td>v13.6.0, v12.16.0</td>
<td><p>Unflag self-referencing a package using its name.</p></td></tr>
<tr><td>v12.7.0</td>
<td><p>Introduce <code>"exports"</code> <code>package.json</code> field as a more powerful alternative to the classic <code>"main"</code> field.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p>Add support for ES modules using <code>.js</code> file extension via <code>package.json</code> <code>"type"</code> field.</p></td></tr>
</tbody></table>
</details>
</div>
<section><h3>Introduction<span><a class="mark" href="#all_packages_introduction" id="all_packages_introduction">#</a></span><a aria-hidden="true" class="legacy" id="packages_introduction"></a></h3>
<p>A package is a folder tree described by a <code>package.json</code> file. The package
consists of the folder containing the <code>package.json</code> file and all subfolders
until the next folder containing another <code>package.json</code> file, or a folder
named <code>node_modules</code>.</p>
<p>This page provides guidance for package authors writing <code>package.json</code> files
along with a reference for the <a href="#all_packages_nodejs-packagejson-field-definitions"><code>package.json</code></a> fields defined by Node.js.</p>
</section><section><h3>Determining module system<span><a class="mark" href="#all_packages_determining-module-system" id="all_packages_determining-module-system">#</a></span><a aria-hidden="true" class="legacy" id="packages_determining_module_system"></a></h3>
<h4>Introduction<span><a class="mark" href="#all_packages_introduction_1" id="all_packages_introduction_1">#</a></span><a aria-hidden="true" class="legacy" id="packages_introduction_1"></a></h4>
<p>Node.js will treat the following as <a href="esm.html">ES modules</a> when passed to <code>node</code> as the
initial input, or when referenced by <code>import</code> statements or <code>import()</code>
expressions:</p>
<ul>
<li>
<p>Files with an <code>.mjs</code> extension.</p>
</li>
<li>
<p>Files with a <code>.js</code> extension when the nearest parent <code>package.json</code> file
contains a top-level <a href="#all_packages_type"><code>"type"</code></a> field with a value of <code>"module"</code>.</p>
</li>
<li>
<p>Strings passed in as an argument to <code>--eval</code>, or piped to <code>node</code> via <code>STDIN</code>,
with the flag <code>--input-type=module</code>.</p>
</li>
<li>
<p>When using <a href="#all_cli_--experimental-detect-module"><code>--experimental-detect-module</code></a>, code containing syntax only
successfully parsed as <a href="esm.html">ES modules</a>, such as <code>import</code> or <code>export</code>
statements or <code>import.meta</code>, having no explicit marker of how it should be
interpreted. Explicit markers are <code>.mjs</code> or <code>.cjs</code> extensions, <code>package.json</code>
<code>"type"</code> fields with either <code>"module"</code> or <code>"commonjs"</code> values, or
<code>--input-type</code> or <code>--experimental-default-type</code> flags. Dynamic <code>import()</code>
expressions are supported in either CommonJS or ES modules and would not
cause a file to be treated as an ES module.</p>
</li>
</ul>
<p>Node.js will treat the following as <a href="modules.html">CommonJS</a> when passed to <code>node</code> as the
initial input, or when referenced by <code>import</code> statements or <code>import()</code>
expressions:</p>
<ul>
<li>
<p>Files with a <code>.cjs</code> extension.</p>
</li>
<li>
<p>Files with a <code>.js</code> extension when the nearest parent <code>package.json</code> file
contains a top-level field <a href="#all_packages_type"><code>"type"</code></a> 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>
<p>Aside from these explicit cases, there are other cases where Node.js defaults to
one module system or the other based on the value of the
<a href="#all_cli_--experimental-default-typetype"><code>--experimental-default-type</code></a> flag:</p>
<ul>
<li>
<p>Files ending in <code>.js</code> or with no extension, if there is no <code>package.json</code> file
present in the same folder or any parent folder.</p>
</li>
<li>
<p>Files ending in <code>.js</code> or with no extension, if the nearest parent
<code>package.json</code> field lacks a <code>"type"</code> field; unless the folder is inside a
<code>node_modules</code> folder. (Package scopes under <code>node_modules</code> are always treated
as CommonJS when the <code>package.json</code> file lacks a <code>"type"</code> field, regardless
of <code>--experimental-default-type</code>, for backward compatibility.)</p>
</li>
<li>
<p>Strings passed in as an argument to <code>--eval</code> or piped to <code>node</code> via <code>STDIN</code>,
when <code>--input-type</code> is unspecified.</p>
</li>
</ul>
<p>This flag currently defaults to <code>"commonjs"</code>, but it may change in the future to
default to <code>"module"</code>. For this reason it is best to be explicit wherever
possible; in particular, package authors should always include the <a href="#all_packages_type"><code>"type"</code></a>
field in their <code>package.json</code> files, 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>
<h4>Modules loaders<span><a class="mark" href="#all_packages_modules-loaders" id="all_packages_modules-loaders">#</a></span><a aria-hidden="true" class="legacy" id="packages_modules_loaders"></a></h4>
<p>Node.js has two systems for resolving a specifier and loading modules.</p>
<p>There is the CommonJS module loader:</p>
<ul>
<li>It is fully synchronous.</li>
<li>It is responsible for handling <code>require()</code> calls.</li>
<li>It is monkey patchable.</li>
<li>It supports <a href="#all_modules_folders-as-modules">folders as modules</a>.</li>
<li>When resolving a specifier, if no exact match is found, it will try to add
extensions (<code>.js</code>, <code>.json</code>, and finally <code>.node</code>) and then attempt to resolve
<a href="#all_modules_folders-as-modules">folders as modules</a>.</li>
<li>It treats <code>.json</code> as JSON text files.</li>
<li><code>.node</code> files are interpreted as compiled addon modules loaded with
<code>process.dlopen()</code>.</li>
<li>It treats all files that lack <code>.json</code> or <code>.node</code> extensions as JavaScript
text files.</li>
<li>It can only be used to <a href="#all_modules_loading-ecmascript-modules-using-require">load ECMASCript modules from CommonJS modules</a> if
the module graph is synchronous (that contains no top-level <code>await</code>) when
<code>--experimental-require-module</code> is enabled.
When used to load a JavaScript text file that is not an ECMAScript module,
the file will be loaded as a CommonJS module.</li>
</ul>
<p>There is the ECMAScript module loader:</p>
<ul>
<li>It is asynchronous, unless it's being used to load modules for <code>require()</code>.</li>
<li>It is responsible for handling <code>import</code> statements and <code>import()</code> expressions.</li>
<li>It is not monkey patchable, can be customized using <a href="#all_esm_loaders">loader hooks</a>.</li>
<li>It does not support folders as modules, directory indexes (e.g.
<code>'./startup/index.js'</code>) must be fully specified.</li>
<li>It does no extension searching. A file extension must be provided
when the specifier is a relative or absolute file URL.</li>
<li>It can load JSON modules, but an import assertion is required.</li>
<li>It accepts only <code>.js</code>, <code>.mjs</code>, and <code>.cjs</code> extensions for JavaScript text
files.</li>
<li>It can be used to load JavaScript CommonJS modules. Such modules
are passed through the <code>cjs-module-lexer</code> to try to identify named exports,
which are available if they can be determined through static analysis.
Imported CommonJS modules have their URLs converted to absolute
paths and are then loaded via the CommonJS module loader.</li>
</ul>
<h4><code>package.json</code> and file extensions<span><a class="mark" href="#all_packages_packagejson-and-file-extensions" id="all_packages_packagejson-and-file-extensions">#</a></span><a aria-hidden="true" class="legacy" id="packages_package_json_and_file_extensions"></a></h4>
<p>Within a package, the <a href="#all_packages_nodejs-packagejson-field-definitions"><code>package.json</code></a> <a href="#all_packages_type"><code>"type"</code></a> field defines how
Node.js should interpret <code>.js</code> files. If a <code>package.json</code> file does not have a
<code>"type"</code> field, <code>.js</code> files are treated as <a href="modules.html">CommonJS</a>.</p>
<p>A <code>package.json</code> <code>"type"</code> value of <code>"module"</code> tells Node.js to interpret <code>.js</code>
files within that package as using <a href="esm.html">ES module</a> syntax.</p>
<p>The <code>"type"</code> field 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"><span class="hljs-comment">// my-app.js, treated as an ES module because there is a package.json</span>
<span class="hljs-comment">// file in the same folder with "type": "module".</span>

<span class="hljs-keyword">import</span> <span class="hljs-string">'./startup/init.js'</span>;
<span class="hljs-comment">// Loaded as ES module since ./startup contains no package.json file,</span>
<span class="hljs-comment">// and therefore inherits the "type" value from one level up.</span>

<span class="hljs-keyword">import</span> <span class="hljs-string">'commonjs-package'</span>;
<span class="hljs-comment">// Loaded as CommonJS since ./node_modules/commonjs-package/package.json</span>
<span class="hljs-comment">// lacks a "type" field or contains "type": "commonjs".</span>

<span class="hljs-keyword">import</span> <span class="hljs-string">'./node_modules/commonjs-package/index.js'</span>;
<span class="hljs-comment">// Loaded as CommonJS since ./node_modules/commonjs-package/package.json</span>
<span class="hljs-comment">// lacks a "type" field or contains "type": "commonjs".</span></code> <button class="copy-button">copy</button></pre>
<p>Files ending with <code>.mjs</code> are always loaded as <a href="esm.html">ES modules</a> regardless of
the nearest parent <code>package.json</code>.</p>
<p>Files ending with <code>.cjs</code> are always loaded as <a href="modules.html">CommonJS</a> regardless of the
nearest parent <code>package.json</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">import</span> <span class="hljs-string">'./legacy-file.cjs'</span>;
<span class="hljs-comment">// Loaded as CommonJS since .cjs is always loaded as CommonJS.</span>

<span class="hljs-keyword">import</span> <span class="hljs-string">'commonjs-package/src/index.mjs'</span>;
<span class="hljs-comment">// Loaded as ES module since .mjs is always loaded as ES module.</span></code> <button class="copy-button">copy</button></pre>
<p>The <code>.mjs</code> and <code>.cjs</code> extensions can be used to mix types within the same
package:</p>
<ul>
<li>
<p>Within a <code>"type": "module"</code> package, Node.js can be instructed to
interpret a particular file as <a href="modules.html">CommonJS</a> 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).</p>
</li>
<li>
<p>Within a <code>"type": "commonjs"</code> package, Node.js can be instructed to
interpret a particular file as an <a href="esm.html">ES module</a> 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).</p>
</li>
</ul>
<h4><code>--input-type</code> flag<span><a class="mark" href="#all_packages_--input-type-flag" id="all_packages_--input-type-flag">#</a></span><a aria-hidden="true" class="legacy" id="packages_input_type_flag"></a></h4>
<div class="api_metadata">
<span>Added in: v12.0.0</span>
</div>
<p>Strings passed in as an argument to <code>--eval</code> (or <code>-e</code>), or piped to <code>node</code> via
<code>STDIN</code>, are treated as <a href="esm.html">ES modules</a> when the <code>--input-type=module</code> flag
is set.</p>
<pre><code class="language-bash">node --input-type=module --<span class="hljs-built_in">eval</span> <span class="hljs-string">"import { sep } from 'node:path'; console.log(sep);"</span>

<span class="hljs-built_in">echo</span> <span class="hljs-string">"import { sep } from 'node:path'; console.log(sep);"</span> | node --input-type=module</code> <button class="copy-button">copy</button></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>
</section><section><h3>Determining package manager<span><a class="mark" href="#all_packages_determining-package-manager" id="all_packages_determining-package-manager">#</a></span><a aria-hidden="true" class="legacy" id="packages_determining_package_manager"></a></h3>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>While all Node.js projects are expected to be installable by all package
managers once published, their development teams are often required to use one
specific package manager. To make this process easier, Node.js ships with a
tool called <a href="corepack.html">Corepack</a> that aims to make all package managers transparently
available in your environment - provided you have Node.js installed.</p>
<p>By default Corepack won't enforce any specific package manager and will use
the generic "Last Known Good" versions associated with each Node.js release,
but you can improve this experience by setting the <a href="#all_packages_packagemanager"><code>"packageManager"</code></a> field
in your project's <code>package.json</code>.</p>
</section><section><h3>Package entry points<span><a class="mark" href="#all_packages_package-entry-points" id="all_packages_package-entry-points">#</a></span><a aria-hidden="true" class="legacy" id="packages_package_entry_points"></a></h3>
<p>In a package's <code>package.json</code> file, two fields can define entry points for a
package: <a href="#all_packages_main"><code>"main"</code></a> and <a href="#all_packages_exports"><code>"exports"</code></a>. Both fields apply to both ES module
and CommonJS module entry points.</p>
<p>The <a href="#all_packages_main"><code>"main"</code></a> 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 <a href="#all_packages_exports"><code>"exports"</code></a> provides a modern alternative to <a href="#all_packages_main"><code>"main"</code></a> allowing
multiple entry points to be defined, conditional entry resolution support
between environments, and <strong>preventing any other entry points besides those
defined in <a href="#all_packages_exports"><code>"exports"</code></a></strong>. This encapsulation allows module authors to
clearly define the public interface for their package.</p>
<p>For new packages targeting the currently supported versions of Node.js, the
<a href="#all_packages_exports"><code>"exports"</code></a> field is recommended. For packages supporting Node.js 10 and
below, the <a href="#all_packages_main"><code>"main"</code></a> field is required. If both <a href="#all_packages_exports"><code>"exports"</code></a> and
<a href="#all_packages_main"><code>"main"</code></a> are defined, the <a href="#all_packages_exports"><code>"exports"</code></a> field takes precedence over
<a href="#all_packages_main"><code>"main"</code></a> in supported versions of Node.js.</p>
<p><a href="#all_packages_conditional-exports">Conditional exports</a> can be used within <a href="#all_packages_exports"><code>"exports"</code></a> 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="#all_packages_dual-commonjses-module-packages">the dual CommonJS/ES module packages section</a>.</p>
<p>Existing packages introducing the <a href="#all_packages_exports"><code>"exports"</code></a> field will prevent consumers
of the package from using any entry points that are not defined, including the
<a href="#all_packages_nodejs-packagejson-field-definitions"><code>package.json</code></a> (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 <a href="#all_packages_exports"><code>"exports"</code></a> 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 previously 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"><span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"my-package"</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"exports"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"."</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./lib/index.js"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"./lib"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./lib/index.js"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"./lib/index"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./lib/index.js"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"./lib/index.js"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./lib/index.js"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"./feature"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./feature/index.js"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"./feature/index"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./feature/index.js"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"./feature/index.js"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./feature/index.js"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"./package.json"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./package.json"</span>
  <span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>Alternatively a project could choose to export entire folders both with and
without extensioned subpaths using export patterns:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"my-package"</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"exports"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"."</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./lib/index.js"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"./lib"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./lib/index.js"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"./lib/*"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./lib/*.js"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"./lib/*.js"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./lib/*.js"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"./feature"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./feature/index.js"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"./feature/*"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./feature/*.js"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"./feature/*.js"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./feature/*.js"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"./package.json"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./package.json"</span>
  <span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>With the above providing backwards-compatibility for any minor package versions,
a future major change for the package can then properly restrict the exports
to only the specific feature exports exposed:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"my-package"</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"exports"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"."</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./lib/index.js"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"./feature/*.js"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./feature/*.js"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"./feature/internal/*"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">null</span></span>
  <span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<h4>Main entry point export<span><a class="mark" href="#all_packages_main-entry-point-export" id="all_packages_main-entry-point-export">#</a></span><a aria-hidden="true" class="legacy" id="packages_main_entry_point_export"></a></h4>
<p>When writing a new package, it is recommended to use the <a href="#all_packages_exports"><code>"exports"</code></a> field:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"exports"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./index.js"</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>When the <a href="#all_packages_exports"><code>"exports"</code></a> field is defined, all subpaths of the package are
encapsulated and no longer available to importers. For example,
<code>require('pkg/subpath.js')</code> throws an <a href="#all_errors_err_package_path_not_exported"><code>ERR_PACKAGE_PATH_NOT_EXPORTED</code></a>
error.</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>
<p>All currently supported versions of Node.js and modern build tools support the
<code>"exports"</code> field. For projects using an older version of Node.js or a related
build tool, compatibility can be achieved by including the <code>"main"</code> field
alongside <code>"exports"</code> pointing to the same module:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"main"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./index.js"</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"exports"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./index.js"</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<h4>Subpath exports<span><a class="mark" href="#all_packages_subpath-exports" id="all_packages_subpath-exports">#</a></span><a aria-hidden="true" class="legacy" id="packages_subpath_exports"></a></h4>
<div class="api_metadata">
<span>Added in: v12.7.0</span>
</div>
<p>When using the <a href="#all_packages_exports"><code>"exports"</code></a> field, custom subpaths can be defined along
with the main entry point by treating the main entry point as the
<code>"."</code> subpath:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"exports"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"."</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./index.js"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"./submodule.js"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./src/submodule.js"</span>
  <span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>Now only the defined subpath in <a href="#all_packages_exports"><code>"exports"</code></a> can be imported by a consumer:</p>
<pre><code class="language-js"><span class="hljs-keyword">import</span> submodule <span class="hljs-keyword">from</span> <span class="hljs-string">'es-module-package/submodule.js'</span>;
<span class="hljs-comment">// Loads ./node_modules/es-module-package/src/submodule.js</span></code> <button class="copy-button">copy</button></pre>
<p>While other subpaths will error:</p>
<pre><code class="language-js"><span class="hljs-keyword">import</span> submodule <span class="hljs-keyword">from</span> <span class="hljs-string">'es-module-package/private-module.js'</span>;
<span class="hljs-comment">// Throws ERR_PACKAGE_PATH_NOT_EXPORTED</span></code> <button class="copy-button">copy</button></pre>
<h5>Extensions in subpaths<span><a class="mark" href="#all_packages_extensions-in-subpaths" id="all_packages_extensions-in-subpaths">#</a></span><a aria-hidden="true" class="legacy" id="packages_extensions_in_subpaths"></a></h5>
<p>Package authors should provide either extensioned (<code>import 'pkg/subpath.js'</code>) or
extensionless (<code>import 'pkg/subpath'</code>) subpaths in their exports. This ensures
that there is only one subpath for each exported module so that all dependents
import the same consistent specifier, keeping the package contract clear for
consumers and simplifying package subpath completions.</p>
<p>Traditionally, packages tended to use the extensionless style, which has the
benefits of readability and of masking the true path of the file within the
package.</p>
<p>With <a href="https://github.com/WICG/import-maps">import maps</a> now providing a standard for package resolution in browsers
and other JavaScript runtimes, using the extensionless style can result in
bloated import map definitions. Explicit file extensions can avoid this issue by
enabling the import map to utilize a <a href="https://github.com/WICG/import-maps#packages-via-trailing-slashes">packages folder mapping</a> to map multiple
subpaths where possible instead of a separate map entry per package subpath
export. This also mirrors the requirement of using <a href="#all_esm_mandatory-file-extensions">the full specifier path</a>
in relative and absolute import specifiers.</p>
<h4>Exports sugar<span><a class="mark" href="#all_packages_exports-sugar" id="all_packages_exports-sugar">#</a></span><a aria-hidden="true" class="legacy" id="packages_exports_sugar"></a></h4>
<div class="api_metadata">
<span>Added in: v12.11.0</span>
</div>
<p>If the <code>"."</code> export is the only export, the <a href="#all_packages_exports"><code>"exports"</code></a> field provides sugar
for this case being the direct <a href="#all_packages_exports"><code>"exports"</code></a> field value.</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"exports"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"."</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./index.js"</span>
  <span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>can be written:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"exports"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./index.js"</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<h4>Subpath imports<span><a class="mark" href="#all_packages_subpath-imports" id="all_packages_subpath-imports">#</a></span><a aria-hidden="true" class="legacy" id="packages_subpath_imports"></a></h4>
<div class="api_metadata">
<span>Added in: v14.6.0, v12.19.0</span>
</div>
<p>In addition to the <a href="#all_packages_exports"><code>"exports"</code></a> field, there is a package <code>"imports"</code> field
to create private mappings that only apply to import specifiers from within the
package itself.</p>
<p>Entries in the <code>"imports"</code> field must always start with <code>#</code> to ensure they are
disambiguated from external package specifiers.</p>
<p>For example, the imports field can be used to gain the benefits of conditional
exports for internal modules:</p>
<pre><code class="language-json"><span class="hljs-comment">// package.json</span>
<span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"imports"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"#dep"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"node"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"dep-node-native"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"default"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./dep-polyfill.js"</span>
    <span class="hljs-punctuation">}</span>
  <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"dependencies"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"dep-node-native"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"^1.0.0"</span>
  <span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>where <code>import '#dep'</code> does not get the resolution of the external package
<code>dep-node-native</code> (including its exports in turn), and instead gets the local
file <code>./dep-polyfill.js</code> relative to the package in other environments.</p>
<p>Unlike the <code>"exports"</code> field, the <code>"imports"</code> field permits mapping to external
packages.</p>
<p>The resolution rules for the imports field are otherwise analogous to the
exports field.</p>
<h4>Subpath patterns<span><a class="mark" href="#all_packages_subpath-patterns" id="all_packages_subpath-patterns">#</a></span><a aria-hidden="true" class="legacy" id="packages_subpath_patterns"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.10.0, v14.19.0</td>
<td><p>Support pattern trailers in "imports" field.</p></td></tr>
<tr><td>v16.9.0, v14.19.0</td>
<td><p>Support pattern trailers.</p></td></tr>
<tr><td>v14.13.0, v12.20.0</td>
<td><p><span>Added in: v14.13.0, v12.20.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>For packages with a small number of exports or imports, we recommend
explicitly listing each exports subpath entry. But for packages that have
large numbers of subpaths, this might cause <code>package.json</code> bloat and
maintenance issues.</p>
<p>For these use cases, subpath export patterns can be used instead:</p>
<pre><code class="language-json"><span class="hljs-comment">// ./node_modules/es-module-package/package.json</span>
<span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"exports"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"./features/*.js"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./src/features/*.js"</span>
  <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"imports"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"#internal/*.js"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./src/internal/*.js"</span>
  <span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p><strong><code>*</code> maps expose nested subpaths as it is a string replacement syntax
only.</strong></p>
<p>All instances of <code>*</code> on the right hand side will then be replaced with this
value, including if it contains any <code>/</code> separators.</p>
<pre><code class="language-js"><span class="hljs-keyword">import</span> featureX <span class="hljs-keyword">from</span> <span class="hljs-string">'es-module-package/features/x.js'</span>;
<span class="hljs-comment">// Loads ./node_modules/es-module-package/src/features/x.js</span>

<span class="hljs-keyword">import</span> featureY <span class="hljs-keyword">from</span> <span class="hljs-string">'es-module-package/features/y/y.js'</span>;
<span class="hljs-comment">// Loads ./node_modules/es-module-package/src/features/y/y.js</span>

<span class="hljs-keyword">import</span> internalZ <span class="hljs-keyword">from</span> <span class="hljs-string">'#internal/z.js'</span>;
<span class="hljs-comment">// Loads ./node_modules/es-module-package/src/internal/z.js</span></code> <button class="copy-button">copy</button></pre>
<p>This is a direct static matching and replacement without any special handling
for file extensions. Including the <code>"*.js"</code> on both sides of the mapping
restricts the exposed package exports to only JS files.</p>
<p>The property of exports being statically enumerable is maintained with exports
patterns since the individual exports for a package can be determined by
treating the right hand side target pattern as a <code>**</code> glob against the list of
files within the package. Because <code>node_modules</code> paths are forbidden in exports
targets, this expansion is dependent on only the files of the package itself.</p>
<p>To exclude private subfolders from patterns, <code>null</code> targets can be used:</p>
<pre><code class="language-json"><span class="hljs-comment">// ./node_modules/es-module-package/package.json</span>
<span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"exports"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"./features/*.js"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./src/features/*.js"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"./features/private-internal/*"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">null</span></span>
  <span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<pre><code class="language-js"><span class="hljs-keyword">import</span> featureInternal <span class="hljs-keyword">from</span> <span class="hljs-string">'es-module-package/features/private-internal/m.js'</span>;
<span class="hljs-comment">// Throws: ERR_PACKAGE_PATH_NOT_EXPORTED</span>

<span class="hljs-keyword">import</span> featureX <span class="hljs-keyword">from</span> <span class="hljs-string">'es-module-package/features/x.js'</span>;
<span class="hljs-comment">// Loads ./node_modules/es-module-package/src/features/x.js</span></code> <button class="copy-button">copy</button></pre>
<h4>Conditional exports<span><a class="mark" href="#all_packages_conditional-exports" id="all_packages_conditional-exports">#</a></span><a aria-hidden="true" class="legacy" id="packages_conditional_exports"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.7.0, v12.16.0</td>
<td><p>Unflag conditional exports.</p></td></tr>
<tr><td>v13.2.0, v12.16.0</td>
<td><p><span>Added in: v13.2.0, v12.16.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<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>
<pre><code class="language-json"><span class="hljs-comment">// package.json</span>
<span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"exports"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"import"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./index-module.js"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"require"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./index-require.cjs"</span>
  <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"type"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"module"</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>Node.js implements the following conditions, listed in order from most
specific to least specific as conditions should be defined:</p>
<ul>
<li><code>"node-addons"</code> - similar to <code>"node"</code> and matches for any Node.js environment.
This condition can be used to provide an entry point which uses native C++
addons as opposed to an entry point which is more universal and doesn't rely
on native addons. This condition can be disabled via the
<a href="#all_cli_--no-addons"><code>--no-addons</code> flag</a>.</li>
<li><code>"node"</code> - matches for any Node.js environment. Can be a CommonJS or ES
module file. <em>In most cases explicitly calling out the Node.js platform is
not necessary.</em></li>
<li><code>"import"</code> - matches when the package is loaded via <code>import</code> or
<code>import()</code>, or via any top-level import or resolve operation by the
ECMAScript module loader. Applies regardless of the module format of the
target file. <em>Always mutually exclusive with <code>"require"</code>.</em></li>
<li><code>"require"</code> - matches when the package is loaded via <code>require()</code>. The
referenced file should be loadable with <code>require()</code> although the condition
matches regardless of the module format of the target file. Expected
formats include CommonJS, JSON, native addons, and ES modules
if <code>--experimental-require-module</code> is enabled. <em>Always mutually
exclusive with <code>"import"</code>.</em></li>
<li><code>"default"</code> - the generic fallback that always matches. Can be a CommonJS
or ES module file. <em>This condition should always come last.</em></li>
</ul>
<p>Within the <a href="#all_packages_exports"><code>"exports"</code></a> object, key order is significant. During condition
matching, earlier entries have higher priority and take precedence over later
entries. <em>The general rule is that conditions should be from most specific to
least specific in object order</em>.</p>
<p>Using the <code>"import"</code> and <code>"require"</code> conditions can lead to some hazards,
which are further explained in <a href="#all_packages_dual-commonjses-module-packages">the dual CommonJS/ES module packages section</a>.</p>
<p>The <code>"node-addons"</code> condition can be used to provide an entry point which
uses native C++ addons. However, this condition can be disabled via the
<a href="#all_cli_--no-addons"><code>--no-addons</code> flag</a>. When using <code>"node-addons"</code>, it's recommended to treat
<code>"default"</code> as an enhancement that provides a more universal entry point, e.g.
using WebAssembly instead of a native addon.</p>
<p>Conditional exports can also be extended to exports subpaths, for example:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"exports"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"."</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./index.js"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"./feature.js"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"node"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./feature-node.js"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"default"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./feature.js"</span>
    <span class="hljs-punctuation">}</span>
  <span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>Defines a package where <code>require('pkg/feature.js')</code> and
<code>import 'pkg/feature.js'</code> could provide different implementations between
Node.js and other JS environments.</p>
<p>When using environment branches, always include a <code>"default"</code> condition where
possible. Providing a <code>"default"</code> condition ensures that any unknown JS
environments are able to use this universal implementation, which helps avoid
these JS environments from having to pretend to be existing environments in
order to support packages with conditional exports. For this reason, using
<code>"node"</code> and <code>"default"</code> condition branches is usually preferable to using
<code>"node"</code> and <code>"browser"</code> condition branches.</p>
<h4>Nested conditions<span><a class="mark" href="#all_packages_nested-conditions" id="all_packages_nested-conditions">#</a></span><a aria-hidden="true" class="legacy" id="packages_nested_conditions"></a></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>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"exports"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"node"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"import"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./feature-node.mjs"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"require"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./feature-node.cjs"</span>
    <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"default"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./feature.mjs"</span>
  <span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>Conditions continue to be matched in order as with flat conditions. If
a nested condition 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>Resolving user conditions<span><a class="mark" href="#all_packages_resolving-user-conditions" id="all_packages_resolving-user-conditions">#</a></span><a aria-hidden="true" class="legacy" id="packages_resolving_user_conditions"></a></h4>
<div class="api_metadata">
<span>Added in: v14.9.0, v12.19.0</span>
</div>
<p>When running Node.js, custom user conditions can be added with the
<code>--conditions</code> flag:</p>
<pre><code class="language-bash">node --conditions=development index.js</code> <button class="copy-button">copy</button></pre>
<p>which would then resolve the <code>"development"</code> condition in package imports and
exports, while resolving the existing <code>"node"</code>, <code>"node-addons"</code>, <code>"default"</code>,
<code>"import"</code>, and <code>"require"</code> conditions as appropriate.</p>
<p>Any number of custom conditions can be set with repeat flags.</p>
<h4>Community Conditions Definitions<span><a class="mark" href="#all_packages_community-conditions-definitions" id="all_packages_community-conditions-definitions">#</a></span><a aria-hidden="true" class="legacy" id="packages_community_conditions_definitions"></a></h4>
<p>Condition strings other than the <code>"import"</code>, <code>"require"</code>, <code>"node"</code>,
<code>"node-addons"</code> and <code>"default"</code> conditions
<a href="#all_packages_conditional-exports">implemented in Node.js core</a> are ignored by default.</p>
<p>Other platforms may implement other conditions and user conditions can be
enabled in Node.js via the <a href="#all_packages_resolving-user-conditions"><code>--conditions</code> / <code>-C</code> flag</a>.</p>
<p>Since custom package conditions require clear definitions to ensure correct
usage, a list of common known package conditions and their strict definitions
is provided below to assist with ecosystem coordination.</p>
<ul>
<li><code>"types"</code> - can be used by typing systems to resolve the typing file for
the given export. <em>This condition should always be included first.</em></li>
<li><code>"browser"</code> - any web browser environment.</li>
<li><code>"development"</code> - can be used to define a development-only environment
entry point, for example to provide additional debugging context such as
better error messages when running in a development mode. <em>Must always be
mutually exclusive with <code>"production"</code>.</em></li>
<li><code>"production"</code> - can be used to define a production environment entry
point. <em>Must always be mutually exclusive with <code>"development"</code>.</em></li>
</ul>
<p>For other runtimes, platform-specific condition key definitions are maintained
by the <a href="https://wintercg.org/">WinterCG</a> in the <a href="https://runtime-keys.proposal.wintercg.org/">Runtime Keys</a> proposal specification.</p>
<p>New conditions definitions may be added to this list by creating a pull request
to the <a href="https://github.com/nodejs/node/blob/HEAD/doc/api/packages.md#conditions-definitions">Node.js documentation for this section</a>. The requirements for listing
a new condition definition here are that:</p>
<ul>
<li>The definition should be clear and unambiguous for all implementers.</li>
<li>The use case for why the condition is needed should be clearly justified.</li>
<li>There should exist sufficient existing implementation usage.</li>
<li>The condition name should not conflict with another condition definition or
condition in wide usage.</li>
<li>The listing of the condition definition should provide a coordination
benefit to the ecosystem that wouldn't otherwise be possible. For example,
this would not necessarily be the case for company-specific or
application-specific conditions.</li>
<li>The condition should be such that a Node.js user would expect it to be in
Node.js core documentation. The <code>"types"</code> condition is a good example: It
doesn't really belong in the <a href="https://runtime-keys.proposal.wintercg.org/">Runtime Keys</a> proposal but is a good fit
here in the Node.js docs.</li>
</ul>
<p>The above definitions may be moved to a dedicated conditions registry in due
course.</p>
<h4>Self-referencing a package using its name<span><a class="mark" href="#all_packages_self-referencing-a-package-using-its-name" id="all_packages_self-referencing-a-package-using-its-name">#</a></span><a aria-hidden="true" class="legacy" id="packages_self_referencing_a_package_using_its_name"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.6.0, v12.16.0</td>
<td><p>Unflag self-referencing a package using its name.</p></td></tr>
<tr><td>v13.1.0, v12.16.0</td>
<td><p><span>Added in: v13.1.0, v12.16.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Within a package, the values defined in the package's
<code>package.json</code> <a href="#all_packages_exports"><code>"exports"</code></a> field can be referenced via the package's name.
For example, assuming the <code>package.json</code> is:</p>
<pre><code class="language-json"><span class="hljs-comment">// package.json</span>
<span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"a-package"</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"exports"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"."</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./index.mjs"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"./foo.js"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./foo.js"</span>
  <span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>Then any module <em>in that package</em> can reference an export in the package itself:</p>
<pre><code class="language-js"><span class="hljs-comment">// ./a-module.mjs</span>
<span class="hljs-keyword">import</span> { something } <span class="hljs-keyword">from</span> <span class="hljs-string">'a-package'</span>; <span class="hljs-comment">// Imports "something" from ./index.mjs.</span></code> <button class="copy-button">copy</button></pre>
<p>Self-referencing is available only if <code>package.json</code> has <a href="#all_packages_exports"><code>"exports"</code></a>, and
will allow importing only what that <a href="#all_packages_exports"><code>"exports"</code></a> (in the <code>package.json</code>)
allows. So the code below, given the previous package, will generate a runtime
error:</p>
<pre><code class="language-js"><span class="hljs-comment">// ./another-module.mjs</span>

<span class="hljs-comment">// Imports "another" from ./m.mjs. Fails because</span>
<span class="hljs-comment">// the "package.json" "exports" field</span>
<span class="hljs-comment">// does not provide an export named "./m.mjs".</span>
<span class="hljs-keyword">import</span> { another } <span class="hljs-keyword">from</span> <span class="hljs-string">'a-package/m.mjs'</span>;</code> <button class="copy-button">copy</button></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 cjs"><span class="hljs-comment">// ./a-module.js</span>
<span class="hljs-keyword">const</span> { something } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'a-package/foo.js'</span>); <span class="hljs-comment">// Loads from ./foo.js.</span></code> <button class="copy-button">copy</button></pre>
<p>Finally, self-referencing also works with scoped packages. For example, this
code will also work:</p>
<pre><code class="language-json"><span class="hljs-comment">// package.json</span>
<span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"@my/package"</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"exports"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./index.js"</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<pre><code class="language-js cjs"><span class="hljs-comment">// ./index.js</span>
<span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = <span class="hljs-number">42</span>;</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-js cjs"><span class="hljs-comment">// ./other.js</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-built_in">require</span>(<span class="hljs-string">'@my/package'</span>));</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node other.js</span>
42</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Dual CommonJS/ES module packages<span><a class="mark" href="#all_packages_dual-commonjses-module-packages" id="all_packages_dual-commonjses-module-packages">#</a></span><a aria-hidden="true" class="legacy" id="packages_dual_commonjs_es_module_packages"></a></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> <a href="#all_packages_main"><code>"main"</code></a> 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="#all_packages_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="#all_packages_dual-package-hazard" id="all_packages_dual-package-hazard">#</a></span><a aria-hidden="true" class="legacy" id="packages_dual_package_hazard"></a></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="#all_packages_writing-dual-packages-while-avoiding-or-minimizing-hazards" id="all_packages_writing-dual-packages-while-avoiding-or-minimizing-hazards">#</a></span><a aria-hidden="true" class="legacy" id="packages_writing_dual_packages_while_avoiding_or_minimizing_hazards"></a></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 might instead be written where any version of Node.js receives only
CommonJS sources, and any separate ES module sources the package might contain
are 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 might also switch from CommonJS to ES module syntax in a <a href="https://semver.org/">breaking
change</a> 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="#all_packages_approach-1-use-an-es-module-wrapper" id="all_packages_approach-1-use-an-es-module-wrapper">#</a></span><a aria-hidden="true" class="legacy" id="packages_approach_1_use_an_es_module_wrapper"></a></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="#all_packages_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>
<pre><code class="language-json"><span class="hljs-comment">// ./node_modules/pkg/package.json</span>
<span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"type"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"module"</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"exports"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"import"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./wrapper.mjs"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"require"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./index.cjs"</span>
  <span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>The preceding example uses explicit extensions <code>.mjs</code> and <code>.cjs</code>.
If your files use the <code>.js</code> extension, <code>"type": "module"</code> will cause such files
to be treated as ES modules, just as <code>"type": "commonjs"</code> would cause them
to be treated as CommonJS.
See <a href="#all_esm_enabling">Enabling</a>.</p>
<pre><code class="language-js cjs"><span class="hljs-comment">// ./node_modules/pkg/index.cjs</span>
<span class="hljs-built_in">exports</span>.<span class="hljs-property">name</span> = <span class="hljs-string">'value'</span>;</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-js"><span class="hljs-comment">// ./node_modules/pkg/wrapper.mjs</span>
<span class="hljs-keyword">import</span> cjsModule <span class="hljs-keyword">from</span> <span class="hljs-string">'./index.cjs'</span>;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> name = cjsModule.<span class="hljs-property">name</span>;</code> <button class="copy-button">copy</button></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"><span class="hljs-keyword">import</span> cjsModule <span class="hljs-keyword">from</span> <span class="hljs-string">'./index.cjs'</span>;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> name = cjsModule.<span class="hljs-property">name</span>;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> cjsModule;</code> <button class="copy-button">copy</button></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>
<pre><code class="language-json"><span class="hljs-comment">// ./node_modules/pkg/package.json</span>
<span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"type"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"module"</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"exports"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"."</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./index.cjs"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"./module"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./wrapper.mjs"</span>
  <span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<h5>Approach #2: Isolate state<span><a class="mark" href="#all_packages_approach-2-isolate-state" id="all_packages_approach-2-isolate-state">#</a></span><a aria-hidden="true" class="legacy" id="packages_approach_2_isolate_state"></a></h5>
<p>A <a href="#all_packages_nodejs-packagejson-field-definitions"><code>package.json</code></a> file can define the separate CommonJS and ES module entry
points directly:</p>
<pre><code class="language-json"><span class="hljs-comment">// ./node_modules/pkg/package.json</span>
<span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"type"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"module"</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"exports"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"import"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./index.mjs"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"require"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./index.cjs"</span>
  <span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></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 might 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"><span class="hljs-keyword">import</span> <span class="hljs-title class_">Date</span> <span class="hljs-keyword">from</span> <span class="hljs-string">'date'</span>;
<span class="hljs-keyword">const</span> someDate = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Date</span>();
<span class="hljs-comment">// someDate contains state; Date does not</span></code> <button class="copy-button">copy</button></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 cjs"><span class="hljs-comment">// ./node_modules/pkg/index.cjs</span>
<span class="hljs-keyword">const</span> state = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./state.cjs'</span>);
<span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span>.<span class="hljs-property">state</span> = state;</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-js"><span class="hljs-comment">// ./node_modules/pkg/index.mjs</span>
<span class="hljs-keyword">import</span> state <span class="hljs-keyword">from</span> <span class="hljs-string">'./state.cjs'</span>;
<span class="hljs-keyword">export</span> {
  state,
};</code> <button class="copy-button">copy</button></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>
<pre><code class="language-json"><span class="hljs-comment">// ./node_modules/pkg/package.json</span>
<span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"type"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"module"</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"exports"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"."</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./index.cjs"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"./module"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./index.mjs"</span>
  <span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3>Node.js <code>package.json</code> field definitions<span><a class="mark" href="#all_packages_nodejs-packagejson-field-definitions" id="all_packages_nodejs-packagejson-field-definitions">#</a></span><a aria-hidden="true" class="legacy" id="packages_node_js_package_json_field_definitions"></a></h3>
<p>This section describes the fields used by the Node.js runtime. Other tools (such
as <a href="https://docs.npmjs.com/cli/v8/configuring-npm/package-json">npm</a>) use
additional fields which are ignored by Node.js and not documented here.</p>
<p>The following fields in <code>package.json</code> files are used in Node.js:</p>
<ul>
<li><a href="#all_packages_name"><code>"name"</code></a> - Relevant when using named imports within a package. Also used
by package managers as the name of the package.</li>
<li><a href="#all_packages_main"><code>"main"</code></a> - The default module when loading the package, if exports is not
specified, and in versions of Node.js prior to the introduction of exports.</li>
<li><a href="#all_packages_packagemanager"><code>"packageManager"</code></a> - The package manager recommended when contributing to
the package. Leveraged by the <a href="corepack.html">Corepack</a> shims.</li>
<li><a href="#all_packages_type"><code>"type"</code></a> - The package type determining whether to load <code>.js</code> files as
CommonJS or ES modules.</li>
<li><a href="#all_packages_exports"><code>"exports"</code></a> - Package exports and conditional exports. When present,
limits which submodules can be loaded from within the package.</li>
<li><a href="#all_packages_imports"><code>"imports"</code></a> - Package imports, for use by modules within the package
itself.</li>
</ul>
<h4><code>"name"</code><span><a class="mark" href="#all_packages_name" id="all_packages_name">#</a></span><a aria-hidden="true" class="legacy" id="packages_name"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.6.0, v12.16.0</td>
<td><p>Remove the <code>--experimental-resolve-self</code> option.</p></td></tr>
<tr><td>v13.1.0, v12.16.0</td>
<td><p><span>Added in: v13.1.0, v12.16.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"package-name"</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>The <code>"name"</code> field defines your package's name. Publishing to the
<em>npm</em> registry requires a name that satisfies
<a href="https://docs.npmjs.com/files/package.json#name">certain requirements</a>.</p>
<p>The <code>"name"</code> field can be used in addition to the <a href="#all_packages_exports"><code>"exports"</code></a> field to
<a href="#all_packages_self-referencing-a-package-using-its-name">self-reference</a> a package using its name.</p>
<h4><code>"main"</code><span><a class="mark" href="#all_packages_main" id="all_packages_main">#</a></span><a aria-hidden="true" class="legacy" id="packages_main"></a></h4>
<div class="api_metadata">
<span>Added in: v0.4.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"main"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./index.js"</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>The <code>"main"</code> field defines the entry point of a package when imported by name
via a <code>node_modules</code> lookup.  Its value is a path.</p>
<p>When a package has an <a href="#all_packages_exports"><code>"exports"</code></a> field, this will take precedence over the
<code>"main"</code> field when importing the package by name.</p>
<p>It also defines the script that is used when the <a href="#all_modules_folders-as-modules">package directory is loaded
via <code>require()</code></a>.</p>
<pre><code class="language-js cjs"><span class="hljs-comment">// This resolves to ./path/to/directory/index.js.</span>
<span class="hljs-built_in">require</span>(<span class="hljs-string">'./path/to/directory'</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>"packageManager"</code><span><a class="mark" href="#all_packages_packagemanager" id="all_packages_packagemanager">#</a></span><a aria-hidden="true" class="legacy" id="packages_packagemanager"></a></h4>
<div class="api_metadata">
<span>Added in: v16.9.0, v14.19.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"packageManager"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"&#x3C;package manager name>@&#x3C;version>"</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>The <code>"packageManager"</code> field defines which package manager is expected to be
used when working on the current project. It can be set to any of the
<a href="#all_corepack_supported-package-managers">supported package managers</a>, and will ensure that your teams use the exact
same package manager versions without having to install anything else other than
Node.js.</p>
<p>This field is currently experimental and needs to be opted-in; check the
<a href="corepack.html">Corepack</a> page for details about the procedure.</p>
<h4><code>"type"</code><span><a class="mark" href="#all_packages_type" id="all_packages_type">#</a></span><a aria-hidden="true" class="legacy" id="packages_type"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.2.0, v12.17.0</td>
<td><p>Unflag <code>--experimental-modules</code>.</p></td></tr>
<tr><td>v12.0.0</td>
<td><p><span>Added in: v12.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Type: <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>"type"</code> field defines the module format that Node.js uses for all
<code>.js</code> files that have that <code>package.json</code> file as their nearest parent.</p>
<p>Files ending with <code>.js</code> are 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 a node_modules folder or the volume root is reached.</p>
<pre><code class="language-json"><span class="hljs-comment">// package.json</span>
<span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"type"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"module"</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<pre><code class="language-bash"><span class="hljs-comment"># In same folder as preceding package.json</span>
node my-app.js <span class="hljs-comment"># Runs as ES module</span></code> <button class="copy-button">copy</button></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 <a href="modules.html">CommonJS</a>. If the volume
root is reached and no <code>package.json</code> is found, <code>.js</code> files are treated as
<a href="modules.html">CommonJS</a>.</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"><span class="hljs-comment">// my-app.js, part of the same example as above</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'./startup.js'</span>; <span class="hljs-comment">// Loaded as ES module because of package.json</span></code> <button class="copy-button">copy</button></pre>
<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>
<h4><code>"exports"</code><span><a class="mark" href="#all_packages_exports" id="all_packages_exports">#</a></span><a aria-hidden="true" class="legacy" id="packages_exports"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.13.0, v12.20.0</td>
<td><p>Add support for <code>"exports"</code> patterns.</p></td></tr>
<tr><td>v13.7.0, v12.17.0</td>
<td><p>Unflag conditional exports.</p></td></tr>
<tr><td>v13.7.0, v12.16.0</td>
<td><p>Implement logical conditional exports ordering.</p></td></tr>
<tr><td>v13.7.0, v12.16.0</td>
<td><p>Remove the <code>--experimental-conditional-exports</code> option. In 12.16.0, conditional exports are still behind <code>--experimental-modules</code>.</p></td></tr>
<tr><td>v13.2.0, v12.16.0</td>
<td><p>Implement conditional exports.</p></td></tr>
<tr><td>v12.7.0</td>
<td><p><span>Added in: v12.7.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Type: <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#String_type" class="type">&#x3C;string[]></a></li>
</ul>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"exports"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./index.js"</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>The <code>"exports"</code> field allows defining the <a href="#all_packages_package-entry-points">entry points</a> of a package when
imported by name loaded either via a <code>node_modules</code> lookup or a
<a href="#all_packages_self-referencing-a-package-using-its-name">self-reference</a> to its own name. It is supported in Node.js 12+ as an
alternative to the <a href="#all_packages_main"><code>"main"</code></a> that can support defining <a href="#all_packages_subpath-exports">subpath exports</a>
and <a href="#all_packages_conditional-exports">conditional exports</a> while encapsulating internal unexported modules.</p>
<p><a href="#all_packages_conditional-exports">Conditional Exports</a> can also 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>.</p>
<p>All paths defined in the <code>"exports"</code> must be relative file URLs starting with
<code>./</code>.</p>
<h4><code>"imports"</code><span><a class="mark" href="#all_packages_imports" id="all_packages_imports">#</a></span><a aria-hidden="true" class="legacy" id="packages_imports"></a></h4>
<div class="api_metadata">
<span>Added in: v14.6.0, v12.19.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
</ul>
<pre><code class="language-json"><span class="hljs-comment">// package.json</span>
<span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"imports"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"#dep"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"node"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"dep-node-native"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"default"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./dep-polyfill.js"</span>
    <span class="hljs-punctuation">}</span>
  <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"dependencies"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"dep-node-native"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"^1.0.0"</span>
  <span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>Entries in the imports field must be strings starting with <code>#</code>.</p>
<p>Package imports permit mapping to external packages.</p>
<p>This field defines <a href="#all_packages_subpath-imports">subpath imports</a> for the current package.</p></section>
        </section>
<section><h2>Net<span><a class="mark" href="#all_net_net" id="all_net_net">#</a></span><a aria-hidden="true" class="legacy" id="net_net"></a></h2>

<!--lint disable maximum-line-length-->
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/net.js">lib/net.js</a></p>
<p>The <code>node:net</code> module provides an asynchronous network API for creating stream-based
TCP or <a href="#all_net_ipc-support">IPC</a> servers (<a href="#all_net_netcreateserveroptions-connectionlistener"><code>net.createServer()</code></a>) and clients
(<a href="#all_net_netcreateconnection"><code>net.createConnection()</code></a>).</p>
<p>It can be accessed using:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> net = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:net'</span>);</code> <button class="copy-button">copy</button></pre>
<section><h3>IPC support<span><a class="mark" href="#all_net_ipc-support" id="all_net_ipc-support">#</a></span><a aria-hidden="true" class="legacy" id="net_ipc_support"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.8.0</td>
<td><p>Support binding to abstract Unix domain socket path like <code>\0abstract</code>. We can bind '\0' for Node.js <code>&#x3C; v20.4.0</code>.</p></td></tr>
</tbody></table>
</details>
</div>
<p>The <code>node:net</code> module supports IPC with named pipes on Windows, and Unix domain
sockets on other operating systems.</p>
<h4>Identifying paths for IPC connections<span><a class="mark" href="#all_net_identifying-paths-for-ipc-connections" id="all_net_identifying-paths-for-ipc-connections">#</a></span><a aria-hidden="true" class="legacy" id="net_identifying_paths_for_ipc_connections"></a></h4>
<p><a href="#all_net_netconnect"><code>net.connect()</code></a>, <a href="#all_net_netcreateconnection"><code>net.createConnection()</code></a>, <a href="#all_net_serverlisten"><code>server.listen()</code></a>, and
<a href="#all_net_socketconnect"><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
file system 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="#all_net_netcreateserveroptions-connectionlistener"><code>net.createServer()</code></a> may create a Unix domain socket and
<a href="#all_net_serverclosecallback"><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 file system and
will persist until unlinked. On Linux, You can use Unix abstract socket by adding
<code>\0</code> to the beginning of the path, such as <code>\0abstract</code>. The path to the Unix
abstract socket is not visible in the file system and it will disappear automatically
when all open references to the socket are closed.</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.<span class="hljs-title function_">createServer</span>().<span class="hljs-title function_">listen</span>(
  path.<span class="hljs-title function_">join</span>(<span class="hljs-string">'\\\\?\\pipe'</span>, process.<span class="hljs-title function_">cwd</span>(), <span class="hljs-string">'myctl'</span>));</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>net.BlockList</code><span><a class="mark" href="#all_net_class-netblocklist" id="all_net_class-netblocklist">#</a></span><a aria-hidden="true" class="legacy" id="net_class_net_blocklist"></a></h3>
<div class="api_metadata">
<span>Added in: v15.0.0, v14.18.0</span>
</div>
<p>The <code>BlockList</code> object can be used with some network APIs to specify rules for
disabling inbound or outbound access to specific IP addresses, IP ranges, or
IP subnets.</p>
<h4><code>blockList.addAddress(address[, type])</code><span><a class="mark" href="#all_net_blocklistaddaddressaddress-type" id="all_net_blocklistaddaddressaddress-type">#</a></span><a aria-hidden="true" class="legacy" id="net_blocklist_addaddress_address_type"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0, v14.18.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> | <a href="#all_net_class-netsocketaddress" class="type">&#x3C;net.SocketAddress></a> An IPv4 or IPv6 address.</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>'ipv4'</code> or <code>'ipv6'</code>. <strong>Default:</strong> <code>'ipv4'</code>.</li>
</ul>
<p>Adds a rule to block the given IP address.</p>
<h4><code>blockList.addRange(start, end[, type])</code><span><a class="mark" href="#all_net_blocklistaddrangestart-end-type" id="all_net_blocklistaddrangestart-end-type">#</a></span><a aria-hidden="true" class="legacy" id="net_blocklist_addrange_start_end_type"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0, v14.18.0</span>
</div>
<ul>
<li><code>start</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#all_net_class-netsocketaddress" class="type">&#x3C;net.SocketAddress></a> The starting IPv4 or IPv6 address in the
range.</li>
<li><code>end</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#all_net_class-netsocketaddress" class="type">&#x3C;net.SocketAddress></a> The ending IPv4 or IPv6 address in the range.</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>'ipv4'</code> or <code>'ipv6'</code>. <strong>Default:</strong> <code>'ipv4'</code>.</li>
</ul>
<p>Adds a rule to block a range of IP addresses from <code>start</code> (inclusive) to
<code>end</code> (inclusive).</p>
<h4><code>blockList.addSubnet(net, prefix[, type])</code><span><a class="mark" href="#all_net_blocklistaddsubnetnet-prefix-type" id="all_net_blocklistaddsubnetnet-prefix-type">#</a></span><a aria-hidden="true" class="legacy" id="net_blocklist_addsubnet_net_prefix_type"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0, v14.18.0</span>
</div>
<ul>
<li><code>net</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#all_net_class-netsocketaddress" class="type">&#x3C;net.SocketAddress></a> The network IPv4 or IPv6 address.</li>
<li><code>prefix</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The number of CIDR prefix bits. For IPv4, this
must be a value between <code>0</code> and <code>32</code>. For IPv6, this must be between
<code>0</code> and <code>128</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>'ipv4'</code> or <code>'ipv6'</code>. <strong>Default:</strong> <code>'ipv4'</code>.</li>
</ul>
<p>Adds a rule to block a range of IP addresses specified as a subnet mask.</p>
<h4><code>blockList.check(address[, type])</code><span><a class="mark" href="#all_net_blocklistcheckaddress-type" id="all_net_blocklistcheckaddress-type">#</a></span><a aria-hidden="true" class="legacy" id="net_blocklist_check_address_type"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0, v14.18.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> | <a href="#all_net_class-netsocketaddress" class="type">&#x3C;net.SocketAddress></a> The IP address to check</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>'ipv4'</code> or <code>'ipv6'</code>. <strong>Default:</strong> <code>'ipv4'</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 given IP address matches any of the rules added to the
<code>BlockList</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> blockList = <span class="hljs-keyword">new</span> net.<span class="hljs-title class_">BlockList</span>();
blockList.<span class="hljs-title function_">addAddress</span>(<span class="hljs-string">'123.123.123.123'</span>);
blockList.<span class="hljs-title function_">addRange</span>(<span class="hljs-string">'10.0.0.1'</span>, <span class="hljs-string">'10.0.0.10'</span>);
blockList.<span class="hljs-title function_">addSubnet</span>(<span class="hljs-string">'8592:757c:efae:4e45::'</span>, <span class="hljs-number">64</span>, <span class="hljs-string">'ipv6'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(blockList.<span class="hljs-title function_">check</span>(<span class="hljs-string">'123.123.123.123'</span>));  <span class="hljs-comment">// Prints: true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(blockList.<span class="hljs-title function_">check</span>(<span class="hljs-string">'10.0.0.3'</span>));  <span class="hljs-comment">// Prints: true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(blockList.<span class="hljs-title function_">check</span>(<span class="hljs-string">'222.111.111.222'</span>));  <span class="hljs-comment">// Prints: false</span>

<span class="hljs-comment">// IPv6 notation for IPv4 addresses works:</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(blockList.<span class="hljs-title function_">check</span>(<span class="hljs-string">'::ffff:7b7b:7b7b'</span>, <span class="hljs-string">'ipv6'</span>)); <span class="hljs-comment">// Prints: true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(blockList.<span class="hljs-title function_">check</span>(<span class="hljs-string">'::ffff:123.123.123.123'</span>, <span class="hljs-string">'ipv6'</span>)); <span class="hljs-comment">// Prints: true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>blockList.rules</code><span><a class="mark" href="#all_net_blocklistrules" id="all_net_blocklistrules">#</a></span><a aria-hidden="true" class="legacy" id="net_blocklist_rules"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0, v14.18.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a></li>
</ul>
<p>The list of rules added to the blocklist.</p>
</section><section><h3>Class: <code>net.SocketAddress</code><span><a class="mark" href="#all_net_class-netsocketaddress" id="all_net_class-netsocketaddress">#</a></span><a aria-hidden="true" class="legacy" id="net_class_net_socketaddress"></a></h3>
<div class="api_metadata">
<span>Added in: v15.14.0, v14.18.0</span>
</div>
<h4><code>new net.SocketAddress([options])</code><span><a class="mark" href="#all_net_new-netsocketaddressoptions" id="all_net_new-netsocketaddressoptions">#</a></span><a aria-hidden="true" class="legacy" id="net_new_net_socketaddress_options"></a></h4>
<div class="api_metadata">
<span>Added in: v15.14.0, v14.18.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>
<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 network address as either an IPv4 or IPv6 string.
<strong>Default</strong>: <code>'127.0.0.1'</code> if <code>family</code> is <code>'ipv4'</code>; <code>'::'</code> if <code>family</code> is
<code>'ipv6'</code>.</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> One of either <code>'ipv4'</code> or <code>'ipv6'</code>.
<strong>Default</strong>: <code>'ipv4'</code>.</li>
<li><code>flowlabel</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> An IPv6 flow-label used only if <code>family</code> is <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> An IP port.</li>
</ul>
</li>
</ul>
<h4><code>socketaddress.address</code><span><a class="mark" href="#all_net_socketaddressaddress" id="all_net_socketaddressaddress">#</a></span><a aria-hidden="true" class="legacy" id="net_socketaddress_address"></a></h4>
<div class="api_metadata">
<span>Added in: v15.14.0, v14.18.0</span>
</div>
<ul>
<li>Type <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<h4><code>socketaddress.family</code><span><a class="mark" href="#all_net_socketaddressfamily" id="all_net_socketaddressfamily">#</a></span><a aria-hidden="true" class="legacy" id="net_socketaddress_family"></a></h4>
<div class="api_metadata">
<span>Added in: v15.14.0, v14.18.0</span>
</div>
<ul>
<li>Type <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>
</ul>
<h4><code>socketaddress.flowlabel</code><span><a class="mark" href="#all_net_socketaddressflowlabel" id="all_net_socketaddressflowlabel">#</a></span><a aria-hidden="true" class="legacy" id="net_socketaddress_flowlabel"></a></h4>
<div class="api_metadata">
<span>Added in: v15.14.0, v14.18.0</span>
</div>
<ul>
<li>Type <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<h4><code>socketaddress.port</code><span><a class="mark" href="#all_net_socketaddressport" id="all_net_socketaddressport">#</a></span><a aria-hidden="true" class="legacy" id="net_socketaddress_port"></a></h4>
<div class="api_metadata">
<span>Added in: v15.14.0, v14.18.0</span>
</div>
<ul>
<li>Type <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
</section><section><h3>Class: <code>net.Server</code><span><a class="mark" href="#all_net_class-netserver" id="all_net_class-netserver">#</a></span><a aria-hidden="true" class="legacy" id="net_class_net_server"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li>Extends: <a href="#all_events_class-eventemitter" class="type">&#x3C;EventEmitter></a></li>
</ul>
<p>This class is used to create a TCP or <a href="#all_net_ipc-support">IPC</a> server.</p>
<h4><code>new net.Server([options][, connectionListener])</code><span><a class="mark" href="#all_net_new-netserveroptions-connectionlistener" id="all_net_new-netserveroptions-connectionlistener">#</a></span><a aria-hidden="true" class="legacy" id="net_new_net_server_options_connectionlistener"></a></h4>
<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="#all_net_netcreateserveroptions-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="#all_net_event-connection"><code>'connection'</code></a> event.</li>
<li>Returns: <a href="#all_net_class-netserver" class="type">&#x3C;net.Server></a></li>
</ul>
<p><code>net.Server</code> is an <a href="#all_events_class-eventemitter"><code>EventEmitter</code></a> with the following events:</p>
<h4>Event: <code>'close'</code><span><a class="mark" href="#all_net_event-close" id="all_net_event-close">#</a></span><a aria-hidden="true" class="legacy" id="net_event_close"></a></h4>
<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>
<h4>Event: <code>'connection'</code><span><a class="mark" href="#all_net_event-connection" id="all_net_event-connection">#</a></span><a aria-hidden="true" class="legacy" id="net_event_connection"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><a href="#all_net_class-netsocket" 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>
<h4>Event: <code>'error'</code><span><a class="mark" href="#all_net_event-error" id="all_net_event-error">#</a></span><a aria-hidden="true" class="legacy" id="net_event_error"></a></h4>
<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="#all_net_class-netsocket"><code>net.Socket</code></a>, the <a href="#all_net_event-close"><code>'close'</code></a>
event will <strong>not</strong> be emitted directly following this event unless
<a href="#all_net_serverclosecallback"><code>server.close()</code></a> is manually called. See the example in discussion of
<a href="#all_net_serverlisten"><code>server.listen()</code></a>.</p>
<h4>Event: <code>'listening'</code><span><a class="mark" href="#all_net_event-listening" id="all_net_event-listening">#</a></span><a aria-hidden="true" class="legacy" id="net_event_listening"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<p>Emitted when the server has been bound after calling <a href="#all_net_serverlisten"><code>server.listen()</code></a>.</p>
<h4>Event: <code>'drop'</code><span><a class="mark" href="#all_net_event-drop" id="all_net_event-drop">#</a></span><a aria-hidden="true" class="legacy" id="net_event_drop"></a></h4>
<div class="api_metadata">
<span>Added in: v18.6.0, v16.17.0</span>
</div>
<p>When the number of connections reaches the threshold of <code>server.maxConnections</code>,
the server will drop new connections and emit <code>'drop'</code> event instead. If it is a
TCP server, the argument is as follows, otherwise the argument is <code>undefined</code>.</p>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> The argument passed to event listener.
<ul>
<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.</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.</li>
<li><code>localFamily</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Local family.</li>
<li><code>remoteAddress</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Remote address.</li>
<li><code>remotePort</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Remote port.</li>
<li><code>remoteFamily</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Remote IP family. <code>'IPv4'</code> or <code>'IPv6'</code>.</li>
</ul>
</li>
</ul>
<h4><code>server.address()</code><span><a class="mark" href="#all_net_serveraddress" id="all_net_serveraddress">#</a></span><a aria-hidden="true" class="legacy" id="net_server_address"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.4.0</td>
<td><p>The <code>family</code> property now returns a string instead of a number.</p></td></tr>
<tr><td>v18.0.0</td>
<td><p>The <code>family</code> property now returns a number instead of a string.</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>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"><span class="hljs-keyword">const</span> server = net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">socket</span>) =></span> {
  socket.<span class="hljs-title function_">end</span>(<span class="hljs-string">'goodbye\n'</span>);
}).<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-comment">// Handle errors here.</span>
  <span class="hljs-keyword">throw</span> err;
});

<span class="hljs-comment">// Grab an arbitrary unused port.</span>
server.<span class="hljs-title function_">listen</span>(<span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'opened server on'</span>, server.<span class="hljs-title function_">address</span>());
});</code> <button class="copy-button">copy</button></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>
<h4><code>server.close([callback])</code><span><a class="mark" href="#all_net_serverclosecallback" id="all_net_serverclosecallback">#</a></span><a aria-hidden="true" class="legacy" id="net_server_close_callback"></a></h4>
<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="#all_net_class-netserver" 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="#all_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>
<h4><code>server[Symbol.asyncDispose]()</code><span><a class="mark" href="#all_net_serversymbolasyncdispose" id="all_net_serversymbolasyncdispose">#</a></span><a aria-hidden="true" class="legacy" id="net_server_symbol_asyncdispose"></a></h4>
<div class="api_metadata">
<span>Added in: v20.5.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Calls <a href="#all_net_serverclosecallback"><code>server.close()</code></a> and returns a promise that fulfills when the
server has closed.</p>
<h4><code>server.getConnections(callback)</code><span><a class="mark" href="#all_net_servergetconnectionscallback" id="all_net_servergetconnectionscallback">#</a></span><a aria-hidden="true" class="legacy" id="net_server_getconnections_callback"></a></h4>
<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="#all_net_class-netserver" 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>
<h4><code>server.listen()</code><span><a class="mark" href="#all_net_serverlisten" id="all_net_serverlisten">#</a></span><a aria-hidden="true" class="legacy" id="net_server_listen"></a></h4>
<p>Start a server listening for connections. A <code>net.Server</code> can be a TCP or
an <a href="#all_net_ipc-support">IPC</a> server depending on what it listens to.</p>
<p>Possible signatures:</p>
<ul>
<li><a href="#all_net_serverlistenhandle-backlog-callback"><code>server.listen(handle[, backlog][, callback])</code></a></li>
<li><a href="#all_net_serverlistenoptions-callback"><code>server.listen(options[, callback])</code></a></li>
<li><a href="#all_net_serverlistenpath-backlog-callback"><code>server.listen(path[, backlog][, callback])</code></a>
for <a href="#all_net_ipc-support">IPC</a> servers</li>
<li><a href="#all_net_serverlistenport-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="#all_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="#all_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="#all_net_class-netsocket"><code>net.Socket</code></a> are set to <code>SO_REUSEADDR</code> (see <a href="https://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.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =></span> {
  <span class="hljs-keyword">if</span> (e.<span class="hljs-property">code</span> === <span class="hljs-string">'EADDRINUSE'</span>) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'Address in use, retrying...'</span>);
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
      server.<span class="hljs-title function_">close</span>();
      server.<span class="hljs-title function_">listen</span>(<span class="hljs-variable constant_">PORT</span>, <span class="hljs-variable constant_">HOST</span>);
    }, <span class="hljs-number">1000</span>);
  }
});</code> <button class="copy-button">copy</button></pre>
<h5><code>server.listen(handle[, backlog][, callback])</code><span><a class="mark" href="#all_net_serverlistenhandle-backlog-callback" id="all_net_serverlistenhandle-backlog-callback">#</a></span><a aria-hidden="true" class="legacy" id="net_server_listen_handle_backlog_callback"></a></h5>
<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="#all_net_serverlisten"><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="#all_net_class-netserver" 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>
<h5><code>server.listen(options[, callback])</code><span><a class="mark" href="#all_net_serverlistenoptions-callback" id="all_net_serverlistenoptions-callback">#</a></span><a aria-hidden="true" class="legacy" id="net_server_listen_options_callback"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.6.0</td>
<td><p>AbortSignal support was added.</p></td></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><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:
<ul>
<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="#all_net_serverlisten"><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>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>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>
<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="#all_net_identifying-paths-for-ipc-connections">Identifying paths for IPC connections</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><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>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> An AbortSignal that may be used to close a listening
server.</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>
</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="#all_net_class-netserver" class="type">&#x3C;net.Server></a></li>
</ul>
<p>If <code>port</code> is specified, it behaves the same as
<a href="#all_net_serverlistenport-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="#all_net_serverlistenpath-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.<span class="hljs-title function_">listen</span>({
  <span class="hljs-attr">host</span>: <span class="hljs-string">'localhost'</span>,
  <span class="hljs-attr">port</span>: <span class="hljs-number">80</span>,
  <span class="hljs-attr">exclusive</span>: <span class="hljs-literal">true</span>,
});</code> <button class="copy-button">copy</button></pre>
<p>When <code>exclusive</code> is <code>true</code> and the underlying handle is shared, it is
possible that several workers query a handle with different backlogs.
In this case, the first <code>backlog</code> passed to the master process will be used.</p>
<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>
<p>If the <code>signal</code> option is enabled, calling <code>.abort()</code> on the corresponding
<code>AbortController</code> is similar to calling <code>.close()</code> on the server:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> controller = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
server.<span class="hljs-title function_">listen</span>({
  <span class="hljs-attr">host</span>: <span class="hljs-string">'localhost'</span>,
  <span class="hljs-attr">port</span>: <span class="hljs-number">80</span>,
  <span class="hljs-attr">signal</span>: controller.<span class="hljs-property">signal</span>,
});
<span class="hljs-comment">// Later, when you want to close the server.</span>
controller.<span class="hljs-title function_">abort</span>();</code> <button class="copy-button">copy</button></pre>
<h5><code>server.listen(path[, backlog][, callback])</code><span><a class="mark" href="#all_net_serverlistenpath-backlog-callback" id="all_net_serverlistenpath-backlog-callback">#</a></span><a aria-hidden="true" class="legacy" id="net_server_listen_path_backlog_callback"></a></h5>
<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="#all_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="#all_net_serverlisten"><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="#all_net_class-netserver" class="type">&#x3C;net.Server></a></li>
</ul>
<p>Start an <a href="#all_net_ipc-support">IPC</a> server listening for connections on the given <code>path</code>.</p>
<h5><code>server.listen([port[, host[, backlog]]][, callback])</code><span><a class="mark" href="#all_net_serverlistenport-host-backlog-callback" id="all_net_serverlistenport-host-backlog-callback">#</a></span><a aria-hidden="true" class="legacy" id="net_server_listen_port_host_backlog_callback"></a></h5>
<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="#all_net_serverlisten"><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="#all_net_class-netserver" 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="#all_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>
<h4><code>server.listening</code><span><a class="mark" href="#all_net_serverlistening" id="all_net_serverlistening">#</a></span><a aria-hidden="true" class="legacy" id="net_server_listening"></a></h4>
<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>
<h4><code>server.maxConnections</code><span><a class="mark" href="#all_net_servermaxconnections" id="all_net_servermaxconnections">#</a></span><a aria-hidden="true" class="legacy" id="net_server_maxconnections"></a></h4>
<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="#all_child_process_child_processforkmodulepath-args-options"><code>child_process.fork()</code></a>.</p>
<h4><code>server.ref()</code><span><a class="mark" href="#all_net_serverref" id="all_net_serverref">#</a></span><a aria-hidden="true" class="legacy" id="net_server_ref"></a></h4>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div>
<ul>
<li>Returns: <a href="#all_net_class-netserver" 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>
<h4><code>server.unref()</code><span><a class="mark" href="#all_net_serverunref" id="all_net_serverunref">#</a></span><a aria-hidden="true" class="legacy" id="net_server_unref"></a></h4>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div>
<ul>
<li>Returns: <a href="#all_net_class-netserver" 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>
</section><section><h3>Class: <code>net.Socket</code><span><a class="mark" href="#all_net_class-netsocket" id="all_net_class-netsocket">#</a></span><a aria-hidden="true" class="legacy" id="net_class_net_socket"></a></h3>
<div class="api_metadata">
<span>Added in: v0.3.4</span>
</div>
<ul>
<li>Extends: <a href="#all_stream_class-streamduplex" class="type">&#x3C;stream.Duplex></a></li>
</ul>
<p>This class is an abstraction of a TCP socket or a streaming <a href="#all_net_ipc-support">IPC</a> endpoint
(uses named pipes on Windows, and Unix domain sockets otherwise). It is also
an <a href="#all_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="#all_net_netcreateconnection"><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="#all_net_event-connection"><code>'connection'</code></a> event emitted on a <a href="#all_net_class-netserver"><code>net.Server</code></a>, so the user can use
it to interact with the client.</p>
<h4><code>new net.Socket([options])</code><span><a class="mark" href="#all_net_new-netsocketoptions" id="all_net_new-netsocketoptions">#</a></span><a aria-hidden="true" class="legacy" id="net_new_net_socket_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.14.0</td>
<td><p>AbortSignal support was added.</p></td></tr>
<tr><td>v0.3.4</td>
<td><p><span>Added in: v0.3.4</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> Available options are:
<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 socket will
automatically end the writable side when the readable side ends. See
<a href="#all_net_netcreateserveroptions-connectionlistener"><code>net.createServer()</code></a> and the <a href="#all_net_event-end"><code>'end'</code></a> event for details. <strong>Default:</strong>
<code>false</code>.</li>
<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>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.
<ul>
<li><code>buffer</code> <a href="#all_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>
<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>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> An Abort signal that may be used to destroy the
socket.</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="#all_net_class-netsocket" 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="#all_net_ipc-support">IPC</a>
endpoint, depending on what it <a href="#all_net_socketconnect"><code>connect()</code></a> to.</p>
<h4>Event: <code>'close'</code><span><a class="mark" href="#all_net_event-close_1" id="all_net_event-close_1">#</a></span><a aria-hidden="true" class="legacy" id="net_event_close_1"></a></h4>
<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>
<h4>Event: <code>'connect'</code><span><a class="mark" href="#all_net_event-connect" id="all_net_event-connect">#</a></span><a aria-hidden="true" class="legacy" id="net_event_connect"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<p>Emitted when a socket connection is successfully established.
See <a href="#all_net_netcreateconnection"><code>net.createConnection()</code></a>.</p>
<h4>Event: <code>'connectionAttempt'</code><span><a class="mark" href="#all_net_event-connectionattempt" id="all_net_event-connectionattempt">#</a></span><a aria-hidden="true" class="legacy" id="net_event_connectionattempt"></a></h4>
<div class="api_metadata">
<span>Added in: v20.12.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> The IP which the socket is attempting to connect 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> The port which the socket is attempting to connect to.</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> The family of the IP. It can be <code>6</code> for IPv6 or <code>4</code> for IPv4.</li>
</ul>
<p>Emitted when a new connection attempt is started. This may be emitted multiple times
if the family autoselection algorithm is enabled in <a href="#all_net_socketconnectoptions-connectlistener"><code>socket.connect(options)</code></a>.</p>
<h4>Event: <code>'connectionAttemptFailed'</code><span><a class="mark" href="#all_net_event-connectionattemptfailed" id="all_net_event-connectionattemptfailed">#</a></span><a aria-hidden="true" class="legacy" id="net_event_connectionattemptfailed"></a></h4>
<div class="api_metadata">
<span>Added in: v20.12.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> The IP which the socket attempted to connect 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> The port which the socket attempted to connect to.</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> The family of the IP. It can be <code>6</code> for IPv6 or <code>4</code> for IPv4.</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 associated with the failure.</li>
</ul>
<p>Emitted when a connection attempt failed. This may be emitted multiple times
if the family autoselection algorithm is enabled in <a href="#all_net_socketconnectoptions-connectlistener"><code>socket.connect(options)</code></a>.</p>
<h4>Event: <code>'connectionAttemptTimeout'</code><span><a class="mark" href="#all_net_event-connectionattempttimeout" id="all_net_event-connectionattempttimeout">#</a></span><a aria-hidden="true" class="legacy" id="net_event_connectionattempttimeout"></a></h4>
<div class="api_metadata">
<span>Added in: v20.12.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> The IP which the socket attempted to connect 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> The port which the socket attempted to connect to.</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> The family of the IP. It can be <code>6</code> for IPv6 or <code>4</code> for IPv4.</li>
</ul>
<p>Emitted when a connection attempt timed out. This is only emitted (and may be
emitted multiple times) if the family autoselection algorithm is enabled
in <a href="#all_net_socketconnectoptions-connectlistener"><code>socket.connect(options)</code></a>.</p>
<h4>Event: <code>'data'</code><span><a class="mark" href="#all_net_event-data" id="all_net_event-data">#</a></span><a aria-hidden="true" class="legacy" id="net_event_data"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<ul>
<li><a href="#all_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="#all_net_socketsetencodingencoding"><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>
<h4>Event: <code>'drain'</code><span><a class="mark" href="#all_net_event-drain" id="all_net_event-drain">#</a></span><a aria-hidden="true" class="legacy" id="net_event_drain"></a></h4>
<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>
<h4>Event: <code>'end'</code><span><a class="mark" href="#all_net_event-end" id="all_net_event-end">#</a></span><a aria-hidden="true" class="legacy" id="net_event_end"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div>
<p>Emitted when the other end of the socket signals the end of transmission, thus
ending the readable side of the socket.</p>
<p>By default (<code>allowHalfOpen</code> is <code>false</code>) the socket will send an end of
transmission 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="#all_net_socketenddata-encoding-callback"><code>end()</code></a> its writable side,
allowing the user to write arbitrary amounts of data. The user must call
<a href="#all_net_socketenddata-encoding-callback"><code>end()</code></a> explicitly to close the connection (i.e. sending a
FIN packet back).</p>
<h4>Event: <code>'error'</code><span><a class="mark" href="#all_net_event-error_1" id="all_net_event-error_1">#</a></span><a aria-hidden="true" class="legacy" id="net_event_error_1"></a></h4>
<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>
<h4>Event: <code>'lookup'</code><span><a class="mark" href="#all_net_event-lookup" id="all_net_event-lookup">#</a></span><a aria-hidden="true" class="legacy" id="net_event_lookup"></a></h4>
<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="#all_dns_dnslookuphostname-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#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 address type. See <a href="#all_dns_dnslookuphostname-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>
<h4>Event: <code>'ready'</code><span><a class="mark" href="#all_net_event-ready" id="all_net_event-ready">#</a></span><a aria-hidden="true" class="legacy" id="net_event_ready"></a></h4>
<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>
<h4>Event: <code>'timeout'</code><span><a class="mark" href="#all_net_event-timeout" id="all_net_event-timeout">#</a></span><a aria-hidden="true" class="legacy" id="net_event_timeout"></a></h4>
<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="#all_net_socketsettimeouttimeout-callback"><code>socket.setTimeout()</code></a>.</p>
<h4><code>socket.address()</code><span><a class="mark" href="#all_net_socketaddress" id="all_net_socketaddress">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_address"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.4.0</td>
<td><p>The <code>family</code> property now returns a string instead of a number.</p></td></tr>
<tr><td>v18.0.0</td>
<td><p>The <code>family</code> property now returns a number instead of a string.</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>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>
<h4><code>socket.autoSelectFamilyAttemptedAddresses</code><span><a class="mark" href="#all_net_socketautoselectfamilyattemptedaddresses" id="all_net_socketautoselectfamilyattemptedaddresses">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_autoselectfamilyattemptedaddresses"></a></h4>
<div class="api_metadata">
<span>Added in: v19.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>This property is only present if the family autoselection algorithm is enabled in
<a href="#all_net_socketconnectoptions-connectlistener"><code>socket.connect(options)</code></a> and it is an array of the addresses that have been attempted.</p>
<p>Each address is a string in the form of <code>$IP:$PORT</code>. If the connection was successful,
then the last address is the one that the socket is currently connected to.</p>
<h4><code>socket.bufferSize</code><span><a class="mark" href="#all_net_socketbuffersize" id="all_net_socketbuffersize">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_buffersize"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.8</span><span>Deprecated since: v14.6.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_stream_writablewritablelength"><code>writable.writableLength</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></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="#all_net_socketpause"><code>socket.pause()</code></a> and <a href="#all_net_socketresume"><code>socket.resume()</code></a>.</p>
<h4><code>socket.bytesRead</code><span><a class="mark" href="#all_net_socketbytesread" id="all_net_socketbytesread">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_bytesread"></a></h4>
<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>
<h4><code>socket.bytesWritten</code><span><a class="mark" href="#all_net_socketbyteswritten" id="all_net_socketbyteswritten">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_byteswritten"></a></h4>
<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>
<h4><code>socket.connect()</code><span><a class="mark" href="#all_net_socketconnect" id="all_net_socketconnect">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_connect"></a></h4>
<p>Initiate a connection on a given socket.</p>
<p>Possible signatures:</p>
<ul>
<li><a href="#all_net_socketconnectoptions-connectlistener"><code>socket.connect(options[, connectListener])</code></a></li>
<li><a href="#all_net_socketconnectpath-connectlistener"><code>socket.connect(path[, connectListener])</code></a>
for <a href="#all_net_ipc-support">IPC</a> connections.</li>
<li><a href="#all_net_socketconnectport-host-connectlistener"><code>socket.connect(port[, host][, connectListener])</code></a>
for TCP connections.</li>
<li>Returns: <a href="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a> The socket itself.</li>
</ul>
<p>This function is asynchronous. When the connection is established, the
<a href="#all_net_event-connect"><code>'connect'</code></a> event will be emitted. If there is a problem connecting,
instead of a <a href="#all_net_event-connect"><code>'connect'</code></a> event, an <a href="#all_net_event-error_1"><code>'error'</code></a> event will be emitted with
the error passed to the <a href="#all_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="#all_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>
<h5><code>socket.connect(options[, connectListener])</code><span><a class="mark" href="#all_net_socketconnectoptions-connectlistener" id="all_net_socketconnectoptions-connectlistener">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_connect_options_connectlistener"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>The default value for the autoSelectFamily option is now true. The <code>--enable-network-family-autoselection</code> CLI flag has been renamed to <code>--network-family-autoselection</code>. The old name is now an alias but it is discouraged.</p></td></tr>
<tr><td>v19.4.0</td>
<td><p>The default value for autoSelectFamily option can be changed at runtime using <code>setDefaultAutoSelectFamily</code> or via the command line option <code>--enable-network-family-autoselection</code>.</p></td></tr>
<tr><td>v19.3.0, v18.13.0</td>
<td><p>Added the <code>autoSelectFamily</code> option.</p></td></tr>
<tr><td>v17.7.0, v16.15.0</td>
<td><p>The <code>noDelay</code>, <code>keepAlive</code>, and <code>keepAliveInitialDelay</code> options are supported now.</p></td></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="#all_net_socketconnect"><code>socket.connect()</code></a>
methods. Will be added as a listener for the <a href="#all_net_event-connect"><code>'connect'</code></a> event once.</li>
<li>Returns: <a href="#all_net_class-netsocket" 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="#all_net_netcreateconnection"><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>autoSelectFamily</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>, it enables a family
autodetection algorithm that loosely implements section 5 of <a href="https://www.rfc-editor.org/rfc/rfc8305.txt">RFC 8305</a>. The
<code>all</code> option passed to lookup is set to <code>true</code> and the sockets attempts to
connect to all obtained IPv6 and IPv4 addresses, in sequence, until a
connection is established. The first returned AAAA address is tried first,
then the first returned A address, then the second returned AAAA address and
so on. Each connection attempt (but the last one) is given the amount of time
specified by the <code>autoSelectFamilyAttemptTimeout</code> option before timing out and
trying the next address. Ignored if the <code>family</code> option is not <code>0</code> or if
<code>localAddress</code> is set. Connection errors are not emitted if at least one
connection succeeds. If all connections attempts fails, a single
<code>AggregateError</code> with all failed attempts is emitted. <strong>Default:</strong>
<a href="#all_net_netgetdefaultautoselectfamily"><code>net.getDefaultAutoSelectFamily()</code></a>.</li>
<li><code>autoSelectFamilyAttemptTimeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a>: The amount of time in milliseconds
to wait for a connection attempt to finish before trying the next address when
using the <code>autoSelectFamily</code> option. If set to a positive integer less than
<code>10</code>, then the value <code>10</code> will be used instead. <strong>Default:</strong>
<a href="#all_net_netgetdefaultautoselectfamilyattempttimeout"><code>net.getDefaultAutoSelectFamilyAttemptTimeout()</code></a>.</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="#all_dns_supported-getaddrinfo-flags"><code>dns.lookup()</code> hints</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. <strong>Default:</strong> <code>'localhost'</code>.</li>
<li><code>keepAlive</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>, it enables keep-alive functionality on
the socket immediately after the connection is established, similarly on what
is done in <a href="#all_net_socketsetkeepaliveenable-initialdelay"><code>socket.setKeepAlive()</code></a>. <strong>Default:</strong> <code>false</code>.</li>
<li><code>keepAliveInitialDelay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> If set to a positive number, it sets the
initial delay before the first keepalive probe is sent on an idle socket.
<strong>Default:</strong> <code>0</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>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="#all_dns_dnslookuphostname-options-callback"><code>dns.lookup()</code></a>.</li>
<li><code>noDelay</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>, it disables the use of Nagle's algorithm
immediately after the socket is established. <strong>Default:</strong> <code>false</code>.</li>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Required. Port the socket should connect to.</li>
</ul>
<p>For <a href="#all_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="#all_net_identifying-paths-for-ipc-connections">Identifying paths for IPC connections</a>. If provided, the TCP-specific
options above are ignored.</li>
</ul>
<h5><code>socket.connect(path[, connectListener])</code><span><a class="mark" href="#all_net_socketconnectpath-connectlistener" id="all_net_socketconnectpath-connectlistener">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_connect_path_connectlistener"></a></h5>
<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="#all_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="#all_net_socketconnect"><code>socket.connect()</code></a>
methods. Will be added as a listener for the <a href="#all_net_event-connect"><code>'connect'</code></a> event once.</li>
<li>Returns: <a href="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a> The socket itself.</li>
</ul>
<p>Initiate an <a href="#all_net_ipc-support">IPC</a> connection on the given socket.</p>
<p>Alias to
<a href="#all_net_socketconnectoptions-connectlistener"><code>socket.connect(options[, connectListener])</code></a>
called with <code>{ path: path }</code> as <code>options</code>.</p>
<h5><code>socket.connect(port[, host][, connectListener])</code><span><a class="mark" href="#all_net_socketconnectport-host-connectlistener" id="all_net_socketconnectport-host-connectlistener">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_connect_port_host_connectlistener"></a></h5>
<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="#all_net_socketconnect"><code>socket.connect()</code></a>
methods. Will be added as a listener for the <a href="#all_net_event-connect"><code>'connect'</code></a> event once.</li>
<li>Returns: <a href="#all_net_class-netsocket" 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="#all_net_socketconnectoptions-connectlistener"><code>socket.connect(options[, connectListener])</code></a>
called with <code>{port: port, host: host}</code> as <code>options</code>.</p>
<h4><code>socket.connecting</code><span><a class="mark" href="#all_net_socketconnecting" id="all_net_socketconnecting">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_connecting"></a></h4>
<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="#all_net_socketconnectoptions-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="#all_net_socketconnectoptions-connectlistener"><code>socket.connect(options[, connectListener])</code></a>
callback is a listener for the <code>'connect'</code> event.</p>
<h4><code>socket.destroy([error])</code><span><a class="mark" href="#all_net_socketdestroyerror" id="all_net_socketdestroyerror">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_destroy_error"></a></h4>
<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="#all_net_class-netsocket" 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="#all_stream_writabledestroyerror"><code>writable.destroy()</code></a> for further details.</p>
<h4><code>socket.destroyed</code><span><a class="mark" href="#all_net_socketdestroyed" id="all_net_socketdestroyed">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_destroyed"></a></h4>
<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="#all_stream_writabledestroyed"><code>writable.destroyed</code></a> for further details.</p>
<h4><code>socket.destroySoon()</code><span><a class="mark" href="#all_net_socketdestroysoon" id="all_net_socketdestroysoon">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_destroysoon"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.4</span>
</div>
<p>Destroys the socket after all data is written. If the <code>'finish'</code> event was
already emitted the socket is destroyed immediately. If the socket is still
writable it implicitly calls <code>socket.end()</code>.</p>
<h4><code>socket.end([data[, encoding]][, callback])</code><span><a class="mark" href="#all_net_socketenddata-encoding-callback" id="all_net_socketenddata-encoding-callback">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_end_data_encoding_callback"></a></h4>
<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="#all_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="#all_net_class-netsocket" 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="#all_stream_writableendchunk-encoding-callback"><code>writable.end()</code></a> for further details.</p>
<h4><code>socket.localAddress</code><span><a class="mark" href="#all_net_socketlocaladdress" id="all_net_socketlocaladdress">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_localaddress"></a></h4>
<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>
<h4><code>socket.localPort</code><span><a class="mark" href="#all_net_socketlocalport" id="all_net_socketlocalport">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_localport"></a></h4>
<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>
<h4><code>socket.localFamily</code><span><a class="mark" href="#all_net_socketlocalfamily" id="all_net_socketlocalfamily">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_localfamily"></a></h4>
<div class="api_metadata">
<span>Added in: v18.8.0, v16.18.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 string representation of the local IP family. <code>'IPv4'</code> or <code>'IPv6'</code>.</p>
<h4><code>socket.pause()</code><span><a class="mark" href="#all_net_socketpause" id="all_net_socketpause">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_pause"></a></h4>
<ul>
<li>Returns: <a href="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a> The socket itself.</li>
</ul>
<p>Pauses the reading of data. That is, <a href="#all_net_event-data"><code>'data'</code></a> events will not be emitted.
Useful to throttle back an upload.</p>
<h4><code>socket.pending</code><span><a class="mark" href="#all_net_socketpending" id="all_net_socketpending">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_pending"></a></h4>
<div class="api_metadata">
<span>Added in: v11.2.0, v10.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></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="#all_net_socketconnecting"><code>socket.connecting</code></a>).</p>
<h4><code>socket.ref()</code><span><a class="mark" href="#all_net_socketref" id="all_net_socketref">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_ref"></a></h4>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div>
<ul>
<li>Returns: <a href="#all_net_class-netsocket" 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>
<h4><code>socket.remoteAddress</code><span><a class="mark" href="#all_net_socketremoteaddress" id="all_net_socketremoteaddress">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_remoteaddress"></a></h4>
<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>
<h4><code>socket.remoteFamily</code><span><a class="mark" href="#all_net_socketremotefamily" id="all_net_socketremotefamily">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_remotefamily"></a></h4>
<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>. Value may be <code>undefined</code> if
the socket is destroyed (for example, if the client disconnected).</p>
<h4><code>socket.remotePort</code><span><a class="mark" href="#all_net_socketremoteport" id="all_net_socketremoteport">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_remoteport"></a></h4>
<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>. Value may be <code>undefined</code> if
the socket is destroyed (for example, if the client disconnected).</p>
<h4><code>socket.resetAndDestroy()</code><span><a class="mark" href="#all_net_socketresetanddestroy" id="all_net_socketresetanddestroy">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_resetanddestroy"></a></h4>
<div class="api_metadata">
<span>Added in: v18.3.0, v16.17.0</span>
</div>
<ul>
<li>Returns: <a href="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a></li>
</ul>
<p>Close the TCP connection by sending an RST packet and destroy the stream.
If this TCP socket is in connecting status, it will send an RST packet and destroy this TCP socket once it is connected.
Otherwise, it will call <code>socket.destroy</code> with an <code>ERR_SOCKET_CLOSED</code> Error.
If this is not a TCP socket (for example, a pipe), calling this method will immediately throw an <code>ERR_INVALID_HANDLE_TYPE</code> Error.</p>
<h4><code>socket.resume()</code><span><a class="mark" href="#all_net_socketresume" id="all_net_socketresume">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_resume"></a></h4>
<ul>
<li>Returns: <a href="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a> The socket itself.</li>
</ul>
<p>Resumes reading after a call to <a href="#all_net_socketpause"><code>socket.pause()</code></a>.</p>
<h4><code>socket.setEncoding([encoding])</code><span><a class="mark" href="#all_net_socketsetencodingencoding" id="all_net_socketsetencodingencoding">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_setencoding_encoding"></a></h4>
<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="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a> The socket itself.</li>
</ul>
<p>Set the encoding for the socket as a <a href="#all_stream_class-streamreadable">Readable Stream</a>. See
<a href="#all_stream_readablesetencodingencoding"><code>readable.setEncoding()</code></a> for more information.</p>
<h4><code>socket.setKeepAlive([enable][, initialDelay])</code><span><a class="mark" href="#all_net_socketsetkeepaliveenable-initialdelay" id="all_net_socketsetkeepaliveenable-initialdelay">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_setkeepalive_enable_initialdelay"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.12.0, v12.17.0</td>
<td><p>New defaults for <code>TCP_KEEPCNT</code> and <code>TCP_KEEPINTVL</code> socket options were added.</p></td></tr>
<tr><td>v0.1.92</td>
<td><p><span>Added in: v0.1.92</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>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="#all_net_class-netsocket" 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>
<p>Enabling the keep-alive functionality will set the following socket options:</p>
<ul>
<li><code>SO_KEEPALIVE=1</code></li>
<li><code>TCP_KEEPIDLE=initialDelay</code></li>
<li><code>TCP_KEEPCNT=10</code></li>
<li><code>TCP_KEEPINTVL=1</code></li>
</ul>
<h4><code>socket.setNoDelay([noDelay])</code><span><a class="mark" href="#all_net_socketsetnodelaynodelay" id="all_net_socketsetnodelaynodelay">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_setnodelay_nodelay"></a></h4>
<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="#all_net_class-netsocket" 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>
<h4><code>socket.setTimeout(timeout[, callback])</code><span><a class="mark" href="#all_net_socketsettimeouttimeout-callback" id="all_net_socketsettimeouttimeout-callback">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_settimeout_timeout_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</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>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="#all_net_class-netsocket" 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="#all_net_event-timeout"><code>'timeout'</code></a>
event but the connection will not be severed. The user must manually call
<a href="#all_net_socketenddata-encoding-callback"><code>socket.end()</code></a> or <a href="#all_net_socketdestroyerror"><code>socket.destroy()</code></a> to end the connection.</p>
<pre><code class="language-js">socket.<span class="hljs-built_in">setTimeout</span>(<span class="hljs-number">3000</span>);
socket.<span class="hljs-title function_">on</span>(<span class="hljs-string">'timeout'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'socket timeout'</span>);
  socket.<span class="hljs-title function_">end</span>();
});</code> <button class="copy-button">copy</button></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="#all_net_event-timeout"><code>'timeout'</code></a> event.</p>
<h4><code>socket.timeout</code><span><a class="mark" href="#all_net_sockettimeout" id="all_net_sockettimeout">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_timeout"></a></h4>
<div class="api_metadata">
<span>Added in: v10.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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a></li>
</ul>
<p>The socket timeout in milliseconds as set by <a href="#all_net_socketsettimeouttimeout-callback"><code>socket.setTimeout()</code></a>.
It is <code>undefined</code> if a timeout has not been set.</p>
<h4><code>socket.unref()</code><span><a class="mark" href="#all_net_socketunref" id="all_net_socketunref">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_unref"></a></h4>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div>
<ul>
<li>Returns: <a href="#all_net_class-netsocket" 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>
<h4><code>socket.write(data[, encoding][, callback])</code><span><a class="mark" href="#all_net_socketwritedata-encoding-callback" id="all_net_socketwritedata-encoding-callback">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_write_data_encoding_callback"></a></h4>
<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="#all_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="#all_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="#all_stream_writablewritechunk-encoding-callback"><code>write()</code></a> method for more
information.</p>
<h4><code>socket.readyState</code><span><a class="mark" href="#all_net_socketreadystate" id="all_net_socketreadystate">#</a></span><a aria-hidden="true" class="legacy" id="net_socket_readystate"></a></h4>
<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>This property represents the state of the connection as a string.</p>
<ul>
<li>If the stream is connecting <code>socket.readyState</code> is <code>opening</code>.</li>
<li>If the stream is readable and writable, it is <code>open</code>.</li>
<li>If the stream is readable and not writable, it is <code>readOnly</code>.</li>
<li>If the stream is not readable and writable, it is <code>writeOnly</code>.</li>
</ul>
</section><section><h3><code>net.connect()</code><span><a class="mark" href="#all_net_netconnect" id="all_net_netconnect">#</a></span><a aria-hidden="true" class="legacy" id="net_net_connect"></a></h3>
<p>Aliases to
<a href="#all_net_netcreateconnection"><code>net.createConnection()</code></a>.</p>
<p>Possible signatures:</p>
<ul>
<li><a href="#all_net_netconnectoptions-connectlistener"><code>net.connect(options[, connectListener])</code></a></li>
<li><a href="#all_net_netconnectpath-connectlistener"><code>net.connect(path[, connectListener])</code></a> for <a href="#all_net_ipc-support">IPC</a>
connections.</li>
<li><a href="#all_net_netconnectport-host-connectlistener"><code>net.connect(port[, host][, connectListener])</code></a>
for TCP connections.</li>
</ul>
<h4><code>net.connect(options[, connectListener])</code><span><a class="mark" href="#all_net_netconnectoptions-connectlistener" id="all_net_netconnectoptions-connectlistener">#</a></span><a aria-hidden="true" class="legacy" id="net_net_connect_options_connectlistener"></a></h4>
<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="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a></li>
</ul>
<p>Alias to
<a href="#all_net_netcreateconnectionoptions-connectlistener"><code>net.createConnection(options[, connectListener])</code></a>.</p>
<h4><code>net.connect(path[, connectListener])</code><span><a class="mark" href="#all_net_netconnectpath-connectlistener" id="all_net_netconnectpath-connectlistener">#</a></span><a aria-hidden="true" class="legacy" id="net_net_connect_path_connectlistener"></a></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></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="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a></li>
</ul>
<p>Alias to
<a href="#all_net_netcreateconnectionpath-connectlistener"><code>net.createConnection(path[, connectListener])</code></a>.</p>
<h4><code>net.connect(port[, host][, connectListener])</code><span><a class="mark" href="#all_net_netconnectport-host-connectlistener" id="all_net_netconnectport-host-connectlistener">#</a></span><a aria-hidden="true" class="legacy" id="net_net_connect_port_host_connectlistener"></a></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>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="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a></li>
</ul>
<p>Alias to
<a href="#all_net_netcreateconnectionport-host-connectlistener"><code>net.createConnection(port[, host][, connectListener])</code></a>.</p>
</section><section><h3><code>net.createConnection()</code><span><a class="mark" href="#all_net_netcreateconnection" id="all_net_netcreateconnection">#</a></span><a aria-hidden="true" class="legacy" id="net_net_createconnection"></a></h3>
<p>A factory function, which creates a new <a href="#all_net_class-netsocket"><code>net.Socket</code></a>,
immediately initiates connection with <a href="#all_net_socketconnect"><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="#all_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="#all_net_event-connect"><code>'connect'</code></a> event <strong>once</strong>.</p>
<p>Possible signatures:</p>
<ul>
<li><a href="#all_net_netcreateconnectionoptions-connectlistener"><code>net.createConnection(options[, connectListener])</code></a></li>
<li><a href="#all_net_netcreateconnectionpath-connectlistener"><code>net.createConnection(path[, connectListener])</code></a>
for <a href="#all_net_ipc-support">IPC</a> connections.</li>
<li><a href="#all_net_netcreateconnectionport-host-connectlistener"><code>net.createConnection(port[, host][, connectListener])</code></a>
for TCP connections.</li>
</ul>
<p>The <a href="#all_net_netconnect"><code>net.connect()</code></a> function is an alias to this function.</p>
<h4><code>net.createConnection(options[, connectListener])</code><span><a class="mark" href="#all_net_netcreateconnectionoptions-connectlistener" id="all_net_netcreateconnectionoptions-connectlistener">#</a></span><a aria-hidden="true" class="legacy" id="net_net_createconnection_options_connectlistener"></a></h4>
<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="#all_net_new-netsocketoptions"><code>new net.Socket([options])</code></a> call and the
<a href="#all_net_socketconnectoptions-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="#all_net_netcreateconnection"><code>net.createConnection()</code></a> functions. If supplied, will be added as
a listener for the <a href="#all_net_event-connect"><code>'connect'</code></a> event on the returned socket once.</li>
<li>Returns: <a href="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a> The newly created socket used to start the connection.</li>
</ul>
<p>For available options, see
<a href="#all_net_new-netsocketoptions"><code>new net.Socket([options])</code></a>
and <a href="#all_net_socketconnectoptions-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="#all_net_socketsettimeouttimeout-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="#all_net_netcreateserveroptions-connectionlistener"><code>net.createServer()</code></a> section:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> net = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:net'</span>);
<span class="hljs-keyword">const</span> client = net.<span class="hljs-title function_">createConnection</span>({ <span class="hljs-attr">port</span>: <span class="hljs-number">8124</span> }, <span class="hljs-function">() =></span> {
  <span class="hljs-comment">// 'connect' listener.</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'connected to server!'</span>);
  client.<span class="hljs-title function_">write</span>(<span class="hljs-string">'world!\r\n'</span>);
});
client.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data.<span class="hljs-title function_">toString</span>());
  client.<span class="hljs-title function_">end</span>();
});
client.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'disconnected from server'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>To connect on the socket <code>/tmp/echo.sock</code>:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> client = net.<span class="hljs-title function_">createConnection</span>({ <span class="hljs-attr">path</span>: <span class="hljs-string">'/tmp/echo.sock'</span> });</code> <button class="copy-button">copy</button></pre>
<p>Following is an example of a client using the <code>port</code> and <code>onread</code>
option. In this case, the <code>onread</code> option will be only used to call
<code>new net.Socket([options])</code> and the <code>port</code> option will be used to
call <code>socket.connect(options[, connectListener])</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> net = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:net'</span>);
net.<span class="hljs-title function_">createConnection</span>({
  <span class="hljs-attr">port</span>: <span class="hljs-number">80</span>,
  <span class="hljs-attr">onread</span>: {
    <span class="hljs-comment">// Reuses a 4KiB Buffer for every read from the socket.</span>
    <span class="hljs-attr">buffer</span>: <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">4</span> * <span class="hljs-number">1024</span>),
    <span class="hljs-attr">callback</span>: <span class="hljs-keyword">function</span>(<span class="hljs-params">nread, buf</span>) {
      <span class="hljs-comment">// Received data is available in `buf` from 0 to `nread`.</span>
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'utf8'</span>, <span class="hljs-number">0</span>, nread));
    },
  },
});</code> <button class="copy-button">copy</button></pre>
<h4><code>net.createConnection(path[, connectListener])</code><span><a class="mark" href="#all_net_netcreateconnectionpath-connectlistener" id="all_net_netcreateconnectionpath-connectlistener">#</a></span><a aria-hidden="true" class="legacy" id="net_net_createconnection_path_connectlistener"></a></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 socket should connect to. Will be passed to
<a href="#all_net_socketconnectpath-connectlistener"><code>socket.connect(path[, connectListener])</code></a>.
See <a href="#all_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="#all_net_netcreateconnection"><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="#all_net_socketconnectpath-connectlistener"><code>socket.connect(path[, connectListener])</code></a>.</li>
<li>Returns: <a href="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a> The newly created socket used to start the connection.</li>
</ul>
<p>Initiates an <a href="#all_net_ipc-support">IPC</a> connection.</p>
<p>This function creates a new <a href="#all_net_class-netsocket"><code>net.Socket</code></a> with all options set to default,
immediately initiates connection with
<a href="#all_net_socketconnectpath-connectlistener"><code>socket.connect(path[, connectListener])</code></a>,
then returns the <code>net.Socket</code> that starts the connection.</p>
<h4><code>net.createConnection(port[, host][, connectListener])</code><span><a class="mark" href="#all_net_netcreateconnectionport-host-connectlistener" id="all_net_netcreateconnectionport-host-connectlistener">#</a></span><a aria-hidden="true" class="legacy" id="net_net_createconnection_port_host_connectlistener"></a></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 socket should connect to. Will be passed to
<a href="#all_net_socketconnectport-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="#all_net_socketconnectport-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="#all_net_netcreateconnection"><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="#all_net_socketconnectport-host-connectlistener"><code>socket.connect(port[, host][, connectListener])</code></a>.</li>
<li>Returns: <a href="#all_net_class-netsocket" 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="#all_net_class-netsocket"><code>net.Socket</code></a> with all options set to default,
immediately initiates connection with
<a href="#all_net_socketconnectport-host-connectlistener"><code>socket.connect(port[, host][, connectListener])</code></a>,
then returns the <code>net.Socket</code> that starts the connection.</p>
</section><section><h3><code>net.createServer([options][, connectionListener])</code><span><a class="mark" href="#all_net_netcreateserveroptions-connectionlistener" id="all_net_netcreateserveroptions-connectionlistener">#</a></span><a aria-hidden="true" class="legacy" id="net_net_createserver_options_connectionlistener"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.1.0</td>
<td><p>The <code>highWaterMark</code> option is supported now.</p></td></tr>
<tr><td>v17.7.0, v16.15.0</td>
<td><p>The <code>noDelay</code>, <code>keepAlive</code>, and <code>keepAliveInitialDelay</code> options are 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>
<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> If set to <code>false</code>, then the socket will
automatically end the writable side when the readable side ends.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>highWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Optionally overrides all <a href="#all_net_class-netsocket"><code>net.Socket</code></a>s'
<code>readableHighWaterMark</code> and <code>writableHighWaterMark</code>.
<strong>Default:</strong> See <a href="#all_stream_streamgetdefaulthighwatermarkobjectmode"><code>stream.getDefaultHighWaterMark()</code></a>.</li>
<li><code>keepAlive</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>, it enables keep-alive functionality
on the socket immediately after a new incoming connection is received,
similarly on what is done in <a href="#all_net_socketsetkeepaliveenable-initialdelay"><code>socket.setKeepAlive()</code></a>. <strong>Default:</strong>
<code>false</code>.</li>
<li><code>keepAliveInitialDelay</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> If set to a positive number, it sets the
initial delay before the first keepalive probe is sent on an idle socket.
<strong>Default:</strong> <code>0</code>.</li>
<li><code>noDelay</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>, it disables the use of Nagle's
algorithm immediately after a new incoming connection is received.
<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>
<p><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="#all_net_event-connection"><code>'connection'</code></a> event.</p>
</li>
<li>
<p>Returns: <a href="#all_net_class-netserver" class="type">&#x3C;net.Server></a></p>
</li>
</ul>
<p>Creates a new TCP or <a href="#all_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
signals the end of transmission, the server will only send back the end of
transmission when <a href="#all_net_socketenddata-encoding-callback"><code>socket.end()</code></a> is explicitly called. For example, in the
context of TCP, when a FIN packed is received, a FIN packed is sent
back only when <a href="#all_net_socketenddata-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="#all_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="#all_net_socketresume"><code>socket.resume()</code></a>.</p>
<p>The server can be a TCP server or an <a href="#all_net_ipc-support">IPC</a> server, depending on what it
<a href="#all_net_serverlisten"><code>listen()</code></a> to.</p>
<p>Here is an example of a TCP echo server which listens for connections
on port 8124:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> net = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:net'</span>);
<span class="hljs-keyword">const</span> server = net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">c</span>) =></span> {
  <span class="hljs-comment">// 'connection' listener.</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'client connected'</span>);
  c.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'client disconnected'</span>);
  });
  c.<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello\r\n'</span>);
  c.<span class="hljs-title function_">pipe</span>(c);
});
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-keyword">throw</span> err;
});
server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8124</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'server bound'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>Test this by using <code>telnet</code>:</p>
<pre><code class="language-bash">telnet localhost 8124</code> <button class="copy-button">copy</button></pre>
<p>To listen on the socket <code>/tmp/echo.sock</code>:</p>
<pre><code class="language-js">server.<span class="hljs-title function_">listen</span>(<span class="hljs-string">'/tmp/echo.sock'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'server bound'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>Use <code>nc</code> to connect to a Unix domain socket server:</p>
<pre><code class="language-bash">nc -U /tmp/echo.sock</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>net.getDefaultAutoSelectFamily()</code><span><a class="mark" href="#all_net_netgetdefaultautoselectfamily" id="all_net_netgetdefaultautoselectfamily">#</a></span><a aria-hidden="true" class="legacy" id="net_net_getdefaultautoselectfamily"></a></h3>
<div class="api_metadata">
<span>Added in: v19.4.0</span>
</div>
<p>Gets the current default value of the <code>autoSelectFamily</code> option of <a href="#all_net_socketconnectoptions-connectlistener"><code>socket.connect(options)</code></a>.
The initial default value is <code>true</code>, unless the command line option
<code>--no-network-family-autoselection</code> is provided.</p>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> The current default value of the <code>autoSelectFamily</code> option.</li>
</ul>
</section><section><h3><code>net.setDefaultAutoSelectFamily(value)</code><span><a class="mark" href="#all_net_netsetdefaultautoselectfamilyvalue" id="all_net_netsetdefaultautoselectfamilyvalue">#</a></span><a aria-hidden="true" class="legacy" id="net_net_setdefaultautoselectfamily_value"></a></h3>
<div class="api_metadata">
<span>Added in: v19.4.0</span>
</div>
<p>Sets the default value of the <code>autoSelectFamily</code> option of <a href="#all_net_socketconnectoptions-connectlistener"><code>socket.connect(options)</code></a>.</p>
<ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> The new default value. The initial default value is <code>false</code>.</li>
</ul>
</section><section><h3><code>net.getDefaultAutoSelectFamilyAttemptTimeout()</code><span><a class="mark" href="#all_net_netgetdefaultautoselectfamilyattempttimeout" id="all_net_netgetdefaultautoselectfamilyattempttimeout">#</a></span><a aria-hidden="true" class="legacy" id="net_net_getdefaultautoselectfamilyattempttimeout"></a></h3>
<div class="api_metadata">
<span>Added in: v19.8.0</span>
</div>
<p>Gets the current default value of the <code>autoSelectFamilyAttemptTimeout</code> option of <a href="#all_net_socketconnectoptions-connectlistener"><code>socket.connect(options)</code></a>.
The initial default value is <code>250</code> or the value specified via the command line
option <code>--network-family-autoselection-attempt-timeout</code>.</p>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The current default value of the <code>autoSelectFamilyAttemptTimeout</code> option.</li>
</ul>
</section><section><h3><code>net.setDefaultAutoSelectFamilyAttemptTimeout(value)</code><span><a class="mark" href="#all_net_netsetdefaultautoselectfamilyattempttimeoutvalue" id="all_net_netsetdefaultautoselectfamilyattempttimeoutvalue">#</a></span><a aria-hidden="true" class="legacy" id="net_net_setdefaultautoselectfamilyattempttimeout_value"></a></h3>
<div class="api_metadata">
<span>Added in: v19.8.0</span>
</div>
<p>Sets the default value of the <code>autoSelectFamilyAttemptTimeout</code> option of <a href="#all_net_socketconnectoptions-connectlistener"><code>socket.connect(options)</code></a>.</p>
<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> The new default value, which must be a positive number. If the number is less than <code>10</code>,
the value <code>10</code> is used instead. The initial default value is <code>250</code> or the value specified via the command line
option <code>--network-family-autoselection-attempt-timeout</code>.</li>
</ul>
</section><section><h3><code>net.isIP(input)</code><span><a class="mark" href="#all_net_netisipinput" id="all_net_netisipinput">#</a></span><a aria-hidden="true" class="legacy" id="net_net_isip_input"></a></h3>
<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>Returns <code>6</code> if <code>input</code> is an IPv6 address. Returns <code>4</code> if <code>input</code> is an IPv4
address in <a href="https://en.wikipedia.org/wiki/Dot-decimal_notation">dot-decimal notation</a> with no leading zeroes. Otherwise, returns
<code>0</code>.</p>
<pre><code class="language-js">net.<span class="hljs-title function_">isIP</span>(<span class="hljs-string">'::1'</span>); <span class="hljs-comment">// returns 6</span>
net.<span class="hljs-title function_">isIP</span>(<span class="hljs-string">'127.0.0.1'</span>); <span class="hljs-comment">// returns 4</span>
net.<span class="hljs-title function_">isIP</span>(<span class="hljs-string">'127.000.000.001'</span>); <span class="hljs-comment">// returns 0</span>
net.<span class="hljs-title function_">isIP</span>(<span class="hljs-string">'127.0.0.1/24'</span>); <span class="hljs-comment">// returns 0</span>
net.<span class="hljs-title function_">isIP</span>(<span class="hljs-string">'fhqwhgads'</span>); <span class="hljs-comment">// returns 0</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>net.isIPv4(input)</code><span><a class="mark" href="#all_net_netisipv4input" id="all_net_netisipv4input">#</a></span><a aria-hidden="true" class="legacy" id="net_net_isipv4_input"></a></h3>
<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 <code>input</code> is an IPv4 address in <a href="https://en.wikipedia.org/wiki/Dot-decimal_notation">dot-decimal notation</a> with no
leading zeroes. Otherwise, returns <code>false</code>.</p>
<pre><code class="language-js">net.<span class="hljs-title function_">isIPv4</span>(<span class="hljs-string">'127.0.0.1'</span>); <span class="hljs-comment">// returns true</span>
net.<span class="hljs-title function_">isIPv4</span>(<span class="hljs-string">'127.000.000.001'</span>); <span class="hljs-comment">// returns false</span>
net.<span class="hljs-title function_">isIPv4</span>(<span class="hljs-string">'127.0.0.1/24'</span>); <span class="hljs-comment">// returns false</span>
net.<span class="hljs-title function_">isIPv4</span>(<span class="hljs-string">'fhqwhgads'</span>); <span class="hljs-comment">// returns false</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>net.isIPv6(input)</code><span><a class="mark" href="#all_net_netisipv6input" id="all_net_netisipv6input">#</a></span><a aria-hidden="true" class="legacy" id="net_net_isipv6_input"></a></h3>
<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 <code>input</code> is an IPv6 address. Otherwise, returns <code>false</code>.</p>
<pre><code class="language-js">net.<span class="hljs-title function_">isIPv6</span>(<span class="hljs-string">'::1'</span>); <span class="hljs-comment">// returns true</span>
net.<span class="hljs-title function_">isIPv6</span>(<span class="hljs-string">'fhqwhgads'</span>); <span class="hljs-comment">// returns false</span></code> <button class="copy-button">copy</button></pre></section>
        </section>
<section><h2>OS<span><a class="mark" href="#all_os_os" id="all_os_os">#</a></span><a aria-hidden="true" class="legacy" id="os_os"></a></h2>

<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/os.js">lib/os.js</a></p>
<p>The <code>node:os</code> module provides operating system-related utility methods and
properties. It can be accessed using:</p>

<pre class="with-30-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> os <span class="hljs-keyword">from</span> <span class="hljs-string">'node:os'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> os = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:os'</span>);</code><button class="copy-button">copy</button></pre>
<section><h3><code>os.EOL</code><span><a class="mark" href="#all_os_oseol" id="all_os_oseol">#</a></span><a aria-hidden="true" class="legacy" id="os_os_eol"></a></h3>
<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>
</section><section><h3><code>os.availableParallelism()</code><span><a class="mark" href="#all_os_osavailableparallelism" id="all_os_osavailableparallelism">#</a></span><a aria-hidden="true" class="legacy" id="os_os_availableparallelism"></a></h3>
<div class="api_metadata">
<span>Added in: v19.4.0, v18.14.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 estimate of the default amount of parallelism a program should use.
Always returns a value greater than zero.</p>
<p>This function is a small wrapper about libuv's <a href="https://docs.libuv.org/en/v1.x/misc.html#c.uv_available_parallelism"><code>uv_available_parallelism()</code></a>.</p>
</section><section><h3><code>os.arch()</code><span><a class="mark" href="#all_os_osarch" id="all_os_osarch">#</a></span><a aria-hidden="true" class="legacy" id="os_os_arch"></a></h3>
<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>'loong64'</code>,
<code>'mips'</code>, <code>'mipsel'</code>, <code>'ppc'</code>, <code>'ppc64'</code>, <code>'riscv64'</code>, <code>'s390'</code>, <code>'s390x'</code>,
and <code>'x64'</code>.</p>
<p>The return value is equivalent to <a href="#all_process_processarch"><code>process.arch</code></a>.</p>
</section><section><h3><code>os.constants</code><span><a class="mark" href="#all_os_osconstants" id="all_os_osconstants">#</a></span><a aria-hidden="true" class="legacy" id="os_os_constants"></a></h3>
<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="#all_os_os-constants">OS constants</a>.</p>
</section><section><h3><code>os.cpus()</code><span><a class="mark" href="#all_os_oscpus" id="all_os_oscpus">#</a></span><a aria-hidden="true" class="legacy" id="os_os_cpus"></a></h3>
<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.
The array will be empty if no CPU information is available, such as if the
<code>/proc</code> file system is unavailable.</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><code>times</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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 @stylistic/js/semi -->
<pre><code class="language-js">[
  {
    <span class="hljs-attr">model</span>: <span class="hljs-string">'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz'</span>,
    <span class="hljs-attr">speed</span>: <span class="hljs-number">2926</span>,
    <span class="hljs-attr">times</span>: {
      <span class="hljs-attr">user</span>: <span class="hljs-number">252020</span>,
      <span class="hljs-attr">nice</span>: <span class="hljs-number">0</span>,
      <span class="hljs-attr">sys</span>: <span class="hljs-number">30340</span>,
      <span class="hljs-attr">idle</span>: <span class="hljs-number">1070356870</span>,
      <span class="hljs-attr">irq</span>: <span class="hljs-number">0</span>,
    },
  },
  {
    <span class="hljs-attr">model</span>: <span class="hljs-string">'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz'</span>,
    <span class="hljs-attr">speed</span>: <span class="hljs-number">2926</span>,
    <span class="hljs-attr">times</span>: {
      <span class="hljs-attr">user</span>: <span class="hljs-number">306960</span>,
      <span class="hljs-attr">nice</span>: <span class="hljs-number">0</span>,
      <span class="hljs-attr">sys</span>: <span class="hljs-number">26980</span>,
      <span class="hljs-attr">idle</span>: <span class="hljs-number">1071569080</span>,
      <span class="hljs-attr">irq</span>: <span class="hljs-number">0</span>,
    },
  },
  {
    <span class="hljs-attr">model</span>: <span class="hljs-string">'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz'</span>,
    <span class="hljs-attr">speed</span>: <span class="hljs-number">2926</span>,
    <span class="hljs-attr">times</span>: {
      <span class="hljs-attr">user</span>: <span class="hljs-number">248450</span>,
      <span class="hljs-attr">nice</span>: <span class="hljs-number">0</span>,
      <span class="hljs-attr">sys</span>: <span class="hljs-number">21750</span>,
      <span class="hljs-attr">idle</span>: <span class="hljs-number">1070919370</span>,
      <span class="hljs-attr">irq</span>: <span class="hljs-number">0</span>,
    },
  },
  {
    <span class="hljs-attr">model</span>: <span class="hljs-string">'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz'</span>,
    <span class="hljs-attr">speed</span>: <span class="hljs-number">2926</span>,
    <span class="hljs-attr">times</span>: {
      <span class="hljs-attr">user</span>: <span class="hljs-number">256880</span>,
      <span class="hljs-attr">nice</span>: <span class="hljs-number">0</span>,
      <span class="hljs-attr">sys</span>: <span class="hljs-number">19430</span>,
      <span class="hljs-attr">idle</span>: <span class="hljs-number">1070905480</span>,
      <span class="hljs-attr">irq</span>: <span class="hljs-number">20</span>,
    },
  },
]</code> <button class="copy-button">copy</button></pre>
<p><code>nice</code> values are POSIX-only. On Windows, the <code>nice</code> values of all processors
are always 0.</p>
<p><code>os.cpus().length</code> should not be used to calculate the amount of parallelism
available to an application. Use
<a href="#all_os_osavailableparallelism"><code>os.availableParallelism()</code></a> for this purpose.</p>
</section><section><h3><code>os.devNull</code><span><a class="mark" href="#all_os_osdevnull" id="all_os_osdevnull">#</a></span><a aria-hidden="true" class="legacy" id="os_os_devnull"></a></h3>
<div class="api_metadata">
<span>Added in: v16.3.0, v14.18.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 platform-specific file path of the null device.</p>
<ul>
<li><code>\\.\nul</code> on Windows</li>
<li><code>/dev/null</code> on POSIX</li>
</ul>
</section><section><h3><code>os.endianness()</code><span><a class="mark" href="#all_os_osendianness" id="all_os_osendianness">#</a></span><a aria-hidden="true" class="legacy" id="os_os_endianness"></a></h3>
<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>
</section><section><h3><code>os.freemem()</code><span><a class="mark" href="#all_os_osfreemem" id="all_os_osfreemem">#</a></span><a aria-hidden="true" class="legacy" id="os_os_freemem"></a></h3>
<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>
</section><section><h3><code>os.getPriority([pid])</code><span><a class="mark" href="#all_os_osgetprioritypid" id="all_os_osgetprioritypid">#</a></span><a aria-hidden="true" class="legacy" id="os_os_getpriority_pid"></a></h3>
<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>
</section><section><h3><code>os.homedir()</code><span><a class="mark" href="#all_os_oshomedir" id="all_os_oshomedir">#</a></span><a aria-hidden="true" class="legacy" id="os_os_homedir"></a></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></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>
</section><section><h3><code>os.hostname()</code><span><a class="mark" href="#all_os_oshostname" id="all_os_oshostname">#</a></span><a aria-hidden="true" class="legacy" id="os_os_hostname"></a></h3>
<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>
</section><section><h3><code>os.loadavg()</code><span><a class="mark" href="#all_os_osloadavg" id="all_os_osloadavg">#</a></span><a aria-hidden="true" class="legacy" id="os_os_loadavg"></a></h3>
<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>
</section><section><h3><code>os.machine()</code><span><a class="mark" href="#all_os_osmachine" id="all_os_osmachine">#</a></span><a aria-hidden="true" class="legacy" id="os_os_machine"></a></h3>
<div class="api_metadata">
<span>Added in: v18.9.0, v16.18.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 machine type as a string, such as <code>arm</code>, <code>arm64</code>, <code>aarch64</code>,
<code>mips</code>, <code>mips64</code>, <code>ppc64</code>, <code>ppc64le</code>, <code>s390</code>, <code>s390x</code>, <code>i386</code>, <code>i686</code>, <code>x86_64</code>.</p>
<p>On POSIX systems, the machine type is determined by calling
<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>
</section><section><h3><code>os.networkInterfaces()</code><span><a class="mark" href="#all_os_osnetworkinterfaces" id="all_os_osnetworkinterfaces">#</a></span><a aria-hidden="true" class="legacy" id="os_os_networkinterfaces"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.4.0</td>
<td><p>The <code>family</code> property now returns a string instead of a number.</p></td></tr>
<tr><td>v18.0.0</td>
<td><p>The <code>family</code> property now returns a number instead of a string.</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>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">{
  <span class="hljs-attr">lo</span>: [
    {
      <span class="hljs-attr">address</span>: <span class="hljs-string">'127.0.0.1'</span>,
      <span class="hljs-attr">netmask</span>: <span class="hljs-string">'255.0.0.0'</span>,
      <span class="hljs-attr">family</span>: <span class="hljs-string">'IPv4'</span>,
      <span class="hljs-attr">mac</span>: <span class="hljs-string">'00:00:00:00:00:00'</span>,
      <span class="hljs-attr">internal</span>: <span class="hljs-literal">true</span>,
      <span class="hljs-attr">cidr</span>: <span class="hljs-string">'127.0.0.1/8'</span>
    },
    {
      <span class="hljs-attr">address</span>: <span class="hljs-string">'::1'</span>,
      <span class="hljs-attr">netmask</span>: <span class="hljs-string">'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff'</span>,
      <span class="hljs-attr">family</span>: <span class="hljs-string">'IPv6'</span>,
      <span class="hljs-attr">mac</span>: <span class="hljs-string">'00:00:00:00:00:00'</span>,
      <span class="hljs-attr">scopeid</span>: <span class="hljs-number">0</span>,
      <span class="hljs-attr">internal</span>: <span class="hljs-literal">true</span>,
      <span class="hljs-attr">cidr</span>: <span class="hljs-string">'::1/128'</span>
    }
  ],
  <span class="hljs-attr">eth0</span>: [
    {
      <span class="hljs-attr">address</span>: <span class="hljs-string">'192.168.1.108'</span>,
      <span class="hljs-attr">netmask</span>: <span class="hljs-string">'255.255.255.0'</span>,
      <span class="hljs-attr">family</span>: <span class="hljs-string">'IPv4'</span>,
      <span class="hljs-attr">mac</span>: <span class="hljs-string">'01:02:03:0a:0b:0c'</span>,
      <span class="hljs-attr">internal</span>: <span class="hljs-literal">false</span>,
      <span class="hljs-attr">cidr</span>: <span class="hljs-string">'192.168.1.108/24'</span>
    },
    {
      <span class="hljs-attr">address</span>: <span class="hljs-string">'fe80::a00:27ff:fe4e:66a1'</span>,
      <span class="hljs-attr">netmask</span>: <span class="hljs-string">'ffff:ffff:ffff:ffff::'</span>,
      <span class="hljs-attr">family</span>: <span class="hljs-string">'IPv6'</span>,
      <span class="hljs-attr">mac</span>: <span class="hljs-string">'01:02:03:0a:0b:0c'</span>,
      <span class="hljs-attr">scopeid</span>: <span class="hljs-number">1</span>,
      <span class="hljs-attr">internal</span>: <span class="hljs-literal">false</span>,
      <span class="hljs-attr">cidr</span>: <span class="hljs-string">'fe80::a00:27ff:fe4e:66a1/64'</span>
    }
  ]
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>os.platform()</code><span><a class="mark" href="#all_os_osplatform" id="all_os_osplatform">#</a></span><a aria-hidden="true" class="legacy" id="os_os_platform"></a></h3>
<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 for which
the Node.js binary was compiled. 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="#all_process_processplatform"><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/HEAD/BUILDING.md#android">Android support is experimental</a>.</p>
</section><section><h3><code>os.release()</code><span><a class="mark" href="#all_os_osrelease" id="all_os_osrelease">#</a></span><a aria-hidden="true" class="legacy" id="os_os_release"></a></h3>
<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"><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>
</section><section><h3><code>os.setPriority([pid, ]priority)</code><span><a class="mark" href="#all_os_ossetprioritypid-priority" id="all_os_ossetprioritypid-priority">#</a></span><a aria-hidden="true" class="legacy" id="os_os_setpriority_pid_priority"></a></h3>
<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>
</section><section><h3><code>os.tmpdir()</code><span><a class="mark" href="#all_os_ostmpdir" id="all_os_ostmpdir">#</a></span><a aria-hidden="true" class="legacy" id="os_os_tmpdir"></a></h3>
<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>
<p>On Windows, the result can be overridden by <code>TEMP</code> and <code>TMP</code> environment variables, and
<code>TEMP</code> takes precedence over <code>TMP</code>. If neither is set, it defaults to <code>%SystemRoot%\temp</code>
or <code>%windir%\temp</code>.</p>
<p>On non-Windows platforms, <code>TMPDIR</code>, <code>TMP</code> and <code>TEMP</code> environment variables will be checked
to override the result of this method, in the described order. If none of them is set, it
defaults to <code>/tmp</code>.</p>
<p>Some operating system distributions would either configure <code>TMPDIR</code> (non-Windows) or
<code>TEMP</code> and <code>TMP</code> (Windows) by default without additional configurations by the system
administrators. The result of <code>os.tmpdir()</code> typically reflects the system preference
unless it's explicitly overridden by the users.</p>
</section><section><h3><code>os.totalmem()</code><span><a class="mark" href="#all_os_ostotalmem" id="all_os_ostotalmem">#</a></span><a aria-hidden="true" class="legacy" id="os_os_totalmem"></a></h3>
<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>
</section><section><h3><code>os.type()</code><span><a class="mark" href="#all_os_ostype" id="all_os_ostype">#</a></span><a aria-hidden="true" class="legacy" id="os_os_type"></a></h3>
<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"><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"><code>uname(3)</code></a> on various operating systems.</p>
</section><section><h3><code>os.uptime()</code><span><a class="mark" href="#all_os_osuptime" id="all_os_osuptime">#</a></span><a aria-hidden="true" class="legacy" id="os_os_uptime"></a></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 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>
</section><section><h3><code>os.userInfo([options])</code><span><a class="mark" href="#all_os_osuserinfooptions" id="all_os_osuserinfooptions">#</a></span><a aria-hidden="true" class="legacy" id="os_os_userinfo_options"></a></h3>
<div class="api_metadata">
<span>Added in: v6.0.0</span>
</div>
<ul>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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="#all_errors_class-systemerror"><code>SystemError</code></a> if a user has no <code>username</code> or <code>homedir</code>.</p>
</section><section><h3><code>os.version()</code><span><a class="mark" href="#all_os_osversion" id="all_os_osversion">#</a></span><a aria-hidden="true" class="legacy" id="os_os_version"></a></h3>
<div class="api_metadata">
<span>Added in: v13.11.0, 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"><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>
</section><section><h3>OS constants<span><a class="mark" href="#all_os_os-constants" id="all_os_os-constants">#</a></span><a aria-hidden="true" class="legacy" id="os_os_constants_1"></a></h3>
<p>The following constants are exported by <code>os.constants</code>.</p>
<p>Not all constants will be available on every operating system.</p>
<h4>Signal constants<span><a class="mark" href="#all_os_signal-constants" id="all_os_signal-constants">#</a></span><a aria-hidden="true" class="legacy" id="os_signal_constants"></a></h4>
<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
    (<kbd>Ctrl</kbd>+<kbd>C</kbd>).</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>
<h4>Error constants<span><a class="mark" href="#all_os_error-constants" id="all_os_error-constants">#</a></span><a aria-hidden="true" class="legacy" id="os_error_constants"></a></h4>
<p>The following error constants are exported by <code>os.constants.errno</code>.</p>
<h5>POSIX error constants<span><a class="mark" href="#all_os_posix-error-constants" id="all_os_posix-error-constants">#</a></span><a aria-hidden="true" class="legacy" id="os_posix_error_constants"></a></h5>
<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>
<h5>Windows-specific error constants<span><a class="mark" href="#all_os_windows-specific-error-constants" id="all_os_windows-specific-error-constants">#</a></span><a aria-hidden="true" class="legacy" id="os_windows_specific_error_constants"></a></h5>
<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>
<h4>dlopen constants<span><a class="mark" href="#all_os_dlopen-constants" id="all_os_dlopen-constants">#</a></span><a aria-hidden="true" class="legacy" id="os_dlopen_constants"></a></h4>
<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>
<h4>Priority constants<span><a class="mark" href="#all_os_priority-constants" id="all_os_priority-constants">#</a></span><a aria-hidden="true" class="legacy" id="os_priority_constants"></a></h4>
<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>
<h4>libuv constants<span><a class="mark" href="#all_os_libuv-constants" id="all_os_libuv-constants">#</a></span><a aria-hidden="true" class="legacy" id="os_libuv_constants"></a></h4>
<table>
  <tbody><tr>
    <th>Constant</th>
    <th>Description</th>
  </tr>
  <tr>
    <td><code>UV_UDP_REUSEADDR</code></td>
    <td></td>
  </tr>
</tbody></table></section>
        </section>
<section><h2>Path<span><a class="mark" href="#all_path_path" id="all_path_path">#</a></span><a aria-hidden="true" class="legacy" id="path_path"></a></h2>

<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/path.js">lib/path.js</a></p>
<p>The <code>node:path</code> module provides utilities for working with file and directory
paths. It can be accessed using:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:path'</span>);</code> <button class="copy-button">copy</button></pre>
<section><h3>Windows vs. POSIX<span><a class="mark" href="#all_path_windows-vs-posix" id="all_path_windows-vs-posix">#</a></span><a aria-hidden="true" class="legacy" id="path_windows_vs_posix"></a></h3>
<p>The default operation of the <code>node: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>node: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.<span class="hljs-title function_">basename</span>(<span class="hljs-string">'C:\\temp\\myfile.html'</span>);
<span class="hljs-comment">// Returns: 'C:\\temp\\myfile.html'</span></code> <button class="copy-button">copy</button></pre>
<p>On Windows:</p>
<pre><code class="language-js">path.<span class="hljs-title function_">basename</span>(<span class="hljs-string">'C:\\temp\\myfile.html'</span>);
<span class="hljs-comment">// Returns: 'myfile.html'</span></code> <button class="copy-button">copy</button></pre>
<p>To achieve consistent results when working with Windows file paths on any
operating system, use <a href="#all_path_pathwin32"><code>path.win32</code></a>:</p>
<p>On POSIX and Windows:</p>
<pre><code class="language-js">path.<span class="hljs-property">win32</span>.<span class="hljs-title function_">basename</span>(<span class="hljs-string">'C:\\temp\\myfile.html'</span>);
<span class="hljs-comment">// Returns: 'myfile.html'</span></code> <button class="copy-button">copy</button></pre>
<p>To achieve consistent results when working with POSIX file paths on any
operating system, use <a href="#all_path_pathposix"><code>path.posix</code></a>:</p>
<p>On POSIX and Windows:</p>
<pre><code class="language-js">path.<span class="hljs-property">posix</span>.<span class="hljs-title function_">basename</span>(<span class="hljs-string">'/tmp/myfile.html'</span>);
<span class="hljs-comment">// Returns: 'myfile.html'</span></code> <button class="copy-button">copy</button></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>
</section><section><h3><code>path.basename(path[, suffix])</code><span><a class="mark" href="#all_path_pathbasenamepath-suffix" id="all_path_pathbasenamepath-suffix">#</a></span><a aria-hidden="true" class="legacy" id="path_path_basename_path_suffix"></a></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>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>suffix</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> An optional suffix to remove</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 <a href="#all_path_pathsep">directory separators</a> are
ignored.</p>
<pre><code class="language-js">path.<span class="hljs-title function_">basename</span>(<span class="hljs-string">'/foo/bar/baz/asdf/quux.html'</span>);
<span class="hljs-comment">// Returns: 'quux.html'</span>

path.<span class="hljs-title function_">basename</span>(<span class="hljs-string">'/foo/bar/baz/asdf/quux.html'</span>, <span class="hljs-string">'.html'</span>);
<span class="hljs-comment">// Returns: 'quux'</span></code> <button class="copy-button">copy</button></pre>
<p>Although Windows usually treats file names, including file extensions, in a
case-insensitive manner, this function does not. For example, <code>C:\\foo.html</code> and
<code>C:\\foo.HTML</code> refer to the same file, but <code>basename</code> treats the extension as a
case-sensitive string:</p>
<pre><code class="language-js">path.<span class="hljs-property">win32</span>.<span class="hljs-title function_">basename</span>(<span class="hljs-string">'C:\\foo.html'</span>, <span class="hljs-string">'.html'</span>);
<span class="hljs-comment">// Returns: 'foo'</span>

path.<span class="hljs-property">win32</span>.<span class="hljs-title function_">basename</span>(<span class="hljs-string">'C:\\foo.HTML'</span>, <span class="hljs-string">'.html'</span>);
<span class="hljs-comment">// Returns: 'foo.HTML'</span></code> <button class="copy-button">copy</button></pre>
<p>A <a href="#all_errors_class-typeerror"><code>TypeError</code></a> is thrown if <code>path</code> is not a string or if <code>suffix</code> is given
and is not a string.</p>
</section><section><h3><code>path.delimiter</code><span><a class="mark" href="#all_path_pathdelimiter" id="all_path_pathdelimiter">#</a></span><a aria-hidden="true" class="legacy" id="path_path_delimiter"></a></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#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"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(process.<span class="hljs-property">env</span>.<span class="hljs-property">PATH</span>);
<span class="hljs-comment">// Prints: '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin'</span>

process.<span class="hljs-property">env</span>.<span class="hljs-property">PATH</span>.<span class="hljs-title function_">split</span>(path.<span class="hljs-property">delimiter</span>);
<span class="hljs-comment">// Returns: ['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin']</span></code> <button class="copy-button">copy</button></pre>
<p>On Windows:</p>
<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(process.<span class="hljs-property">env</span>.<span class="hljs-property">PATH</span>);
<span class="hljs-comment">// Prints: 'C:\Windows\system32;C:\Windows;C:\Program Files\node\'</span>

process.<span class="hljs-property">env</span>.<span class="hljs-property">PATH</span>.<span class="hljs-title function_">split</span>(path.<span class="hljs-property">delimiter</span>);
<span class="hljs-comment">// Returns ['C:\\Windows\\system32', 'C:\\Windows', 'C:\\Program Files\\node\\']</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>path.dirname(path)</code><span><a class="mark" href="#all_path_pathdirnamepath" id="all_path_pathdirnamepath">#</a></span><a aria-hidden="true" class="legacy" id="path_path_dirname_path"></a></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>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="#all_path_pathsep"><code>path.sep</code></a>.</p>
<pre><code class="language-js">path.<span class="hljs-title function_">dirname</span>(<span class="hljs-string">'/foo/bar/baz/asdf/quux'</span>);
<span class="hljs-comment">// Returns: '/foo/bar/baz/asdf'</span></code> <button class="copy-button">copy</button></pre>
<p>A <a href="#all_errors_class-typeerror"><code>TypeError</code></a> is thrown if <code>path</code> is not a string.</p>
</section><section><h3><code>path.extname(path)</code><span><a class="mark" href="#all_path_pathextnamepath" id="all_path_pathextnamepath">#</a></span><a aria-hidden="true" class="legacy" id="path_path_extname_path"></a></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>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.<span class="hljs-title function_">extname</span>(<span class="hljs-string">'index.html'</span>);
<span class="hljs-comment">// Returns: '.html'</span>

path.<span class="hljs-title function_">extname</span>(<span class="hljs-string">'index.coffee.md'</span>);
<span class="hljs-comment">// Returns: '.md'</span>

path.<span class="hljs-title function_">extname</span>(<span class="hljs-string">'index.'</span>);
<span class="hljs-comment">// Returns: '.'</span>

path.<span class="hljs-title function_">extname</span>(<span class="hljs-string">'index'</span>);
<span class="hljs-comment">// Returns: ''</span>

path.<span class="hljs-title function_">extname</span>(<span class="hljs-string">'.index'</span>);
<span class="hljs-comment">// Returns: ''</span>

path.<span class="hljs-title function_">extname</span>(<span class="hljs-string">'.index.md'</span>);
<span class="hljs-comment">// Returns: '.md'</span></code> <button class="copy-button">copy</button></pre>
<p>A <a href="#all_errors_class-typeerror"><code>TypeError</code></a> is thrown if <code>path</code> is not a string.</p>
</section><section><h3><code>path.format(pathObject)</code><span><a class="mark" href="#all_path_pathformatpathobject" id="all_path_pathformatpathobject">#</a></span><a aria-hidden="true" class="legacy" id="path_path_format_pathobject"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>The dot will be added if it is not specified in <code>ext</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>pathObject</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Any JavaScript object having the following properties:
<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="#all_path_pathparsepath"><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"><span class="hljs-comment">// If `dir`, `root` and `base` are provided,</span>
<span class="hljs-comment">// `${dir}${path.sep}${base}`</span>
<span class="hljs-comment">// will be returned. `root` is ignored.</span>
path.<span class="hljs-title function_">format</span>({
  <span class="hljs-attr">root</span>: <span class="hljs-string">'/ignored'</span>,
  <span class="hljs-attr">dir</span>: <span class="hljs-string">'/home/user/dir'</span>,
  <span class="hljs-attr">base</span>: <span class="hljs-string">'file.txt'</span>,
});
<span class="hljs-comment">// Returns: '/home/user/dir/file.txt'</span>

<span class="hljs-comment">// `root` will be used if `dir` is not specified.</span>
<span class="hljs-comment">// If only `root` is provided or `dir` is equal to `root` then the</span>
<span class="hljs-comment">// platform separator will not be included. `ext` will be ignored.</span>
path.<span class="hljs-title function_">format</span>({
  <span class="hljs-attr">root</span>: <span class="hljs-string">'/'</span>,
  <span class="hljs-attr">base</span>: <span class="hljs-string">'file.txt'</span>,
  <span class="hljs-attr">ext</span>: <span class="hljs-string">'ignored'</span>,
});
<span class="hljs-comment">// Returns: '/file.txt'</span>

<span class="hljs-comment">// `name` + `ext` will be used if `base` is not specified.</span>
path.<span class="hljs-title function_">format</span>({
  <span class="hljs-attr">root</span>: <span class="hljs-string">'/'</span>,
  <span class="hljs-attr">name</span>: <span class="hljs-string">'file'</span>,
  <span class="hljs-attr">ext</span>: <span class="hljs-string">'.txt'</span>,
});
<span class="hljs-comment">// Returns: '/file.txt'</span>

<span class="hljs-comment">// The dot will be added if it is not specified in `ext`.</span>
path.<span class="hljs-title function_">format</span>({
  <span class="hljs-attr">root</span>: <span class="hljs-string">'/'</span>,
  <span class="hljs-attr">name</span>: <span class="hljs-string">'file'</span>,
  <span class="hljs-attr">ext</span>: <span class="hljs-string">'txt'</span>,
});
<span class="hljs-comment">// Returns: '/file.txt'</span></code> <button class="copy-button">copy</button></pre>
<p>On Windows:</p>
<pre><code class="language-js">path.<span class="hljs-title function_">format</span>({
  <span class="hljs-attr">dir</span>: <span class="hljs-string">'C:\\path\\dir'</span>,
  <span class="hljs-attr">base</span>: <span class="hljs-string">'file.txt'</span>,
});
<span class="hljs-comment">// Returns: 'C:\\path\\dir\\file.txt'</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>path.matchesGlob(path, pattern)</code><span><a class="mark" href="#all_path_pathmatchesglobpath-pattern" id="all_path_pathmatchesglobpath-pattern">#</a></span><a aria-hidden="true" class="legacy" id="path_path_matchesglob_path_pattern"></a></h3>
<div class="api_metadata">
<span>Added in: v20.17.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - 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> The path to glob-match against.</li>
<li><code>pattern</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The glob to check the path against.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Whether or not the <code>path</code> matched the <code>pattern</code>.</li>
</ul>
<p>The <code>path.matchesGlob()</code> method determines if <code>path</code> matches the <code>pattern</code>.</p>
<p>For example:</p>
<pre><code class="language-js">path.<span class="hljs-title function_">matchesGlob</span>(<span class="hljs-string">'/foo/bar'</span>, <span class="hljs-string">'/foo/*'</span>); <span class="hljs-comment">// true</span>
path.<span class="hljs-title function_">matchesGlob</span>(<span class="hljs-string">'/foo/bar*'</span>, <span class="hljs-string">'foo/bird'</span>); <span class="hljs-comment">// false</span></code> <button class="copy-button">copy</button></pre>
<p>A <a href="#all_errors_class-typeerror"><code>TypeError</code></a> is thrown if <code>path</code> or <code>pattern</code> are not strings.</p>
</section><section><h3><code>path.isAbsolute(path)</code><span><a class="mark" href="#all_path_pathisabsolutepath" id="all_path_pathisabsolutepath">#</a></span><a aria-hidden="true" class="legacy" id="path_path_isabsolute_path"></a></h3>
<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.<span class="hljs-title function_">isAbsolute</span>(<span class="hljs-string">'/foo/bar'</span>); <span class="hljs-comment">// true</span>
path.<span class="hljs-title function_">isAbsolute</span>(<span class="hljs-string">'/baz/..'</span>);  <span class="hljs-comment">// true</span>
path.<span class="hljs-title function_">isAbsolute</span>(<span class="hljs-string">'qux/'</span>);     <span class="hljs-comment">// false</span>
path.<span class="hljs-title function_">isAbsolute</span>(<span class="hljs-string">'.'</span>);        <span class="hljs-comment">// false</span></code> <button class="copy-button">copy</button></pre>
<p>On Windows:</p>
<pre><code class="language-js">path.<span class="hljs-title function_">isAbsolute</span>(<span class="hljs-string">'//server'</span>);    <span class="hljs-comment">// true</span>
path.<span class="hljs-title function_">isAbsolute</span>(<span class="hljs-string">'\\\\server'</span>);  <span class="hljs-comment">// true</span>
path.<span class="hljs-title function_">isAbsolute</span>(<span class="hljs-string">'C:/foo/..'</span>);   <span class="hljs-comment">// true</span>
path.<span class="hljs-title function_">isAbsolute</span>(<span class="hljs-string">'C:\\foo\\..'</span>); <span class="hljs-comment">// true</span>
path.<span class="hljs-title function_">isAbsolute</span>(<span class="hljs-string">'bar\\baz'</span>);    <span class="hljs-comment">// false</span>
path.<span class="hljs-title function_">isAbsolute</span>(<span class="hljs-string">'bar/baz'</span>);     <span class="hljs-comment">// false</span>
path.<span class="hljs-title function_">isAbsolute</span>(<span class="hljs-string">'.'</span>);           <span class="hljs-comment">// false</span></code> <button class="copy-button">copy</button></pre>
<p>A <a href="#all_errors_class-typeerror"><code>TypeError</code></a> is thrown if <code>path</code> is not a string.</p>
</section><section><h3><code>path.join([...paths])</code><span><a class="mark" href="#all_path_pathjoinpaths" id="all_path_pathjoinpaths">#</a></span><a aria-hidden="true" class="legacy" id="path_path_join_paths"></a></h3>
<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.<span class="hljs-title function_">join</span>(<span class="hljs-string">'/foo'</span>, <span class="hljs-string">'bar'</span>, <span class="hljs-string">'baz/asdf'</span>, <span class="hljs-string">'quux'</span>, <span class="hljs-string">'..'</span>);
<span class="hljs-comment">// Returns: '/foo/bar/baz/asdf'</span>

path.<span class="hljs-title function_">join</span>(<span class="hljs-string">'foo'</span>, {}, <span class="hljs-string">'bar'</span>);
<span class="hljs-comment">// Throws 'TypeError: Path must be a string. Received {}'</span></code> <button class="copy-button">copy</button></pre>
<p>A <a href="#all_errors_class-typeerror"><code>TypeError</code></a> is thrown if any of the path segments is not a string.</p>
</section><section><h3><code>path.normalize(path)</code><span><a class="mark" href="#all_path_pathnormalizepath" id="all_path_pathnormalizepath">#</a></span><a aria-hidden="true" class="legacy" id="path_path_normalize_path"></a></h3>
<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>On POSIX, the types of normalization applied by this function do not strictly
adhere to the POSIX specification. For example, this function will replace two
leading forward slashes with a single slash as if it was a regular absolute
path, whereas a few POSIX systems assign special meaning to paths beginning with
exactly two forward slashes. Similarly, other substitutions performed by this
function, such as removing <code>..</code> segments, may change how the underlying system
resolves the path.</p>
<p>For example, on POSIX:</p>
<pre><code class="language-js">path.<span class="hljs-title function_">normalize</span>(<span class="hljs-string">'/foo/bar//baz/asdf/quux/..'</span>);
<span class="hljs-comment">// Returns: '/foo/bar/baz/asdf'</span></code> <button class="copy-button">copy</button></pre>
<p>On Windows:</p>
<pre><code class="language-js">path.<span class="hljs-title function_">normalize</span>(<span class="hljs-string">'C:\\temp\\\\foo\\bar\\..\\'</span>);
<span class="hljs-comment">// Returns: 'C:\\temp\\foo\\'</span></code> <button class="copy-button">copy</button></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.<span class="hljs-property">win32</span>.<span class="hljs-title function_">normalize</span>(<span class="hljs-string">'C:////temp\\\\/\\/\\/foo/bar'</span>);
<span class="hljs-comment">// Returns: 'C:\\temp\\foo\\bar'</span></code> <button class="copy-button">copy</button></pre>
<p>A <a href="#all_errors_class-typeerror"><code>TypeError</code></a> is thrown if <code>path</code> is not a string.</p>
</section><section><h3><code>path.parse(path)</code><span><a class="mark" href="#all_path_pathparsepath" id="all_path_pathparsepath">#</a></span><a aria-hidden="true" class="legacy" id="path_path_parse_path"></a></h3>
<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="#all_path_pathsep"><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.<span class="hljs-title function_">parse</span>(<span class="hljs-string">'/home/user/dir/file.txt'</span>);
<span class="hljs-comment">// Returns:</span>
<span class="hljs-comment">// { root: '/',</span>
<span class="hljs-comment">//   dir: '/home/user/dir',</span>
<span class="hljs-comment">//   base: 'file.txt',</span>
<span class="hljs-comment">//   ext: '.txt',</span>
<span class="hljs-comment">//   name: 'file' }</span></code> <button class="copy-button">copy</button></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> <button class="copy-button">copy</button></pre>
<p>On Windows:</p>
<pre><code class="language-js">path.<span class="hljs-title function_">parse</span>(<span class="hljs-string">'C:\\path\\dir\\file.txt'</span>);
<span class="hljs-comment">// Returns:</span>
<span class="hljs-comment">// { root: 'C:\\',</span>
<span class="hljs-comment">//   dir: 'C:\\path\\dir',</span>
<span class="hljs-comment">//   base: 'file.txt',</span>
<span class="hljs-comment">//   ext: '.txt',</span>
<span class="hljs-comment">//   name: 'file' }</span></code> <button class="copy-button">copy</button></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> <button class="copy-button">copy</button></pre>
<p>A <a href="#all_errors_class-typeerror"><code>TypeError</code></a> is thrown if <code>path</code> is not a string.</p>
</section><section><h3><code>path.posix</code><span><a class="mark" href="#all_path_pathposix" id="all_path_pathposix">#</a></span><a aria-hidden="true" class="legacy" id="path_path_posix"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.3.0</td>
<td><p>Exposed as <code>require('path/posix')</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><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>
<p>The API is accessible via <code>require('node:path').posix</code> or <code>require('node:path/posix')</code>.</p>
</section><section><h3><code>path.relative(from, to)</code><span><a class="mark" href="#all_path_pathrelativefrom-to" id="all_path_pathrelativefrom-to">#</a></span><a aria-hidden="true" class="legacy" id="path_path_relative_from_to"></a></h3>
<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.<span class="hljs-title function_">relative</span>(<span class="hljs-string">'/data/orandea/test/aaa'</span>, <span class="hljs-string">'/data/orandea/impl/bbb'</span>);
<span class="hljs-comment">// Returns: '../../impl/bbb'</span></code> <button class="copy-button">copy</button></pre>
<p>On Windows:</p>
<pre><code class="language-js">path.<span class="hljs-title function_">relative</span>(<span class="hljs-string">'C:\\orandea\\test\\aaa'</span>, <span class="hljs-string">'C:\\orandea\\impl\\bbb'</span>);
<span class="hljs-comment">// Returns: '..\\..\\impl\\bbb'</span></code> <button class="copy-button">copy</button></pre>
<p>A <a href="#all_errors_class-typeerror"><code>TypeError</code></a> is thrown if either <code>from</code> or <code>to</code> is not a string.</p>
</section><section><h3><code>path.resolve([...paths])</code><span><a class="mark" href="#all_path_pathresolvepaths" id="all_path_pathresolvepaths">#</a></span><a aria-hidden="true" class="legacy" id="path_path_resolve_paths"></a></h3>
<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.<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'/foo/bar'</span>, <span class="hljs-string">'./baz'</span>);
<span class="hljs-comment">// Returns: '/foo/bar/baz'</span>

path.<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'/foo/bar'</span>, <span class="hljs-string">'/tmp/file/'</span>);
<span class="hljs-comment">// Returns: '/tmp/file'</span>

path.<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'wwwroot'</span>, <span class="hljs-string">'static_files/png/'</span>, <span class="hljs-string">'../gif/image.gif'</span>);
<span class="hljs-comment">// If the current working directory is /home/myself/node,</span>
<span class="hljs-comment">// this returns '/home/myself/node/wwwroot/static_files/gif/image.gif'</span></code> <button class="copy-button">copy</button></pre>
<p>A <a href="#all_errors_class-typeerror"><code>TypeError</code></a> is thrown if any of the arguments is not a string.</p>
</section><section><h3><code>path.sep</code><span><a class="mark" href="#all_path_pathsep" id="all_path_pathsep">#</a></span><a aria-hidden="true" class="legacy" id="path_path_sep"></a></h3>
<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"><span class="hljs-string">'foo/bar/baz'</span>.<span class="hljs-title function_">split</span>(path.<span class="hljs-property">sep</span>);
<span class="hljs-comment">// Returns: ['foo', 'bar', 'baz']</span></code> <button class="copy-button">copy</button></pre>
<p>On Windows:</p>
<pre><code class="language-js"><span class="hljs-string">'foo\\bar\\baz'</span>.<span class="hljs-title function_">split</span>(path.<span class="hljs-property">sep</span>);
<span class="hljs-comment">// Returns: ['foo', 'bar', 'baz']</span></code> <button class="copy-button">copy</button></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>
</section><section><h3><code>path.toNamespacedPath(path)</code><span><a class="mark" href="#all_path_pathtonamespacedpathpath" id="all_path_pathtonamespacedpathpath">#</a></span><a aria-hidden="true" class="legacy" id="path_path_tonamespacedpath_path"></a></h3>
<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 systems. On POSIX systems, the
method is non-operational and always returns <code>path</code> without modifications.</p>
</section><section><h3><code>path.win32</code><span><a class="mark" href="#all_path_pathwin32" id="all_path_pathwin32">#</a></span><a aria-hidden="true" class="legacy" id="path_path_win32"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.3.0</td>
<td><p>Exposed as <code>require('path/win32')</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><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>
<p>The API is accessible via <code>require('node:path').win32</code> or <code>require('node:path/win32')</code>.</p></section>
        </section>
<section><h2>Performance measurement APIs<span><a class="mark" href="#all_perf_hooks_performance-measurement-apis" id="all_perf_hooks_performance-measurement-apis">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performance_measurement_apis"></a></h2>

<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/perf_hooks.js">lib/perf_hooks.js</a></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>
<li><a href="https://www.w3.org/TR/resource-timing-2/">Resource Timing</a></li>
</ul>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">PerformanceObserver</span>, performance } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:perf_hooks'</span>);

<span class="hljs-keyword">const</span> obs = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PerformanceObserver</span>(<span class="hljs-function">(<span class="hljs-params">items</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(items.<span class="hljs-title function_">getEntries</span>()[<span class="hljs-number">0</span>].<span class="hljs-property">duration</span>);
  performance.<span class="hljs-title function_">clearMarks</span>();
});
obs.<span class="hljs-title function_">observe</span>({ <span class="hljs-attr">type</span>: <span class="hljs-string">'measure'</span> });
performance.<span class="hljs-title function_">measure</span>(<span class="hljs-string">'Start to Now'</span>);

performance.<span class="hljs-title function_">mark</span>(<span class="hljs-string">'A'</span>);
<span class="hljs-title function_">doSomeLongRunningProcess</span>(<span class="hljs-function">() =></span> {
  performance.<span class="hljs-title function_">measure</span>(<span class="hljs-string">'A to Now'</span>, <span class="hljs-string">'A'</span>);

  performance.<span class="hljs-title function_">mark</span>(<span class="hljs-string">'B'</span>);
  performance.<span class="hljs-title function_">measure</span>(<span class="hljs-string">'A to B'</span>, <span class="hljs-string">'A'</span>, <span class="hljs-string">'B'</span>);
});</code> <button class="copy-button">copy</button></pre>
<section><h3><code>perf_hooks.performance</code><span><a class="mark" href="#all_perf_hooks_perf_hooksperformance" id="all_perf_hooks_perf_hooksperformance">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_perf_hooks_performance"></a></h3>
<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>
<h4><code>performance.clearMarks([name])</code><span><a class="mark" href="#all_perf_hooks_performanceclearmarksname" id="all_perf_hooks_performanceclearmarksname">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performance_clearmarks_name"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>This method must be called with the <code>performance</code> object as the receiver.</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>
</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>
<h4><code>performance.clearMeasures([name])</code><span><a class="mark" href="#all_perf_hooks_performanceclearmeasuresname" id="all_perf_hooks_performanceclearmeasuresname">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performance_clearmeasures_name"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>This method must be called with the <code>performance</code> object as the receiver.</p></td></tr>
<tr><td>v16.7.0</td>
<td><p><span>Added in: v16.7.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>
</ul>
<p>If <code>name</code> is not provided, removes all <code>PerformanceMeasure</code> objects from the
Performance Timeline. If <code>name</code> is provided, removes only the named measure.</p>
<h4><code>performance.clearResourceTimings([name])</code><span><a class="mark" href="#all_perf_hooks_performanceclearresourcetimingsname" id="all_perf_hooks_performanceclearresourcetimingsname">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performance_clearresourcetimings_name"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>This method must be called with the <code>performance</code> object as the receiver.</p></td></tr>
<tr><td>v18.2.0, v16.17.0</td>
<td><p><span>Added in: v18.2.0, v16.17.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>
</ul>
<p>If <code>name</code> is not provided, removes all <code>PerformanceResourceTiming</code> objects from
the Resource Timeline. If <code>name</code> is provided, removes only the named resource.</p>
<h4><code>performance.eventLoopUtilization([utilization1[, utilization2]])</code><span><a class="mark" href="#all_perf_hooks_performanceeventlooputilizationutilization1-utilization2" id="all_perf_hooks_performanceeventlooputilizationutilization1-utilization2">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performance_eventlooputilization_utilization1_utilization2"></a></h4>
<div class="api_metadata">
<span>Added in: v14.10.0, v12.19.0</span>
</div>
<ul>
<li><code>utilization1</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> The result of a previous call to
<code>eventLoopUtilization()</code>.</li>
<li><code>utilization2</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> The result of a previous call to
<code>eventLoopUtilization()</code> prior to <code>utilization1</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>idle</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li><code>active</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li><code>utilization</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>The <code>eventLoopUtilization()</code> method returns an object that contains the
cumulative duration of time the event loop has been both idle and active as a
high resolution milliseconds timer. The <code>utilization</code> value is the calculated
Event Loop Utilization (ELU).</p>
<p>If bootstrapping has not yet finished on the main thread the properties have
the value of <code>0</code>. The ELU is immediately available on <a href="#all_worker_threads_worker-threads">Worker threads</a> since
bootstrap happens within the event loop.</p>
<p>Both <code>utilization1</code> and <code>utilization2</code> are optional parameters.</p>
<p>If <code>utilization1</code> is passed, then the delta between the current call's <code>active</code>
and <code>idle</code> times, as well as the corresponding <code>utilization</code> value are
calculated and returned (similar to <a href="#all_process_processhrtimetime"><code>process.hrtime()</code></a>).</p>
<p>If <code>utilization1</code> and <code>utilization2</code> are both passed, then the delta is
calculated between the two arguments. This is a convenience option because,
unlike <a href="#all_process_processhrtimetime"><code>process.hrtime()</code></a>, calculating the ELU is more complex than a
single subtraction.</p>
<p>ELU is similar to CPU utilization, except that it only measures event loop
statistics and not CPU usage. It represents the percentage of time the event
loop has spent outside the event loop's event provider (e.g. <code>epoll_wait</code>).
No other CPU idle time is taken into consideration. The following is an example
of how a mostly idle process will have a high ELU.</p>
<pre><code class="language-js"><span class="hljs-meta">'use strict'</span>;
<span class="hljs-keyword">const</span> { eventLoopUtilization } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:perf_hooks'</span>).<span class="hljs-property">performance</span>;
<span class="hljs-keyword">const</span> { spawnSync } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:child_process'</span>);

<span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></span> {
  <span class="hljs-keyword">const</span> elu = <span class="hljs-title function_">eventLoopUtilization</span>();
  <span class="hljs-title function_">spawnSync</span>(<span class="hljs-string">'sleep'</span>, [<span class="hljs-string">'5'</span>]);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">eventLoopUtilization</span>(elu).<span class="hljs-property">utilization</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>Although the CPU is mostly idle while running this script, the value of
<code>utilization</code> is <code>1</code>. This is because the call to
<a href="#all_child_process_child_processspawnsynccommand-args-options"><code>child_process.spawnSync()</code></a> blocks the event loop from proceeding.</p>
<p>Passing in a user-defined object instead of the result of a previous call to
<code>eventLoopUtilization()</code> will lead to undefined behavior. The return values
are not guaranteed to reflect any correct state of the event loop.</p>
<h4><code>performance.getEntries()</code><span><a class="mark" href="#all_perf_hooks_performancegetentries" id="all_perf_hooks_performancegetentries">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performance_getentries"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>This method must be called with the <code>performance</code> object as the receiver.</p></td></tr>
<tr><td>v16.7.0</td>
<td><p><span>Added in: v16.7.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Returns: <a href="#all_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>. If you are only interested in
performance entries of certain types or that have certain names, see
<code>performance.getEntriesByType()</code> and <code>performance.getEntriesByName()</code>.</p>
<h4><code>performance.getEntriesByName(name[, type])</code><span><a class="mark" href="#all_perf_hooks_performancegetentriesbynamename-type" id="all_perf_hooks_performancegetentriesbynamename-type">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performance_getentriesbyname_name_type"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>This method must be called with the <code>performance</code> object as the receiver.</p></td></tr>
<tr><td>v16.7.0</td>
<td><p><span>Added in: v16.7.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>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="#all_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>
<h4><code>performance.getEntriesByType(type)</code><span><a class="mark" href="#all_perf_hooks_performancegetentriesbytypetype" id="all_perf_hooks_performancegetentriesbytypetype">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performance_getentriesbytype_type"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>This method must be called with the <code>performance</code> object as the receiver.</p></td></tr>
<tr><td>v16.7.0</td>
<td><p><span>Added in: v16.7.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></li>
<li>Returns: <a href="#all_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>
<h4><code>performance.mark(name[, options])</code><span><a class="mark" href="#all_perf_hooks_performancemarkname-options" id="all_perf_hooks_performancemarkname-options">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performance_mark_name_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>This method must be called with the <code>performance</code> object as the receiver. The name argument is no longer optional.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p>Updated to conform to the User Timing Level 3 specification.</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>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>detail</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> Additional optional detail to include with the mark.</li>
<li><code>startTime</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> An optional timestamp to be used as the mark time.
<strong>Default</strong>: <code>performance.now()</code>.</li>
</ul>
</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>
<p>The created <code>PerformanceMark</code> entry is put in the global Performance Timeline
and can be queried with <code>performance.getEntries</code>,
<code>performance.getEntriesByName</code>, and <code>performance.getEntriesByType</code>. When the
observation is performed, the entries should be cleared from the global
Performance Timeline manually with <code>performance.clearMarks</code>.</p>
<h4><code>performance.markResourceTiming(timingInfo, requestedUrl, initiatorType, global, cacheMode)</code><span><a class="mark" href="#all_perf_hooks_performancemarkresourcetimingtiminginfo-requestedurl-initiatortype-global-cachemode" id="all_perf_hooks_performancemarkresourcetimingtiminginfo-requestedurl-initiatortype-global-cachemode">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performance_markresourcetiming_timinginfo_requestedurl_initiatortype_global_cachemode"></a></h4>
<div class="api_metadata">
<span>Added in: v18.2.0, v16.17.0</span>
</div>
<ul>
<li><code>timingInfo</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> <a href="https://fetch.spec.whatwg.org/#fetch-timing-info">Fetch Timing Info</a></li>
<li><code>requestedUrl</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The resource url</li>
<li><code>initiatorType</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The initiator name, e.g: 'fetch'</li>
<li><code>global</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
<li><code>cacheMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The cache mode must be an empty string ('') or 'local'</li>
</ul>
<p><em>This property is an extension by Node.js. It is not available in Web browsers.</em></p>
<p>Creates a new <code>PerformanceResourceTiming</code> entry in the Resource Timeline. A
<code>PerformanceResourceTiming</code> is a subclass of <code>PerformanceEntry</code> whose
<code>performanceEntry.entryType</code> is always <code>'resource'</code>. Performance resources
are used to mark moments in the Resource Timeline.</p>
<p>The created <code>PerformanceMark</code> entry is put in the global Resource Timeline
and can be queried with <code>performance.getEntries</code>,
<code>performance.getEntriesByName</code>, and <code>performance.getEntriesByType</code>. When the
observation is performed, the entries should be cleared from the global
Performance Timeline manually with <code>performance.clearResourceTimings</code>.</p>
<h4><code>performance.measure(name[, startMarkOrOptions[, endMark]])</code><span><a class="mark" href="#all_perf_hooks_performancemeasurename-startmarkoroptions-endmark" id="all_perf_hooks_performancemeasurename-startmarkoroptions-endmark">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performance_measure_name_startmarkoroptions_endmark"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>This method must be called with the <code>performance</code> object as the receiver.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p>Updated to conform to the User Timing Level 3 specification.</p></td></tr>
<tr><td>v13.13.0, 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>startMarkOrOptions</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> Optional.
<ul>
<li><code>detail</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> Additional optional detail to include with the measure.</li>
<li><code>duration</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Duration between start and end times.</li>
<li><code>end</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> Timestamp to be used as the end time, or a string
identifying a previously recorded mark.</li>
<li><code>start</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> Timestamp to be used as the start time, or a string
identifying a previously recorded mark.</li>
</ul>
</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. Must be omitted if <code>startMarkOrOptions</code> is an
<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>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, an error is thrown.</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>
<p>The created <code>PerformanceMeasure</code> entry is put in the global Performance Timeline
and can be queried with <code>performance.getEntries</code>,
<code>performance.getEntriesByName</code>, and <code>performance.getEntriesByType</code>. When the
observation is performed, the entries should be cleared from the global
Performance Timeline manually with <code>performance.clearMeasures</code>.</p>
<h4><code>performance.nodeTiming</code><span><a class="mark" href="#all_perf_hooks_performancenodetiming" id="all_perf_hooks_performancenodetiming">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performance_nodetiming"></a></h4>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div>
<ul>
<li><a href="#all_perf_hooks_class-performancenodetiming" 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>
<h4><code>performance.now()</code><span><a class="mark" href="#all_perf_hooks_performancenow" id="all_perf_hooks_performancenow">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performance_now"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>This method must be called with the <code>performance</code> object as the receiver.</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>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>
<h4><code>performance.setResourceTimingBufferSize(maxSize)</code><span><a class="mark" href="#all_perf_hooks_performancesetresourcetimingbuffersizemaxsize" id="all_perf_hooks_performancesetresourcetimingbuffersizemaxsize">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performance_setresourcetimingbuffersize_maxsize"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>This method must be called with the <code>performance</code> object as the receiver.</p></td></tr>
<tr><td>v18.8.0</td>
<td><p><span>Added in: v18.8.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Sets the global performance resource timing buffer size to the specified number
of "resource" type performance entry objects.</p>
<p>By default the max buffer size is set to 250.</p>
<h4><code>performance.timeOrigin</code><span><a class="mark" href="#all_perf_hooks_performancetimeorigin" id="all_perf_hooks_performancetimeorigin">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performance_timeorigin"></a></h4>
<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>
<h4><code>performance.timerify(fn[, options])</code><span><a class="mark" href="#all_perf_hooks_performancetimerifyfn-options" id="all_perf_hooks_performancetimerifyfn-options">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performance_timerify_fn_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0</td>
<td><p>Added the histogram option.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p>Re-implemented to use pure-JavaScript and the ability to time async functions.</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>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>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>histogram</code> <a href="#all_perf_hooks_class-recordablehistogram-extends-histogram" class="type">&#x3C;RecordableHistogram></a> A histogram object created using
<code>perf_hooks.createHistogram()</code> that will record runtime durations in
nanoseconds.</li>
</ul>
</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"><span class="hljs-keyword">const</span> {
  performance,
  <span class="hljs-title class_">PerformanceObserver</span>,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:perf_hooks'</span>);

<span class="hljs-keyword">function</span> <span class="hljs-title function_">someFunction</span>(<span class="hljs-params"></span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'hello world'</span>);
}

<span class="hljs-keyword">const</span> wrapped = performance.<span class="hljs-title function_">timerify</span>(someFunction);

<span class="hljs-keyword">const</span> obs = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PerformanceObserver</span>(<span class="hljs-function">(<span class="hljs-params">list</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(list.<span class="hljs-title function_">getEntries</span>()[<span class="hljs-number">0</span>].<span class="hljs-property">duration</span>);

  performance.<span class="hljs-title function_">clearMarks</span>();
  performance.<span class="hljs-title function_">clearMeasures</span>();
  obs.<span class="hljs-title function_">disconnect</span>();
});
obs.<span class="hljs-title function_">observe</span>({ <span class="hljs-attr">entryTypes</span>: [<span class="hljs-string">'function'</span>] });

<span class="hljs-comment">// A performance timeline entry will be created</span>
<span class="hljs-title function_">wrapped</span>();</code> <button class="copy-button">copy</button></pre>
<p>If the wrapped function returns a promise, a finally handler will be attached
to the promise and the duration will be reported once the finally handler is
invoked.</p>
<h4><code>performance.toJSON()</code><span><a class="mark" href="#all_perf_hooks_performancetojson" id="all_perf_hooks_performancetojson">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performance_tojson"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>This method must be called with the <code>performance</code> object as the receiver.</p></td></tr>
<tr><td>v16.1.0</td>
<td><p><span>Added in: v16.1.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>An object which is JSON representation of the <code>performance</code> object. It
is similar to <a href="https://developer.mozilla.org/en-US/docs/Web/API/Performance/toJSON"><code>window.performance.toJSON</code></a> in browsers.</p>
<h5>Event: <code>'resourcetimingbufferfull'</code><span><a class="mark" href="#all_perf_hooks_event-resourcetimingbufferfull" id="all_perf_hooks_event-resourcetimingbufferfull">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_event_resourcetimingbufferfull"></a></h5>
<div class="api_metadata">
<span>Added in: v18.8.0</span>
</div>
<p>The <code>'resourcetimingbufferfull'</code> event is fired when the global performance
resource timing buffer is full. Adjust resource timing buffer size with
<code>performance.setResourceTimingBufferSize()</code> or clear the buffer with
<code>performance.clearResourceTimings()</code> in the event listener to allow
more entries to be added to the performance timeline buffer.</p>
</section><section><h3>Class: <code>PerformanceEntry</code><span><a class="mark" href="#all_perf_hooks_class-performanceentry" id="all_perf_hooks_class-performanceentry">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_class_performanceentry"></a></h3>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div>
<p>The constructor of this class is not exposed to users directly.</p>
<h4><code>performanceEntry.duration</code><span><a class="mark" href="#all_perf_hooks_performanceentryduration" id="all_perf_hooks_performanceentryduration">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceentry_duration"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceEntry</code> object as the receiver.</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><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>
<h4><code>performanceEntry.entryType</code><span><a class="mark" href="#all_perf_hooks_performanceentryentrytype" id="all_perf_hooks_performanceentryentrytype">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceentry_entrytype"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceEntry</code> object as the receiver.</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><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>'dns'</code> (Node.js only)</li>
<li><code>'function'</code> (Node.js only)</li>
<li><code>'gc'</code> (Node.js only)</li>
<li><code>'http2'</code> (Node.js only)</li>
<li><code>'http'</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>'net'</code> (Node.js only)</li>
<li><code>'node'</code> (Node.js only)</li>
<li><code>'resource'</code> (available on the Web)</li>
</ul>
<h4><code>performanceEntry.name</code><span><a class="mark" href="#all_perf_hooks_performanceentryname" id="all_perf_hooks_performanceentryname">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceentry_name"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceEntry</code> object as the receiver.</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><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>
<h4><code>performanceEntry.startTime</code><span><a class="mark" href="#all_perf_hooks_performanceentrystarttime" id="all_perf_hooks_performanceentrystarttime">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceentry_starttime"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceEntry</code> object as the receiver.</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><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>
</section><section><h3>Class: <code>PerformanceMark</code><span><a class="mark" href="#all_perf_hooks_class-performancemark" id="all_perf_hooks_class-performancemark">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_class_performancemark"></a></h3>
<div class="api_metadata">
<span>Added in: v18.2.0, v16.17.0</span>
</div>
<ul>
<li>Extends: <a href="#all_perf_hooks_class-performanceentry" class="type">&#x3C;PerformanceEntry></a></li>
</ul>
<p>Exposes marks created via the <code>Performance.mark()</code> method.</p>
<h4><code>performanceMark.detail</code><span><a class="mark" href="#all_perf_hooks_performancemarkdetail" id="all_perf_hooks_performancemarkdetail">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performancemark_detail"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceMark</code> object as the receiver.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p><span>Added in: v16.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#Data_types" class="type">&#x3C;any></a></li>
</ul>
<p>Additional detail specified when creating with <code>Performance.mark()</code> method.</p>
</section><section><h3>Class: <code>PerformanceMeasure</code><span><a class="mark" href="#all_perf_hooks_class-performancemeasure" id="all_perf_hooks_class-performancemeasure">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_class_performancemeasure"></a></h3>
<div class="api_metadata">
<span>Added in: v18.2.0, v16.17.0</span>
</div>
<ul>
<li>Extends: <a href="#all_perf_hooks_class-performanceentry" class="type">&#x3C;PerformanceEntry></a></li>
</ul>
<p>Exposes measures created via the <code>Performance.measure()</code> method.</p>
<p>The constructor of this class is not exposed to users directly.</p>
<h4><code>performanceMeasure.detail</code><span><a class="mark" href="#all_perf_hooks_performancemeasuredetail" id="all_perf_hooks_performancemeasuredetail">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performancemeasure_detail"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceMeasure</code> object as the receiver.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p><span>Added in: v16.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#Data_types" class="type">&#x3C;any></a></li>
</ul>
<p>Additional detail specified when creating with <code>Performance.measure()</code> method.</p>
</section><section><h3>Class: <code>PerformanceNodeEntry</code><span><a class="mark" href="#all_perf_hooks_class-performancenodeentry" id="all_perf_hooks_class-performancenodeentry">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_class_performancenodeentry"></a></h3>
<div class="api_metadata">
<span>Added in: v19.0.0</span>
</div>
<ul>
<li>Extends: <a href="#all_perf_hooks_class-performanceentry" class="type">&#x3C;PerformanceEntry></a></li>
</ul>
<p><em>This class is an extension by Node.js. It is not available in Web browsers.</em></p>
<p>Provides detailed Node.js timing data.</p>
<p>The constructor of this class is not exposed to users directly.</p>
<h4><code>performanceNodeEntry.detail</code><span><a class="mark" href="#all_perf_hooks_performancenodeentrydetail" id="all_perf_hooks_performancenodeentrydetail">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performancenodeentry_detail"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceNodeEntry</code> object as the receiver.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p><span>Added in: v16.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#Data_types" class="type">&#x3C;any></a></li>
</ul>
<p>Additional detail specific to the <code>entryType</code>.</p>
<h4><code>performanceNodeEntry.flags</code><span><a class="mark" href="#all_perf_hooks_performancenodeentryflags" id="all_perf_hooks_performancenodeentryflags">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performancenodeentry_flags"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0</td>
<td><p>Runtime deprecated. Now moved to the detail property when entryType is 'gc'.</p></td></tr>
<tr><td>v13.9.0, v12.17.0</td>
<td><p><span>Added in: v13.9.0, v12.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <code>performanceNodeEntry.detail</code> 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>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>
<h4><code>performanceNodeEntry.kind</code><span><a class="mark" href="#all_perf_hooks_performancenodeentrykind" id="all_perf_hooks_performancenodeentrykind">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performancenodeentry_kind"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0</td>
<td><p>Runtime deprecated. Now moved to the detail property when entryType is 'gc'.</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>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <code>performanceNodeEntry.detail</code> 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>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>
<h4>Garbage Collection ('gc') Details<span><a class="mark" href="#all_perf_hooks_garbage-collection-gc-details" id="all_perf_hooks_garbage-collection-gc-details">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_garbage_collection_gc_details"></a></h4>
<p>When <code>performanceEntry.type</code> is equal to <code>'gc'</code>, the
<code>performanceNodeEntry.detail</code> property will be an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> with two properties:</p>
<ul>
<li><code>kind</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> One of:
<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>
</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> One of:
<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>
</li>
</ul>
<h4>HTTP ('http') Details<span><a class="mark" href="#all_perf_hooks_http-http-details" id="all_perf_hooks_http-http-details">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_http_http_details"></a></h4>
<p>When <code>performanceEntry.type</code> is equal to <code>'http'</code>, the
<code>performanceNodeEntry.detail</code> property will be an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> containing
additional information.</p>
<p>If <code>performanceEntry.name</code> is equal to <code>HttpClient</code>, the <code>detail</code>
will contain the following properties: <code>req</code>, <code>res</code>. And the <code>req</code> property
will be an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> containing <code>method</code>, <code>url</code>, <code>headers</code>, the <code>res</code> property
will be an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> containing <code>statusCode</code>, <code>statusMessage</code>, <code>headers</code>.</p>
<p>If <code>performanceEntry.name</code> is equal to <code>HttpRequest</code>, the <code>detail</code>
will contain the following properties: <code>req</code>, <code>res</code>. And the <code>req</code> property
will be an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> containing <code>method</code>, <code>url</code>, <code>headers</code>, the <code>res</code> property
will be an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> containing <code>statusCode</code>, <code>statusMessage</code>, <code>headers</code>.</p>
<p>This could add additional memory overhead and should only be used for
diagnostic purposes, not left turned on in production by default.</p>
<h4>HTTP/2 ('http2') Details<span><a class="mark" href="#all_perf_hooks_http2-http2-details" id="all_perf_hooks_http2-http2-details">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_http_2_http2_details"></a></h4>
<p>When <code>performanceEntry.type</code> is equal to <code>'http2'</code>, the
<code>performanceNodeEntry.detail</code> property will be an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> containing
additional performance information.</p>
<p>If <code>performanceEntry.name</code> is equal to <code>Http2Stream</code>, the <code>detail</code>
will contain the following 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>performanceEntry.name</code> is equal to <code>Http2Session</code>, the <code>detail</code> will
contain the following 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>
<h4>Timerify ('function') Details<span><a class="mark" href="#all_perf_hooks_timerify-function-details" id="all_perf_hooks_timerify-function-details">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_timerify_function_details"></a></h4>
<p>When <code>performanceEntry.type</code> is equal to <code>'function'</code>, the
<code>performanceNodeEntry.detail</code> property will be an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type">&#x3C;Array></a> listing
the input arguments to the timed function.</p>
<h4>Net ('net') Details<span><a class="mark" href="#all_perf_hooks_net-net-details" id="all_perf_hooks_net-net-details">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_net_net_details"></a></h4>
<p>When <code>performanceEntry.type</code> is equal to <code>'net'</code>, the
<code>performanceNodeEntry.detail</code> property will be an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> containing
additional information.</p>
<p>If <code>performanceEntry.name</code> is equal to <code>connect</code>, the <code>detail</code>
will contain the following properties: <code>host</code>, <code>port</code>.</p>
<h4>DNS ('dns') Details<span><a class="mark" href="#all_perf_hooks_dns-dns-details" id="all_perf_hooks_dns-dns-details">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_dns_dns_details"></a></h4>
<p>When <code>performanceEntry.type</code> is equal to <code>'dns'</code>, the
<code>performanceNodeEntry.detail</code> property will be an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> containing
additional information.</p>
<p>If <code>performanceEntry.name</code> is equal to <code>lookup</code>, the <code>detail</code>
will contain the following properties: <code>hostname</code>, <code>family</code>, <code>hints</code>, <code>verbatim</code>,
<code>addresses</code>.</p>
<p>If <code>performanceEntry.name</code> is equal to <code>lookupService</code>, the <code>detail</code> will
contain the following properties: <code>host</code>, <code>port</code>, <code>hostname</code>, <code>service</code>.</p>
<p>If <code>performanceEntry.name</code> is equal to <code>queryxxx</code> or <code>getHostByAddr</code>, the <code>detail</code> will
contain the following properties: <code>host</code>, <code>ttl</code>, <code>result</code>. The value of <code>result</code> is
same as the result of <code>queryxxx</code> or <code>getHostByAddr</code>.</p>
</section><section><h3>Class: <code>PerformanceNodeTiming</code><span><a class="mark" href="#all_perf_hooks_class-performancenodetiming" id="all_perf_hooks_class-performancenodetiming">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_class_performancenodetiming"></a></h3>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div>
<ul>
<li>Extends: <a href="#all_perf_hooks_class-performanceentry" class="type">&#x3C;PerformanceEntry></a></li>
</ul>
<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>
<h4><code>performanceNodeTiming.bootstrapComplete</code><span><a class="mark" href="#all_perf_hooks_performancenodetimingbootstrapcomplete" id="all_perf_hooks_performancenodetimingbootstrapcomplete">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performancenodetiming_bootstrapcomplete"></a></h4>
<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>
<h4><code>performanceNodeTiming.environment</code><span><a class="mark" href="#all_perf_hooks_performancenodetimingenvironment" id="all_perf_hooks_performancenodetimingenvironment">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performancenodetiming_environment"></a></h4>
<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>
<h4><code>performanceNodeTiming.idleTime</code><span><a class="mark" href="#all_perf_hooks_performancenodetimingidletime" id="all_perf_hooks_performancenodetimingidletime">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performancenodetiming_idletime"></a></h4>
<div class="api_metadata">
<span>Added in: v14.10.0, v12.19.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 of the amount of time the event loop
has been idle within the event loop's event provider (e.g. <code>epoll_wait</code>). This
does not take CPU usage into consideration. If the event loop has not yet
started (e.g., in the first tick of the main script), the property has the
value of 0.</p>
<h4><code>performanceNodeTiming.loopExit</code><span><a class="mark" href="#all_perf_hooks_performancenodetimingloopexit" id="all_perf_hooks_performancenodetimingloopexit">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performancenodetiming_loopexit"></a></h4>
<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="#all_process_event-exit"><code>'exit'</code></a> event.</p>
<h4><code>performanceNodeTiming.loopStart</code><span><a class="mark" href="#all_perf_hooks_performancenodetimingloopstart" id="all_perf_hooks_performancenodetimingloopstart">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performancenodetiming_loopstart"></a></h4>
<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>
<h4><code>performanceNodeTiming.nodeStart</code><span><a class="mark" href="#all_perf_hooks_performancenodetimingnodestart" id="all_perf_hooks_performancenodetimingnodestart">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performancenodetiming_nodestart"></a></h4>
<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>
<h4><code>performanceNodeTiming.uvMetricsInfo</code><span><a class="mark" href="#all_perf_hooks_performancenodetiminguvmetricsinfo" id="all_perf_hooks_performancenodetiminguvmetricsinfo">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performancenodetiming_uvmetricsinfo"></a></h4>
<div class="api_metadata">
<span>Added in: v20.18.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>
<ul>
<li><code>loopCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Number of event loop iterations.</li>
<li><code>events</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Number of events that have been processed by the event handler.</li>
<li><code>eventsWaiting</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Number of events that were waiting to be processed when the event provider was called.</li>
</ul>
</li>
</ul>
<p>This is a wrapper to the <code>uv_metrics_info</code> function.
It returns the current set of event loop metrics.</p>
<p>It is recommended to use this property inside a function whose execution was
scheduled using <code>setImmediate</code> to avoid collecting metrics before finishing all
operations scheduled during the current loop iteration.</p>

<pre class="with-51-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { performance } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:perf_hooks'</span>);

<span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(performance.<span class="hljs-property">nodeTiming</span>.<span class="hljs-property">uvMetricsInfo</span>);
});</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { performance } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:perf_hooks'</span>;

<span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(performance.<span class="hljs-property">nodeTiming</span>.<span class="hljs-property">uvMetricsInfo</span>);
});</code><button class="copy-button">copy</button></pre>
<h4><code>performanceNodeTiming.v8Start</code><span><a class="mark" href="#all_perf_hooks_performancenodetimingv8start" id="all_perf_hooks_performancenodetimingv8start">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performancenodetiming_v8start"></a></h4>
<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>
</section><section><h3>Class: <code>PerformanceResourceTiming</code><span><a class="mark" href="#all_perf_hooks_class-performanceresourcetiming" id="all_perf_hooks_class-performanceresourcetiming">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_class_performanceresourcetiming"></a></h3>
<div class="api_metadata">
<span>Added in: v18.2.0, v16.17.0</span>
</div>
<ul>
<li>Extends: <a href="#all_perf_hooks_class-performanceentry" class="type">&#x3C;PerformanceEntry></a></li>
</ul>
<p>Provides detailed network timing data regarding the loading of an application's
resources.</p>
<p>The constructor of this class is not exposed to users directly.</p>
<h4><code>performanceResourceTiming.workerStart</code><span><a class="mark" href="#all_perf_hooks_performanceresourcetimingworkerstart" id="all_perf_hooks_performanceresourcetimingworkerstart">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceresourcetiming_workerstart"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceResourceTiming</code> object as the receiver.</p></td></tr>
<tr><td>v18.2.0, v16.17.0</td>
<td><p><span>Added in: v18.2.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</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 immediately before dispatching
the <code>fetch</code> request. If the resource is not intercepted by a worker the property
will always return 0.</p>
<h4><code>performanceResourceTiming.redirectStart</code><span><a class="mark" href="#all_perf_hooks_performanceresourcetimingredirectstart" id="all_perf_hooks_performanceresourcetimingredirectstart">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceresourcetiming_redirectstart"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceResourceTiming</code> object as the receiver.</p></td></tr>
<tr><td>v18.2.0, v16.17.0</td>
<td><p><span>Added in: v18.2.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</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 that represents the start time
of the fetch which initiates the redirect.</p>
<h4><code>performanceResourceTiming.redirectEnd</code><span><a class="mark" href="#all_perf_hooks_performanceresourcetimingredirectend" id="all_perf_hooks_performanceresourcetimingredirectend">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceresourcetiming_redirectend"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceResourceTiming</code> object as the receiver.</p></td></tr>
<tr><td>v18.2.0, v16.17.0</td>
<td><p><span>Added in: v18.2.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</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 that will be created immediately after
receiving the last byte of the response of the last redirect.</p>
<h4><code>performanceResourceTiming.fetchStart</code><span><a class="mark" href="#all_perf_hooks_performanceresourcetimingfetchstart" id="all_perf_hooks_performanceresourcetimingfetchstart">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceresourcetiming_fetchstart"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceResourceTiming</code> object as the receiver.</p></td></tr>
<tr><td>v18.2.0, v16.17.0</td>
<td><p><span>Added in: v18.2.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</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 immediately before the Node.js starts
to fetch the resource.</p>
<h4><code>performanceResourceTiming.domainLookupStart</code><span><a class="mark" href="#all_perf_hooks_performanceresourcetimingdomainlookupstart" id="all_perf_hooks_performanceresourcetimingdomainlookupstart">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceresourcetiming_domainlookupstart"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceResourceTiming</code> object as the receiver.</p></td></tr>
<tr><td>v18.2.0, v16.17.0</td>
<td><p><span>Added in: v18.2.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</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 immediately before the Node.js starts
the domain name lookup for the resource.</p>
<h4><code>performanceResourceTiming.domainLookupEnd</code><span><a class="mark" href="#all_perf_hooks_performanceresourcetimingdomainlookupend" id="all_perf_hooks_performanceresourcetimingdomainlookupend">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceresourcetiming_domainlookupend"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceResourceTiming</code> object as the receiver.</p></td></tr>
<tr><td>v18.2.0, v16.17.0</td>
<td><p><span>Added in: v18.2.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</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 representing the time immediately
after the Node.js finished the domain name lookup for the resource.</p>
<h4><code>performanceResourceTiming.connectStart</code><span><a class="mark" href="#all_perf_hooks_performanceresourcetimingconnectstart" id="all_perf_hooks_performanceresourcetimingconnectstart">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceresourcetiming_connectstart"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceResourceTiming</code> object as the receiver.</p></td></tr>
<tr><td>v18.2.0, v16.17.0</td>
<td><p><span>Added in: v18.2.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</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 representing the time immediately
before Node.js starts to establish the connection to the server to retrieve
the resource.</p>
<h4><code>performanceResourceTiming.connectEnd</code><span><a class="mark" href="#all_perf_hooks_performanceresourcetimingconnectend" id="all_perf_hooks_performanceresourcetimingconnectend">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceresourcetiming_connectend"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceResourceTiming</code> object as the receiver.</p></td></tr>
<tr><td>v18.2.0, v16.17.0</td>
<td><p><span>Added in: v18.2.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</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 representing the time immediately
after Node.js finishes establishing the connection to the server to retrieve
the resource.</p>
<h4><code>performanceResourceTiming.secureConnectionStart</code><span><a class="mark" href="#all_perf_hooks_performanceresourcetimingsecureconnectionstart" id="all_perf_hooks_performanceresourcetimingsecureconnectionstart">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceresourcetiming_secureconnectionstart"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceResourceTiming</code> object as the receiver.</p></td></tr>
<tr><td>v18.2.0, v16.17.0</td>
<td><p><span>Added in: v18.2.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</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 representing the time immediately
before Node.js starts the handshake process to secure the current connection.</p>
<h4><code>performanceResourceTiming.requestStart</code><span><a class="mark" href="#all_perf_hooks_performanceresourcetimingrequeststart" id="all_perf_hooks_performanceresourcetimingrequeststart">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceresourcetiming_requeststart"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceResourceTiming</code> object as the receiver.</p></td></tr>
<tr><td>v18.2.0, v16.17.0</td>
<td><p><span>Added in: v18.2.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</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 representing the time immediately
before Node.js receives the first byte of the response from the server.</p>
<h4><code>performanceResourceTiming.responseEnd</code><span><a class="mark" href="#all_perf_hooks_performanceresourcetimingresponseend" id="all_perf_hooks_performanceresourcetimingresponseend">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceresourcetiming_responseend"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceResourceTiming</code> object as the receiver.</p></td></tr>
<tr><td>v18.2.0, v16.17.0</td>
<td><p><span>Added in: v18.2.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</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 representing the time immediately
after Node.js receives the last byte of the resource or immediately before
the transport connection is closed, whichever comes first.</p>
<h4><code>performanceResourceTiming.transferSize</code><span><a class="mark" href="#all_perf_hooks_performanceresourcetimingtransfersize" id="all_perf_hooks_performanceresourcetimingtransfersize">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceresourcetiming_transfersize"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceResourceTiming</code> object as the receiver.</p></td></tr>
<tr><td>v18.2.0, v16.17.0</td>
<td><p><span>Added in: v18.2.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</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>A number representing the size (in octets) of the fetched resource. The size
includes the response header fields plus the response payload body.</p>
<h4><code>performanceResourceTiming.encodedBodySize</code><span><a class="mark" href="#all_perf_hooks_performanceresourcetimingencodedbodysize" id="all_perf_hooks_performanceresourcetimingencodedbodysize">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceresourcetiming_encodedbodysize"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceResourceTiming</code> object as the receiver.</p></td></tr>
<tr><td>v18.2.0, v16.17.0</td>
<td><p><span>Added in: v18.2.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</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>A number representing the size (in octets) received from the fetch
(HTTP or cache), of the payload body, before removing any applied
content-codings.</p>
<h4><code>performanceResourceTiming.decodedBodySize</code><span><a class="mark" href="#all_perf_hooks_performanceresourcetimingdecodedbodysize" id="all_perf_hooks_performanceresourcetimingdecodedbodysize">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceresourcetiming_decodedbodysize"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>This property getter must be called with the <code>PerformanceResourceTiming</code> object as the receiver.</p></td></tr>
<tr><td>v18.2.0, v16.17.0</td>
<td><p><span>Added in: v18.2.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</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>A number representing the size (in octets) received from the fetch
(HTTP or cache), of the message body, after removing any applied
content-codings.</p>
<h4><code>performanceResourceTiming.toJSON()</code><span><a class="mark" href="#all_perf_hooks_performanceresourcetimingtojson" id="all_perf_hooks_performanceresourcetimingtojson">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceresourcetiming_tojson"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>This method must be called with the <code>PerformanceResourceTiming</code> object as the receiver.</p></td></tr>
<tr><td>v18.2.0, v16.17.0</td>
<td><p><span>Added in: v18.2.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Returns a <code>object</code> that is the JSON representation of the
<code>PerformanceResourceTiming</code> object</p>
</section><section><h3>Class: <code>PerformanceObserver</code><span><a class="mark" href="#all_perf_hooks_class-performanceobserver" id="all_perf_hooks_class-performanceobserver">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_class_performanceobserver"></a></h3>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div>
<h4><code>PerformanceObserver.supportedEntryTypes</code><span><a class="mark" href="#all_perf_hooks_performanceobserversupportedentrytypes" id="all_perf_hooks_performanceobserversupportedentrytypes">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceobserver_supportedentrytypes"></a></h4>
<div class="api_metadata">
<span>Added in: v16.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>Get supported types.</p>
<h4><code>new PerformanceObserver(callback)</code><span><a class="mark" href="#all_perf_hooks_new-performanceobservercallback" id="all_perf_hooks_new-performanceobservercallback">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_new_performanceobserver_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</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>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<ul>
<li><code>list</code> <a href="#all_perf_hooks_class-performanceobserverentrylist" class="type">&#x3C;PerformanceObserverEntryList></a></li>
<li><code>observer</code> <a href="#all_perf_hooks_class-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"><span class="hljs-keyword">const</span> {
  performance,
  <span class="hljs-title class_">PerformanceObserver</span>,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:perf_hooks'</span>);

<span class="hljs-keyword">const</span> obs = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PerformanceObserver</span>(<span class="hljs-function">(<span class="hljs-params">list, observer</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(list.<span class="hljs-title function_">getEntries</span>());

  performance.<span class="hljs-title function_">clearMarks</span>();
  performance.<span class="hljs-title function_">clearMeasures</span>();
  observer.<span class="hljs-title function_">disconnect</span>();
});
obs.<span class="hljs-title function_">observe</span>({ <span class="hljs-attr">entryTypes</span>: [<span class="hljs-string">'mark'</span>], <span class="hljs-attr">buffered</span>: <span class="hljs-literal">true</span> });

performance.<span class="hljs-title function_">mark</span>(<span class="hljs-string">'test'</span>);</code> <button class="copy-button">copy</button></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>
<h4><code>performanceObserver.disconnect()</code><span><a class="mark" href="#all_perf_hooks_performanceobserverdisconnect" id="all_perf_hooks_performanceobserverdisconnect">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceobserver_disconnect"></a></h4>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div>
<p>Disconnects the <code>PerformanceObserver</code> instance from all notifications.</p>
<h4><code>performanceObserver.observe(options)</code><span><a class="mark" href="#all_perf_hooks_performanceobserverobserveoptions" id="all_perf_hooks_performanceobserverobserveoptions">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceobserver_observe_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.7.0</td>
<td><p>Updated to conform to Performance Timeline Level 2. The buffered option has been added back.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p>Updated to conform to User Timing Level 3. The buffered option has been removed.</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>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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> A single <a href="#all_perf_hooks_class-performanceentry" class="type">&#x3C;PerformanceEntry></a> type. Must not be given
if <code>entryTypes</code> is already specified.</li>
<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
<a href="#all_perf_hooks_class-performanceentry" class="type">&#x3C;PerformanceEntry></a> 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 observer callback is called with a
list global <code>PerformanceEntry</code> buffered entries. If false, only
<code>PerformanceEntry</code>s created after the time point are sent to the
observer callback. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
</ul>
<p>Subscribes the <a href="#all_perf_hooks_class-performanceobserver" class="type">&#x3C;PerformanceObserver></a> instance to notifications of new
<a href="#all_perf_hooks_class-performanceentry" class="type">&#x3C;PerformanceEntry></a> instances identified either by <code>options.entryTypes</code>
or <code>options.type</code>:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> {
  performance,
  <span class="hljs-title class_">PerformanceObserver</span>,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:perf_hooks'</span>);

<span class="hljs-keyword">const</span> obs = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PerformanceObserver</span>(<span class="hljs-function">(<span class="hljs-params">list, observer</span>) =></span> {
  <span class="hljs-comment">// Called once asynchronously. `list` contains three items.</span>
});
obs.<span class="hljs-title function_">observe</span>({ <span class="hljs-attr">type</span>: <span class="hljs-string">'mark'</span> });

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> n = <span class="hljs-number">0</span>; n &#x3C; <span class="hljs-number">3</span>; n++)
  performance.<span class="hljs-title function_">mark</span>(<span class="hljs-string">`test<span class="hljs-subst">${n}</span>`</span>);</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>PerformanceObserverEntryList</code><span><a class="mark" href="#all_perf_hooks_class-performanceobserverentrylist" id="all_perf_hooks_class-performanceobserverentrylist">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_class_performanceobserverentrylist"></a></h3>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div>
<p>The <code>PerformanceObserverEntryList</code> class is used to provide access to the
<code>PerformanceEntry</code> instances passed to a <code>PerformanceObserver</code>.
The constructor of this class is not exposed to users.</p>
<h4><code>performanceObserverEntryList.getEntries()</code><span><a class="mark" href="#all_perf_hooks_performanceobserverentrylistgetentries" id="all_perf_hooks_performanceobserverentrylistgetentries">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceobserverentrylist_getentries"></a></h4>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div>
<ul>
<li>Returns: <a href="#all_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>
<pre><code class="language-js"><span class="hljs-keyword">const</span> {
  performance,
  <span class="hljs-title class_">PerformanceObserver</span>,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:perf_hooks'</span>);

<span class="hljs-keyword">const</span> obs = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PerformanceObserver</span>(<span class="hljs-function">(<span class="hljs-params">perfObserverList, observer</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(perfObserverList.<span class="hljs-title function_">getEntries</span>());
  <span class="hljs-comment">/**
   * [
   *   PerformanceEntry {
   *     name: 'test',
   *     entryType: 'mark',
   *     startTime: 81.465639,
   *     duration: 0,
   *     detail: null
   *   },
   *   PerformanceEntry {
   *     name: 'meow',
   *     entryType: 'mark',
   *     startTime: 81.860064,
   *     duration: 0,
   *     detail: null
   *   }
   * ]
   */</span>

  performance.<span class="hljs-title function_">clearMarks</span>();
  performance.<span class="hljs-title function_">clearMeasures</span>();
  observer.<span class="hljs-title function_">disconnect</span>();
});
obs.<span class="hljs-title function_">observe</span>({ <span class="hljs-attr">type</span>: <span class="hljs-string">'mark'</span> });

performance.<span class="hljs-title function_">mark</span>(<span class="hljs-string">'test'</span>);
performance.<span class="hljs-title function_">mark</span>(<span class="hljs-string">'meow'</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>performanceObserverEntryList.getEntriesByName(name[, type])</code><span><a class="mark" href="#all_perf_hooks_performanceobserverentrylistgetentriesbynamename-type" id="all_perf_hooks_performanceobserverentrylistgetentriesbynamename-type">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceobserverentrylist_getentriesbyname_name_type"></a></h4>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#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="#all_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>
<pre><code class="language-js"><span class="hljs-keyword">const</span> {
  performance,
  <span class="hljs-title class_">PerformanceObserver</span>,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:perf_hooks'</span>);

<span class="hljs-keyword">const</span> obs = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PerformanceObserver</span>(<span class="hljs-function">(<span class="hljs-params">perfObserverList, observer</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(perfObserverList.<span class="hljs-title function_">getEntriesByName</span>(<span class="hljs-string">'meow'</span>));
  <span class="hljs-comment">/**
   * [
   *   PerformanceEntry {
   *     name: 'meow',
   *     entryType: 'mark',
   *     startTime: 98.545991,
   *     duration: 0,
   *     detail: null
   *   }
   * ]
   */</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(perfObserverList.<span class="hljs-title function_">getEntriesByName</span>(<span class="hljs-string">'nope'</span>)); <span class="hljs-comment">// []</span>

  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(perfObserverList.<span class="hljs-title function_">getEntriesByName</span>(<span class="hljs-string">'test'</span>, <span class="hljs-string">'mark'</span>));
  <span class="hljs-comment">/**
   * [
   *   PerformanceEntry {
   *     name: 'test',
   *     entryType: 'mark',
   *     startTime: 63.518931,
   *     duration: 0,
   *     detail: null
   *   }
   * ]
   */</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(perfObserverList.<span class="hljs-title function_">getEntriesByName</span>(<span class="hljs-string">'test'</span>, <span class="hljs-string">'measure'</span>)); <span class="hljs-comment">// []</span>

  performance.<span class="hljs-title function_">clearMarks</span>();
  performance.<span class="hljs-title function_">clearMeasures</span>();
  observer.<span class="hljs-title function_">disconnect</span>();
});
obs.<span class="hljs-title function_">observe</span>({ <span class="hljs-attr">entryTypes</span>: [<span class="hljs-string">'mark'</span>, <span class="hljs-string">'measure'</span>] });

performance.<span class="hljs-title function_">mark</span>(<span class="hljs-string">'test'</span>);
performance.<span class="hljs-title function_">mark</span>(<span class="hljs-string">'meow'</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>performanceObserverEntryList.getEntriesByType(type)</code><span><a class="mark" href="#all_perf_hooks_performanceobserverentrylistgetentriesbytypetype" id="all_perf_hooks_performanceobserverentrylistgetentriesbytypetype">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_performanceobserverentrylist_getentriesbytype_type"></a></h4>
<div class="api_metadata">
<span>Added in: v8.5.0</span>
</div>
<ul>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li>Returns: <a href="#all_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>
<pre><code class="language-js"><span class="hljs-keyword">const</span> {
  performance,
  <span class="hljs-title class_">PerformanceObserver</span>,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:perf_hooks'</span>);

<span class="hljs-keyword">const</span> obs = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PerformanceObserver</span>(<span class="hljs-function">(<span class="hljs-params">perfObserverList, observer</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(perfObserverList.<span class="hljs-title function_">getEntriesByType</span>(<span class="hljs-string">'mark'</span>));
  <span class="hljs-comment">/**
   * [
   *   PerformanceEntry {
   *     name: 'test',
   *     entryType: 'mark',
   *     startTime: 55.897834,
   *     duration: 0,
   *     detail: null
   *   },
   *   PerformanceEntry {
   *     name: 'meow',
   *     entryType: 'mark',
   *     startTime: 56.350146,
   *     duration: 0,
   *     detail: null
   *   }
   * ]
   */</span>
  performance.<span class="hljs-title function_">clearMarks</span>();
  performance.<span class="hljs-title function_">clearMeasures</span>();
  observer.<span class="hljs-title function_">disconnect</span>();
});
obs.<span class="hljs-title function_">observe</span>({ <span class="hljs-attr">type</span>: <span class="hljs-string">'mark'</span> });

performance.<span class="hljs-title function_">mark</span>(<span class="hljs-string">'test'</span>);
performance.<span class="hljs-title function_">mark</span>(<span class="hljs-string">'meow'</span>);</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>perf_hooks.createHistogram([options])</code><span><a class="mark" href="#all_perf_hooks_perf_hookscreatehistogramoptions" id="all_perf_hooks_perf_hookscreatehistogramoptions">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_perf_hooks_createhistogram_options"></a></h3>
<div class="api_metadata">
<span>Added in: v15.9.0, v14.18.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>
<ul>
<li><code>lowest</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/BigInt" class="type">&#x3C;bigint></a> The lowest discernible value. Must be an integer
value greater than 0. <strong>Default:</strong> <code>1</code>.</li>
<li><code>highest</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/BigInt" class="type">&#x3C;bigint></a> The highest recordable value. Must be an integer
value that is equal to or greater than two times <code>lowest</code>.
<strong>Default:</strong> <code>Number.MAX_SAFE_INTEGER</code>.</li>
<li><code>figures</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The number of accuracy digits. Must be a number between
<code>1</code> and <code>5</code>. <strong>Default:</strong> <code>3</code>.</li>
</ul>
</li>
<li>Returns: <a href="#all_perf_hooks_class-recordablehistogram-extends-histogram" class="type">&#x3C;RecordableHistogram></a></li>
</ul>
<p>Returns a <a href="#all_perf_hooks_class-recordablehistogram-extends-histogram" class="type">&#x3C;RecordableHistogram></a>.</p>
</section><section><h3><code>perf_hooks.monitorEventLoopDelay([options])</code><span><a class="mark" href="#all_perf_hooks_perf_hooksmonitoreventloopdelayoptions" id="all_perf_hooks_perf_hooksmonitoreventloopdelayoptions">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_perf_hooks_monitoreventloopdelay_options"></a></h3>
<div class="api_metadata">
<span>Added in: v11.10.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>
<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="#all_perf_hooks_class-intervalhistogram-extends-histogram" class="type">&#x3C;IntervalHistogram></a></li>
</ul>
<p><em>This property is an extension by Node.js. It is not available in Web browsers.</em></p>
<p>Creates an <code>IntervalHistogram</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"><span class="hljs-keyword">const</span> { monitorEventLoopDelay } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:perf_hooks'</span>);
<span class="hljs-keyword">const</span> h = <span class="hljs-title function_">monitorEventLoopDelay</span>({ <span class="hljs-attr">resolution</span>: <span class="hljs-number">20</span> });
h.<span class="hljs-title function_">enable</span>();
<span class="hljs-comment">// Do something.</span>
h.<span class="hljs-title function_">disable</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(h.<span class="hljs-property">min</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(h.<span class="hljs-property">max</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(h.<span class="hljs-property">mean</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(h.<span class="hljs-property">stddev</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(h.<span class="hljs-property">percentiles</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(h.<span class="hljs-title function_">percentile</span>(<span class="hljs-number">50</span>));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(h.<span class="hljs-title function_">percentile</span>(<span class="hljs-number">99</span>));</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>Histogram</code><span><a class="mark" href="#all_perf_hooks_class-histogram" id="all_perf_hooks_class-histogram">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_class_histogram"></a></h3>
<div class="api_metadata">
<span>Added in: v11.10.0</span>
</div>
<h4><code>histogram.count</code><span><a class="mark" href="#all_perf_hooks_histogramcount" id="all_perf_hooks_histogramcount">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_histogram_count"></a></h4>
<div class="api_metadata">
<span>Added in: v17.4.0, v16.14.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 samples recorded by the histogram.</p>
<h4><code>histogram.countBigInt</code><span><a class="mark" href="#all_perf_hooks_histogramcountbigint" id="all_perf_hooks_histogramcountbigint">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_histogram_countbigint"></a></h4>
<div class="api_metadata">
<span>Added in: v17.4.0, v16.14.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>The number of samples recorded by the histogram.</p>
<h4><code>histogram.exceeds</code><span><a class="mark" href="#all_perf_hooks_histogramexceeds" id="all_perf_hooks_histogramexceeds">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_histogram_exceeds"></a></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.exceedsBigInt</code><span><a class="mark" href="#all_perf_hooks_histogramexceedsbigint" id="all_perf_hooks_histogramexceedsbigint">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_histogram_exceedsbigint"></a></h4>
<div class="api_metadata">
<span>Added in: v17.4.0, v16.14.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>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="#all_perf_hooks_histogrammax" id="all_perf_hooks_histogrammax">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_histogram_max"></a></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.maxBigInt</code><span><a class="mark" href="#all_perf_hooks_histogrammaxbigint" id="all_perf_hooks_histogrammaxbigint">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_histogram_maxbigint"></a></h4>
<div class="api_metadata">
<span>Added in: v17.4.0, v16.14.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>The maximum recorded event loop delay.</p>
<h4><code>histogram.mean</code><span><a class="mark" href="#all_perf_hooks_histogrammean" id="all_perf_hooks_histogrammean">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_histogram_mean"></a></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="#all_perf_hooks_histogrammin" id="all_perf_hooks_histogrammin">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_histogram_min"></a></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.minBigInt</code><span><a class="mark" href="#all_perf_hooks_histogramminbigint" id="all_perf_hooks_histogramminbigint">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_histogram_minbigint"></a></h4>
<div class="api_metadata">
<span>Added in: v17.4.0, v16.14.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>The minimum recorded event loop delay.</p>
<h4><code>histogram.percentile(percentile)</code><span><a class="mark" href="#all_perf_hooks_histogrampercentilepercentile" id="all_perf_hooks_histogrampercentilepercentile">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_histogram_percentile_percentile"></a></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 in the range (0, 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.percentileBigInt(percentile)</code><span><a class="mark" href="#all_perf_hooks_histogrampercentilebigintpercentile" id="all_perf_hooks_histogrampercentilebigintpercentile">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_histogram_percentilebigint_percentile"></a></h4>
<div class="api_metadata">
<span>Added in: v17.4.0, v16.14.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 in the range (0, 100].</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>Returns the value at the given percentile.</p>
<h4><code>histogram.percentiles</code><span><a class="mark" href="#all_perf_hooks_histogrampercentiles" id="all_perf_hooks_histogrampercentiles">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_histogram_percentiles"></a></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.percentilesBigInt</code><span><a class="mark" href="#all_perf_hooks_histogrampercentilesbigint" id="all_perf_hooks_histogrampercentilesbigint">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_histogram_percentilesbigint"></a></h4>
<div class="api_metadata">
<span>Added in: v17.4.0, v16.14.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="#all_perf_hooks_histogramreset" id="all_perf_hooks_histogramreset">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_histogram_reset"></a></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="#all_perf_hooks_histogramstddev" id="all_perf_hooks_histogramstddev">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_histogram_stddev"></a></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>
</section><section><h3>Class: <code>IntervalHistogram extends Histogram</code><span><a class="mark" href="#all_perf_hooks_class-intervalhistogram-extends-histogram" id="all_perf_hooks_class-intervalhistogram-extends-histogram">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_class_intervalhistogram_extends_histogram"></a></h3>
<p>A <code>Histogram</code> that is periodically updated on a given interval.</p>
<h4><code>histogram.disable()</code><span><a class="mark" href="#all_perf_hooks_histogramdisable" id="all_perf_hooks_histogramdisable">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_histogram_disable"></a></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 update interval 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="#all_perf_hooks_histogramenable" id="all_perf_hooks_histogramenable">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_histogram_enable"></a></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 update interval timer. Returns <code>true</code> if the timer was
started, <code>false</code> if it was already started.</p>
<h4>Cloning an <code>IntervalHistogram</code><span><a class="mark" href="#all_perf_hooks_cloning-an-intervalhistogram" id="all_perf_hooks_cloning-an-intervalhistogram">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_cloning_an_intervalhistogram"></a></h4>
<p><a href="#all_perf_hooks_class-intervalhistogram-extends-histogram" class="type">&#x3C;IntervalHistogram></a> instances can be cloned via <a href="#all_worker_threads_class-messageport" class="type">&#x3C;MessagePort></a>. On the receiving
end, the histogram is cloned as a plain <a href="#all_perf_hooks_class-histogram" class="type">&#x3C;Histogram></a> object that does not
implement the <code>enable()</code> and <code>disable()</code> methods.</p>
</section><section><h3>Class: <code>RecordableHistogram extends Histogram</code><span><a class="mark" href="#all_perf_hooks_class-recordablehistogram-extends-histogram" id="all_perf_hooks_class-recordablehistogram-extends-histogram">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_class_recordablehistogram_extends_histogram"></a></h3>
<div class="api_metadata">
<span>Added in: v15.9.0, v14.18.0</span>
</div>
<h4><code>histogram.add(other)</code><span><a class="mark" href="#all_perf_hooks_histogramaddother" id="all_perf_hooks_histogramaddother">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_histogram_add_other"></a></h4>
<div class="api_metadata">
<span>Added in: v17.4.0, v16.14.0</span>
</div>
<ul>
<li><code>other</code> <a href="#all_perf_hooks_class-recordablehistogram-extends-histogram" class="type">&#x3C;RecordableHistogram></a></li>
</ul>
<p>Adds the values from <code>other</code> to this histogram.</p>
<h4><code>histogram.record(val)</code><span><a class="mark" href="#all_perf_hooks_histogramrecordval" id="all_perf_hooks_histogramrecordval">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_histogram_record_val"></a></h4>
<div class="api_metadata">
<span>Added in: v15.9.0, v14.18.0</span>
</div>
<ul>
<li><code>val</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/BigInt" class="type">&#x3C;bigint></a> The amount to record in the histogram.</li>
</ul>
<h4><code>histogram.recordDelta()</code><span><a class="mark" href="#all_perf_hooks_histogramrecorddelta" id="all_perf_hooks_histogramrecorddelta">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_histogram_recorddelta"></a></h4>
<div class="api_metadata">
<span>Added in: v15.9.0, v14.18.0</span>
</div>
<p>Calculates the amount of time (in nanoseconds) that has passed since the
previous call to <code>recordDelta()</code> and records that amount in the histogram.</p>
</section><section><h3>Examples<span><a class="mark" href="#all_perf_hooks_examples" id="all_perf_hooks_examples">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_examples"></a></h3>
<h4>Measuring the duration of async operations<span><a class="mark" href="#all_perf_hooks_measuring-the-duration-of-async-operations" id="all_perf_hooks_measuring-the-duration-of-async-operations">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_measuring_the_duration_of_async_operations"></a></h4>
<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"><span class="hljs-meta">'use strict'</span>;
<span class="hljs-keyword">const</span> async_hooks = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:async_hooks'</span>);
<span class="hljs-keyword">const</span> {
  performance,
  <span class="hljs-title class_">PerformanceObserver</span>,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:perf_hooks'</span>);

<span class="hljs-keyword">const</span> set = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Set</span>();
<span class="hljs-keyword">const</span> hook = async_hooks.<span class="hljs-title function_">createHook</span>({
  <span class="hljs-title function_">init</span>(<span class="hljs-params">id, type</span>) {
    <span class="hljs-keyword">if</span> (type === <span class="hljs-string">'Timeout'</span>) {
      performance.<span class="hljs-title function_">mark</span>(<span class="hljs-string">`Timeout-<span class="hljs-subst">${id}</span>-Init`</span>);
      set.<span class="hljs-title function_">add</span>(id);
    }
  },
  <span class="hljs-title function_">destroy</span>(<span class="hljs-params">id</span>) {
    <span class="hljs-keyword">if</span> (set.<span class="hljs-title function_">has</span>(id)) {
      set.<span class="hljs-title function_">delete</span>(id);
      performance.<span class="hljs-title function_">mark</span>(<span class="hljs-string">`Timeout-<span class="hljs-subst">${id}</span>-Destroy`</span>);
      performance.<span class="hljs-title function_">measure</span>(<span class="hljs-string">`Timeout-<span class="hljs-subst">${id}</span>`</span>,
                          <span class="hljs-string">`Timeout-<span class="hljs-subst">${id}</span>-Init`</span>,
                          <span class="hljs-string">`Timeout-<span class="hljs-subst">${id}</span>-Destroy`</span>);
    }
  },
});
hook.<span class="hljs-title function_">enable</span>();

<span class="hljs-keyword">const</span> obs = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PerformanceObserver</span>(<span class="hljs-function">(<span class="hljs-params">list, observer</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(list.<span class="hljs-title function_">getEntries</span>()[<span class="hljs-number">0</span>]);
  performance.<span class="hljs-title function_">clearMarks</span>();
  performance.<span class="hljs-title function_">clearMeasures</span>();
  observer.<span class="hljs-title function_">disconnect</span>();
});
obs.<span class="hljs-title function_">observe</span>({ <span class="hljs-attr">entryTypes</span>: [<span class="hljs-string">'measure'</span>], <span class="hljs-attr">buffered</span>: <span class="hljs-literal">true</span> });

<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {}, <span class="hljs-number">1000</span>);</code> <button class="copy-button">copy</button></pre>
<h4>Measuring how long it takes to load dependencies<span><a class="mark" href="#all_perf_hooks_measuring-how-long-it-takes-to-load-dependencies" id="all_perf_hooks_measuring-how-long-it-takes-to-load-dependencies">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_measuring_how_long_it_takes_to_load_dependencies"></a></h4>
<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"><span class="hljs-meta">'use strict'</span>;
<span class="hljs-keyword">const</span> {
  performance,
  <span class="hljs-title class_">PerformanceObserver</span>,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:perf_hooks'</span>);
<span class="hljs-keyword">const</span> mod = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>);

<span class="hljs-comment">// Monkey patch the require function</span>
mod.<span class="hljs-property">Module</span>.<span class="hljs-property"><span class="hljs-keyword">prototype</span></span>.<span class="hljs-property">require</span> =
  performance.<span class="hljs-title function_">timerify</span>(mod.<span class="hljs-property">Module</span>.<span class="hljs-property"><span class="hljs-keyword">prototype</span></span>.<span class="hljs-property">require</span>);
<span class="hljs-built_in">require</span> = performance.<span class="hljs-title function_">timerify</span>(<span class="hljs-built_in">require</span>);

<span class="hljs-comment">// Activate the observer</span>
<span class="hljs-keyword">const</span> obs = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PerformanceObserver</span>(<span class="hljs-function">(<span class="hljs-params">list</span>) =></span> {
  <span class="hljs-keyword">const</span> entries = list.<span class="hljs-title function_">getEntries</span>();
  entries.<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">entry</span>) =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`require('<span class="hljs-subst">${entry[<span class="hljs-number">0</span>]}</span>')`</span>, entry.<span class="hljs-property">duration</span>);
  });
  performance.<span class="hljs-title function_">clearMarks</span>();
  performance.<span class="hljs-title function_">clearMeasures</span>();
  obs.<span class="hljs-title function_">disconnect</span>();
});
obs.<span class="hljs-title function_">observe</span>({ <span class="hljs-attr">entryTypes</span>: [<span class="hljs-string">'function'</span>], <span class="hljs-attr">buffered</span>: <span class="hljs-literal">true</span> });

<span class="hljs-built_in">require</span>(<span class="hljs-string">'some-module'</span>);</code> <button class="copy-button">copy</button></pre>
<h4>Measuring how long one HTTP round-trip takes<span><a class="mark" href="#all_perf_hooks_measuring-how-long-one-http-round-trip-takes" id="all_perf_hooks_measuring-how-long-one-http-round-trip-takes">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_measuring_how_long_one_http_round_trip_takes"></a></h4>
<p>The following example is used to trace the time spent by HTTP client
(<code>OutgoingMessage</code>) and HTTP request (<code>IncomingMessage</code>). For HTTP client,
it means the time interval between starting the request and receiving the
response, and for HTTP request, it means the time interval between receiving
the request and sending the response:</p>
<pre><code class="language-js"><span class="hljs-meta">'use strict'</span>;
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">PerformanceObserver</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:perf_hooks'</span>);
<span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);

<span class="hljs-keyword">const</span> obs = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PerformanceObserver</span>(<span class="hljs-function">(<span class="hljs-params">items</span>) =></span> {
  items.<span class="hljs-title function_">getEntries</span>().<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">item</span>) =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(item);
  });
});

obs.<span class="hljs-title function_">observe</span>({ <span class="hljs-attr">entryTypes</span>: [<span class="hljs-string">'http'</span>] });

<span class="hljs-keyword">const</span> <span class="hljs-variable constant_">PORT</span> = <span class="hljs-number">8080</span>;

http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
  res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'ok'</span>);
}).<span class="hljs-title function_">listen</span>(<span class="hljs-variable constant_">PORT</span>, <span class="hljs-function">() =></span> {
  http.<span class="hljs-title function_">get</span>(<span class="hljs-string">`http://127.0.0.1:<span class="hljs-subst">${PORT}</span>`</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4>Measuring how long the <code>net.connect</code> (only for TCP) takes when the connection is successful<span><a class="mark" href="#all_perf_hooks_measuring-how-long-the-netconnect-only-for-tcp-takes-when-the-connection-is-successful" id="all_perf_hooks_measuring-how-long-the-netconnect-only-for-tcp-takes-when-the-connection-is-successful">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_measuring_how_long_the_net_connect_only_for_tcp_takes_when_the_connection_is_successful"></a></h4>
<pre><code class="language-js"><span class="hljs-meta">'use strict'</span>;
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">PerformanceObserver</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:perf_hooks'</span>);
<span class="hljs-keyword">const</span> net = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:net'</span>);
<span class="hljs-keyword">const</span> obs = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PerformanceObserver</span>(<span class="hljs-function">(<span class="hljs-params">items</span>) =></span> {
  items.<span class="hljs-title function_">getEntries</span>().<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">item</span>) =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(item);
  });
});
obs.<span class="hljs-title function_">observe</span>({ <span class="hljs-attr">entryTypes</span>: [<span class="hljs-string">'net'</span>] });
<span class="hljs-keyword">const</span> <span class="hljs-variable constant_">PORT</span> = <span class="hljs-number">8080</span>;
net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">socket</span>) =></span> {
  socket.<span class="hljs-title function_">destroy</span>();
}).<span class="hljs-title function_">listen</span>(<span class="hljs-variable constant_">PORT</span>, <span class="hljs-function">() =></span> {
  net.<span class="hljs-title function_">connect</span>(<span class="hljs-variable constant_">PORT</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4>Measuring how long the DNS takes when the request is successful<span><a class="mark" href="#all_perf_hooks_measuring-how-long-the-dns-takes-when-the-request-is-successful" id="all_perf_hooks_measuring-how-long-the-dns-takes-when-the-request-is-successful">#</a></span><a aria-hidden="true" class="legacy" id="perf_hooks_measuring_how_long_the_dns_takes_when_the_request_is_successful"></a></h4>
<pre><code class="language-js"><span class="hljs-meta">'use strict'</span>;
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">PerformanceObserver</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:perf_hooks'</span>);
<span class="hljs-keyword">const</span> dns = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:dns'</span>);
<span class="hljs-keyword">const</span> obs = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PerformanceObserver</span>(<span class="hljs-function">(<span class="hljs-params">items</span>) =></span> {
  items.<span class="hljs-title function_">getEntries</span>().<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">item</span>) =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(item);
  });
});
obs.<span class="hljs-title function_">observe</span>({ <span class="hljs-attr">entryTypes</span>: [<span class="hljs-string">'dns'</span>] });
dns.<span class="hljs-title function_">lookup</span>(<span class="hljs-string">'localhost'</span>, <span class="hljs-function">() =></span> {});
dns.<span class="hljs-property">promises</span>.<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'localhost'</span>);</code> <button class="copy-button">copy</button></pre></section>
        </section>
<section><h2>Permissions<span><a class="mark" href="#all_permissions_permissions" id="all_permissions_permissions">#</a></span><a aria-hidden="true" class="legacy" id="permissions_permissions"></a></h2>
<p>Permissions can be used to control what system resources the
Node.js process has access to or what actions the process can take
with those resources. Permissions can also control what modules can
be accessed by other modules.</p>
<ul>
<li>
<p><a href="#all_permissions_module-based-permissions">Module-based permissions</a> control which files
or URLs are available to other modules during application execution.
This can be used to control what modules can be accessed by third-party
dependencies, for example.</p>
</li>
<li>
<p><a href="#all_permissions_process-based-permissions">Process-based permissions</a> control the Node.js
process's access to resources.
The resource can be entirely allowed or denied, or actions related to it can
be controlled. For example, file system reads can be allowed while denying
writes.
This feature does not protect against malicious code. According to the Node.js
<a href="https://github.com/nodejs/node/blob/main/SECURITY.md">Security Policy</a>, Node.js trusts any code it is asked to run.</p>
</li>
</ul>
<p>The permission model implements a "seat belt" approach, which prevents trusted
code from unintentionally changing files or using resources that access has
not explicitly been granted to. It does not provide security guarantees in the
presence of malicious code. Malicious code can bypass the permission model and
execute arbitrary code without the restrictions imposed by the permission
model.</p>
<p>If you find a potential security vulnerability, please refer to our
<a href="https://github.com/nodejs/node/blob/main/SECURITY.md">Security Policy</a>.</p>
<section><h3>Module-based permissions<span><a class="mark" href="#all_permissions_module-based-permissions" id="all_permissions_module-based-permissions">#</a></span><a aria-hidden="true" class="legacy" id="permissions_module_based_permissions"></a></h3>
<h4>Policies<span><a class="mark" href="#all_permissions_policies" id="all_permissions_policies">#</a></span><a aria-hidden="true" class="legacy" id="permissions_policies"></a></h4>


<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Will be removed shortly</div><p></p>

<p>Node.js contains experimental support for creating policies on loading code.</p>
<p>Policies are a security feature intended to ensure the integrity
of the loaded code.</p>
<p>While it does not function as a provenance mechanism to trace the origin of
code, it serves as a robust defense against the execution of malicious code.
Unlike runtime-based models that may restrict capabilities once the code is
loaded, Node.js policies focus on preventing malicious code from ever being
fully loaded into the application in the first place.</p>
<p>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>
<h5>Enabling<span><a class="mark" href="#all_permissions_enabling" id="all_permissions_enabling">#</a></span><a aria-hidden="true" class="legacy" id="permissions_enabling"></a></h5>

<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> <button class="copy-button">copy</button></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=<span class="hljs-string">"sha384-SggXRQHwCG8g+DktYYzxkXRIkTiEYWBHqev0xnpCxYlqMBufKZHAHQM3/boDaI/0"</span> app.js</code> <button class="copy-button">copy</button></pre>
<h5>Features<span><a class="mark" href="#all_permissions_features" id="all_permissions_features">#</a></span><a aria-hidden="true" class="legacy" id="permissions_features"></a></h5>
<h6>Error behavior<span><a class="mark" href="#all_permissions_error-behavior" id="all_permissions_error-behavior">#</a></span><a aria-hidden="true" class="legacy" id="permissions_error_behavior"></a></h6>
<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"><span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"onerror"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"log"</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"resources"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"./app/checked.js"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"integrity"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"sha384-SggXRQHwCG8g+DktYYzxkXRIkTiEYWBHqev0xnpCxYlqMBufKZHAHQM3/boDaI/0"</span>
    <span class="hljs-punctuation">}</span>
  <span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<h6>Integrity checks<span><a class="mark" href="#all_permissions_integrity-checks" id="all_permissions_integrity-checks">#</a></span><a aria-hidden="true" class="legacy" id="permissions_integrity_checks"></a></h6>
<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> or <code>import</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"><span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"resources"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"./app/checked.js"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"integrity"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"sha384-SggXRQHwCG8g+DktYYzxkXRIkTiEYWBHqev0xnpCxYlqMBufKZHAHQM3/boDaI/0"</span>
    <span class="hljs-punctuation">}</span>
  <span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></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>node -e 'process.stdout.write("sha256-");process.stdin.pipe(crypto.createHash("sha256").setEncoding("base64")).pipe(process.stdout)' &#x3C; FILE</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>
<h6>Dependency redirection<span><a class="mark" href="#all_permissions_dependency-redirection" id="all_permissions_dependency-redirection">#</a></span><a aria-hidden="true" class="legacy" id="permissions_dependency_redirection"></a></h6>
<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"><span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"resources"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"./app/checked.js"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"dependencies"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
        <span class="hljs-attr">"fs"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"os"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./app/node_modules/alt-os"</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"http"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span> <span class="hljs-attr">"import"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span> <span class="hljs-punctuation">}</span>
      <span class="hljs-punctuation">}</span>
    <span class="hljs-punctuation">}</span>
  <span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>The dependencies are keyed by the requested specifier string and have values
of either <code>true</code>, <code>null</code>, a string pointing to a module to be resolved,
or a conditions object.</p>
<p>The specifier string does not perform any searching and must match exactly what
is provided to the <code>require()</code> or <code>import</code> except for a canonicalization step.
Therefore, multiple specifiers may be needed in the policy if it uses multiple
different strings to point to the same module (such as excluding the extension).</p>
<p>Specifier strings are canonicalized but not resolved prior to be used for
matching in order to have some compatibility with import maps, for example if a
resource <code>file:///C:/app/utils.js</code> was given the following redirection from a
policy located at <code>file:///C:/app/policy.json</code>:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"resources"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"file:///C:/app/utils.js"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"dependencies"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
        <span class="hljs-attr">"./utils.js"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./utils-v2.js"</span>
      <span class="hljs-punctuation">}</span>
    <span class="hljs-punctuation">}</span>
  <span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>Any specifier used to load <code>file:///C:/app/utils.js</code> would then be intercepted
and redirected to <code>file:///C:/app/utils-v2.js</code> instead regardless of using an
absolute or relative specifier. However, if a specifier that is not an absolute
or relative URL string is used, it would not be intercepted. So, if an import
such as <code>import('#utils')</code> was used, it would not be intercepted.</p>
<p>If the value of the redirection is <code>true</code>, a "dependencies" field at the top of
the policy file will be used. If that field at the top of the policy file is
<code>true</code> the default node searching algorithms are used to find the module.</p>
<p>If the value of the redirection is a string, it is resolved relative to
the manifest and then immediately used without searching.</p>
<p>Any specifier string for which resolution is attempted and that is not listed in
the dependencies results in an error according to the policy.</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>
<p>Similar to <code>"exports"</code> in <code>package.json</code>, dependencies can also be specified to
be objects containing conditions which branch how dependencies are loaded. In
the preceding example, <code>"http"</code> is allowed when the <code>"import"</code> condition is
part of loading it.</p>
<p>A value of <code>null</code> for the resolved value causes the resolution to fail. This
can be used to ensure some kinds of dynamic access are explicitly prevented.</p>
<p>Unknown values for the resolved module location cause failures but are
not guaranteed to be forward compatible.</p>
<p>All the guarantees for policy redirection are specified in the
<a href="#all_permissions_guarantees">Guarantees</a> section.</p>
<h6>Example: Patched dependency<span><a class="mark" href="#all_permissions_example-patched-dependency" id="all_permissions_example-patched-dependency">#</a></span><a aria-hidden="true" class="legacy" id="permissions_example_patched_dependency"></a></h6>
<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"><span class="hljs-keyword">const</span> original = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fn'</span>);
<span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = <span class="hljs-keyword">function</span> <span class="hljs-title function_">fn</span>(<span class="hljs-params">...args</span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">time</span>();
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span>.<span class="hljs-property">target</span> ?
      <span class="hljs-title class_">Reflect</span>.<span class="hljs-title function_">construct</span>(original, args) :
      <span class="hljs-title class_">Reflect</span>.<span class="hljs-title function_">apply</span>(original, <span class="hljs-variable language_">this</span>, args);
  } <span class="hljs-keyword">finally</span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">timeEnd</span>();
  }
};</code> <button class="copy-button">copy</button></pre>
<h5>Scopes<span><a class="mark" href="#all_permissions_scopes" id="all_permissions_scopes">#</a></span><a aria-hidden="true" class="legacy" id="permissions_scopes"></a></h5>
<p>Use the <code>"scopes"</code> field of a manifest to set configuration for many resources
at once. The <code>"scopes"</code> field works by matching resources by their segments.
If a scope or resource includes <code>"cascade": true</code>, unknown specifiers will
be searched for in their containing scope. The containing scope for cascading
is found by recursively reducing the resource URL by removing segments for
<a href="https://url.spec.whatwg.org/#special-scheme">special schemes</a>, keeping trailing <code>"/"</code> suffixes, and removing the query and
hash fragment. This leads to the eventual reduction of the URL to its origin.
If the URL is non-special the scope will be located by the URL's origin. If no
scope is found for the origin or in the case of opaque origins, a protocol
string can be used as a scope. If no scope is found for the URL's protocol, a
final empty string <code>""</code> scope will be used.</p>
<p>Note, <code>blob:</code> URLs adopt their origin from the path they contain, and so a scope
of <code>"blob:https://nodejs.org"</code> will have no effect since no URL can have an
origin of <code>blob:https://nodejs.org</code>; URLs starting with
<code>blob:https://nodejs.org/</code> will use <code>https://nodejs.org</code> for its origin and
thus <code>https:</code> for its protocol scope. For opaque origin <code>blob:</code> URLs they will
have <code>blob:</code> for their protocol scope since they do not adopt origins.</p>
<h6>Example<span><a class="mark" href="#all_permissions_example" id="all_permissions_example">#</a></span><a aria-hidden="true" class="legacy" id="permissions_example"></a></h6>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"scopes"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"file:///C:/app/"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span><span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"file:"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span><span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">""</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span><span class="hljs-punctuation">}</span>
  <span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>Given a file located at <code>file:///C:/app/bin/main.js</code>, the following scopes would
be checked in order:</p>
<ol>
<li><code>"file:///C:/app/bin/"</code></li>
</ol>
<p>This determines the policy for all file based resources within
<code>"file:///C:/app/bin/"</code>. This is not in the <code>"scopes"</code> field of the policy and
would be skipped. Adding this scope to the policy would cause it to be used
prior to the <code>"file:///C:/app/"</code> scope.</p>
<ol start="2">
<li><code>"file:///C:/app/"</code></li>
</ol>
<p>This determines the policy for all file based resources within
<code>"file:///C:/app/"</code>. This is in the <code>"scopes"</code> field of the policy and it would
determine the policy for the resource at <code>file:///C:/app/bin/main.js</code>. If the
scope has <code>"cascade": true</code>, any unsatisfied queries about the resource would
delegate to the next relevant scope for <code>file:///C:/app/bin/main.js</code>, <code>"file:"</code>.</p>
<ol start="3">
<li><code>"file:///C:/"</code></li>
</ol>
<p>This determines the policy for all file based resources within <code>"file:///C:/"</code>.
This is not in the <code>"scopes"</code> field of the policy and would be skipped. It would
not be used for <code>file:///C:/app/bin/main.js</code> unless <code>"file:///C:/app/"</code> is set
to cascade or is not in the <code>"scopes"</code> of the policy.</p>
<ol start="4">
<li><code>"file:///"</code></li>
</ol>
<p>This determines the policy for all file based resources on the <code>localhost</code>. This
is not in the <code>"scopes"</code> field of the policy and would be skipped. It would not
be used for <code>file:///C:/app/bin/main.js</code> unless <code>"file:///C:/"</code> is set to
cascade or is not in the <code>"scopes"</code> of the policy.</p>
<ol start="5">
<li><code>"file:"</code></li>
</ol>
<p>This determines the policy for all file based resources. It would not be used
for <code>file:///C:/app/bin/main.js</code> unless <code>"file:///"</code> is set to cascade or is not
in the <code>"scopes"</code> of the policy.</p>
<ol start="6">
<li><code>""</code></li>
</ol>
<p>This determines the policy for all resources. It would not be used for
<code>file:///C:/app/bin/main.js</code> unless <code>"file:"</code> is set to cascade.</p>
<h6>Integrity using scopes<span><a class="mark" href="#all_permissions_integrity-using-scopes" id="all_permissions_integrity-using-scopes">#</a></span><a aria-hidden="true" class="legacy" id="permissions_integrity_using_scopes"></a></h6>
<p>Setting an integrity to <code>true</code> on a scope will set the integrity for any
resource not found in the manifest to <code>true</code>.</p>
<p>Setting an integrity to <code>null</code> on a scope will set the integrity for any
resource not found in the manifest to fail matching.</p>
<p>Not including an integrity is the same as setting the integrity to <code>null</code>.</p>
<p><code>"cascade"</code> for integrity checks will be ignored if <code>"integrity"</code> is explicitly
set.</p>
<p>The following example allows loading any file:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"scopes"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"file:"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"integrity"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span>
    <span class="hljs-punctuation">}</span>
  <span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<h6>Dependency redirection using scopes<span><a class="mark" href="#all_permissions_dependency-redirection-using-scopes" id="all_permissions_dependency-redirection-using-scopes">#</a></span><a aria-hidden="true" class="legacy" id="permissions_dependency_redirection_using_scopes"></a></h6>
<p>The following example, would allow access to <code>fs</code> for all resources within
<code>./app/</code>:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"resources"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"./app/checked.js"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"cascade"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"integrity"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span>
    <span class="hljs-punctuation">}</span>
  <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"scopes"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"./app/"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"dependencies"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
        <span class="hljs-attr">"fs"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span>
      <span class="hljs-punctuation">}</span>
    <span class="hljs-punctuation">}</span>
  <span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>The following example, would allow access to <code>fs</code> for all <code>data:</code> resources:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"resources"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"data:text/javascript,import('node:fs');"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"cascade"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"integrity"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span>
    <span class="hljs-punctuation">}</span>
  <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"scopes"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"data:"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"dependencies"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
        <span class="hljs-attr">"fs"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span>
      <span class="hljs-punctuation">}</span>
    <span class="hljs-punctuation">}</span>
  <span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<h6>Example: import maps emulation<span><a class="mark" href="#all_permissions_example-import-maps-emulation" id="all_permissions_example-import-maps-emulation">#</a></span><a aria-hidden="true" class="legacy" id="permissions_example_import_maps_emulation"></a></h6>
<p>Given an import map:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"imports"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"react"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./app/node_modules/react/index.js"</span>
  <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"scopes"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"./ssr/"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"react"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./app/node_modules/server-side-react/index.js"</span>
    <span class="hljs-punctuation">}</span>
  <span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"dependencies"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"scopes"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">""</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"cascade"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"dependencies"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
        <span class="hljs-attr">"react"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./app/node_modules/react/index.js"</span>
      <span class="hljs-punctuation">}</span>
    <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"./ssr/"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"cascade"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"dependencies"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
        <span class="hljs-attr">"react"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./app/node_modules/server-side-react/index.js"</span>
      <span class="hljs-punctuation">}</span>
    <span class="hljs-punctuation">}</span>
  <span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p><a href="https://url.spec.whatwg.org/#relative-url-with-fragment-string">Import maps</a> assume you can get any resource by default. This means
<code>"dependencies"</code> at the top level of the policy should be set to <code>true</code>.
Policies require this to be opt-in since it enables all resources of the
application cross linkage which doesn't make sense for many scenarios. They also
assume any given scope has access to any scope above its allowed dependencies;
all scopes emulating import maps must set <code>"cascade": true</code>.</p>
<p>Import maps only have a single top level scope for their "imports". So for
emulating <code>"imports"</code> use the <code>""</code> scope. For emulating <code>"scopes"</code> use the
<code>"scopes"</code> in a similar manner to how <code>"scopes"</code> works in import maps.</p>
<p>Caveats: Policies do not use string matching for various finding of scope. They
do URL traversals. This means things like <code>blob:</code> and <code>data:</code> URLs might not be
entirely interoperable between the two systems. For example import maps can
partially match a <code>data:</code> or <code>blob:</code> URL by partitioning the URL on a <code>/</code>
character, policies intentionally cannot. For <code>blob:</code> URLs import map scopes do
not adopt the origin of the <code>blob:</code> URL.</p>
<p>Additionally, import maps only work on <code>import</code> so it may be desirable to add a
<code>"import"</code> condition to all dependency mappings.</p>
<h5>Guarantees<span><a class="mark" href="#all_permissions_guarantees" id="all_permissions_guarantees">#</a></span><a aria-hidden="true" class="legacy" id="permissions_guarantees"></a></h5>
<ul>
<li>The policies guarantee the file integrity when a module is loaded using
<code>require()</code>, <code>import()</code> or <code>new Module()</code>.</li>
<li>Redirection does not prevent access to APIs through means such as direct
access to <code>require.cache</code> which allow access to loaded modules.
Policy redirection only affects specifiers to <code>require()</code> and
<code>import</code>.</li>
<li>The approval of the module integrity in policies threat model implies
they are allowed to muck with and even circumvent security features once
loaded so environmental/runtime hardening is expected.</li>
</ul>
</section><section><h3>Process-based permissions<span><a class="mark" href="#all_permissions_process-based-permissions" id="all_permissions_process-based-permissions">#</a></span><a aria-hidden="true" class="legacy" id="permissions_process_based_permissions"></a></h3>
<h4>Permission Model<span><a class="mark" href="#all_permissions_permission-model" id="all_permissions_permission-model">#</a></span><a aria-hidden="true" class="legacy" id="permissions_permission_model"></a></h4>

<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active development</div><p></p>
<!-- name=permission-model -->
<p>The Node.js Permission Model is a mechanism for restricting access to specific
resources during execution.
The API exists behind a flag <a href="#all_cli_--experimental-permission"><code>--experimental-permission</code></a> which when enabled,
will restrict access to all available permissions.</p>
<p>The available permissions are documented by the <a href="#all_cli_--experimental-permission"><code>--experimental-permission</code></a>
flag.</p>
<p>When starting Node.js with <code>--experimental-permission</code>,
the ability to access the file system through the <code>fs</code> module, spawn processes,
use <code>node:worker_threads</code>, use native addons, use WASI, and enable the runtime inspector
will be restricted.</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node --experimental-permission index.js</span>
node:internal/modules/cjs/loader:171
  const result = internalModuleStat(filename);
                 ^

Error: Access to this API has been restricted
    at stat (node:internal/modules/cjs/loader:171:18)
    at Module._findPath (node:internal/modules/cjs/loader:627:16)
    at resolveMainPath (node:internal/modules/run_main:19:25)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:24)
    at node:internal/main/run_main_module:23:47 {
  code: 'ERR_ACCESS_DENIED',
  permission: 'FileSystemRead',
  resource: '/home/user/index.js'
}</code> <button class="copy-button">copy</button></pre>
<p>Allowing access to spawning a process and creating worker threads can be done
using the <a href="#all_cli_--allow-child-process"><code>--allow-child-process</code></a> and <a href="#all_cli_--allow-worker"><code>--allow-worker</code></a> respectively.</p>
<p>To allow native addons when using permission model, use the <a href="#all_cli_--allow-addons"><code>--allow-addons</code></a>
flag. For WASI, use the <a href="#all_cli_--allow-wasi"><code>--allow-wasi</code></a> flag.</p>
<h5>Runtime API<span><a class="mark" href="#all_permissions_runtime-api" id="all_permissions_runtime-api">#</a></span><a aria-hidden="true" class="legacy" id="permissions_runtime_api"></a></h5>
<p>When enabling the Permission Model through the <a href="#all_cli_--experimental-permission"><code>--experimental-permission</code></a>
flag a new property <code>permission</code> is added to the <code>process</code> object.
This property contains one function:</p>
<h6><code>permission.has(scope[, reference])</code><span><a class="mark" href="#all_permissions_permissionhasscope-reference" id="all_permissions_permissionhasscope-reference">#</a></span><a aria-hidden="true" class="legacy" id="permissions_permission_has_scope_reference"></a></h6>
<p>API call to check permissions at runtime (<a href="#all_process_processpermissionhasscope-reference"><code>permission.has()</code></a>)</p>
<pre><code class="language-js">process.<span class="hljs-property">permission</span>.<span class="hljs-title function_">has</span>(<span class="hljs-string">'fs.write'</span>); <span class="hljs-comment">// true</span>
process.<span class="hljs-property">permission</span>.<span class="hljs-title function_">has</span>(<span class="hljs-string">'fs.write'</span>, <span class="hljs-string">'/home/rafaelgss/protected-folder'</span>); <span class="hljs-comment">// true</span>

process.<span class="hljs-property">permission</span>.<span class="hljs-title function_">has</span>(<span class="hljs-string">'fs.read'</span>); <span class="hljs-comment">// true</span>
process.<span class="hljs-property">permission</span>.<span class="hljs-title function_">has</span>(<span class="hljs-string">'fs.read'</span>, <span class="hljs-string">'/home/rafaelgss/protected-folder'</span>); <span class="hljs-comment">// false</span></code> <button class="copy-button">copy</button></pre>
<h5>File System Permissions<span><a class="mark" href="#all_permissions_file-system-permissions" id="all_permissions_file-system-permissions">#</a></span><a aria-hidden="true" class="legacy" id="permissions_file_system_permissions"></a></h5>
<p>The Permission Model, by default, restricts access to the file system through the <code>node:fs</code> module.
It does not guarantee that users will not be able to access the file system through other means,
such as through the <code>node:sqlite</code> module.</p>
<p>To allow access to the file system, use the <a href="#all_cli_--allow-fs-read"><code>--allow-fs-read</code></a> and
<a href="#all_cli_--allow-fs-write"><code>--allow-fs-write</code></a> flags:</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node --experimental-permission --allow-fs-read=* --allow-fs-write=* index.js</span>
Hello world!
(node:19836) ExperimentalWarning: Permission is an experimental feature
(Use `node --trace-warnings ...` to show where the warning was created)</code> <button class="copy-button">copy</button></pre>
<p>The valid arguments for both flags are:</p>
<ul>
<li><code>*</code> - To allow all <code>FileSystemRead</code> or <code>FileSystemWrite</code> operations,
respectively.</li>
<li>Paths delimited by comma (<code>,</code>) to allow only matching <code>FileSystemRead</code> or
<code>FileSystemWrite</code> operations, respectively.</li>
</ul>
<p>Example:</p>
<ul>
<li><code>--allow-fs-read=*</code> - It will allow all <code>FileSystemRead</code> operations.</li>
<li><code>--allow-fs-write=*</code> - It will allow all <code>FileSystemWrite</code> operations.</li>
<li><code>--allow-fs-write=/tmp/</code> - It will allow <code>FileSystemWrite</code> access to the <code>/tmp/</code>
folder.</li>
<li><code>--allow-fs-read=/tmp/ --allow-fs-read=/home/.gitignore</code> - It allows <code>FileSystemRead</code> access
to the <code>/tmp/</code> folder <strong>and</strong> the <code>/home/.gitignore</code> path.</li>
</ul>
<p>Wildcards are supported too:</p>
<ul>
<li><code>--allow-fs-read=/home/test*</code> will allow read access to everything
that matches the wildcard. e.g: <code>/home/test/file1</code> or <code>/home/test2</code></li>
</ul>
<p>After passing a wildcard character (<code>*</code>) all subsequent characters will
be ignored. For example: <code>/home/*.js</code> will work similar to <code>/home/*</code>.</p>
<p>When the permission model is initialized, it will automatically add a wildcard
(*) if the specified directory exists. For example, if <code>/home/test/files</code>
exists, it will be treated as <code>/home/test/files/*</code>. However, if the directory
does not exist, the wildcard will not be added, and access will be limited to
<code>/home/test/files</code>. If you want to allow access to a folder that does not exist
yet, make sure to explicitly include the wildcard:
<code>/my-path/folder-do-not-exist/*</code>.</p>
<h5>Permission Model constraints<span><a class="mark" href="#all_permissions_permission-model-constraints" id="all_permissions_permission-model-constraints">#</a></span><a aria-hidden="true" class="legacy" id="permissions_permission_model_constraints"></a></h5>
<p>There are constraints you need to know before using this system:</p>
<ul>
<li>The model does not inherit to a child node process or a worker thread.</li>
<li>When using the Permission Model the following features will be restricted:
<ul>
<li>Native modules</li>
<li>Child process</li>
<li>Worker Threads</li>
<li>Inspector protocol</li>
<li>File system access</li>
<li>WASI</li>
</ul>
</li>
<li>The Permission Model is initialized after the Node.js environment is set up.
However, certain flags such as <code>--env-file</code> or <code>--openssl-config</code> are designed
to read files before environment initialization. As a result, such flags are
not subject to the rules of the Permission Model. The same applies for V8
flags that can be set via runtime through <code>v8.setFlagsFromString</code>.</li>
<li>OpenSSL engines cannot be requested at runtime when the Permission
Model is enabled, affecting the built-in crypto, https, and tls modules.</li>
<li>Using existing file descriptors via the <code>node:fs</code> module bypasses the
Permission Model.</li>
</ul>
<h5>Limitations and Known Issues<span><a class="mark" href="#all_permissions_limitations-and-known-issues" id="all_permissions_limitations-and-known-issues">#</a></span><a aria-hidden="true" class="legacy" id="permissions_limitations_and_known_issues"></a></h5>
<ul>
<li>Symbolic links will be followed even to locations outside of the set of paths
that access has been granted to. Relative symbolic links may allow access to
arbitrary files and directories. When starting applications with the
permission model enabled, you must ensure that no paths to which access has
been granted contain relative symbolic links.</li>
</ul></section>
        </section>
<section><h2>Process<span><a class="mark" href="#all_process_process" id="all_process_process">#</a></span><a aria-hidden="true" class="legacy" id="process_process"></a></h2>


<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/process.js">lib/process.js</a></p>
<p>The <code>process</code> object provides information about, and control over, the current
Node.js process.</p>

<pre class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);</code><button class="copy-button">copy</button></pre>
<section><h3>Process events<span><a class="mark" href="#all_process_process-events" id="all_process_process-events">#</a></span><a aria-hidden="true" class="legacy" id="process_process_events"></a></h3>
<p>The <code>process</code> object is an instance of <a href="#all_events_class-eventemitter"><code>EventEmitter</code></a>.</p>
<h4>Event: <code>'beforeExit'</code><span><a class="mark" href="#all_process_event-beforeexit" id="all_process_event-beforeexit">#</a></span><a aria-hidden="true" class="legacy" id="process_event_beforeexit"></a></h4>
<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="#all_process_processexitcode_1"><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="#all_process_processexitcode"><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 class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'beforeExit'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Process beforeExit event with code: '</span>, code);
});

process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Process exit event with code: '</span>, code);
});

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'This message is displayed first.'</span>);

<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// This message is displayed first.</span>
<span class="hljs-comment">// Process beforeExit event with code: 0</span>
<span class="hljs-comment">// Process exit event with code: 0</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'beforeExit'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Process beforeExit event with code: '</span>, code);
});

process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Process exit event with code: '</span>, code);
});

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'This message is displayed first.'</span>);

<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// This message is displayed first.</span>
<span class="hljs-comment">// Process beforeExit event with code: 0</span>
<span class="hljs-comment">// Process exit event with code: 0</span></code><button class="copy-button">copy</button></pre>
<h4>Event: <code>'disconnect'</code><span><a class="mark" href="#all_process_event-disconnect" id="all_process_event-disconnect">#</a></span><a aria-hidden="true" class="legacy" id="process_event_disconnect"></a></h4>
<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>
<h4>Event: <code>'exit'</code><span><a class="mark" href="#all_process_event-exit" id="all_process_event-exit">#</a></span><a aria-hidden="true" class="legacy" id="process_event_exit"></a></h4>
<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="#all_process_processexitcode_1"><code>process.exitCode</code></a> property, or the <code>exitCode</code> argument passed to the
<a href="#all_process_processexitcode"><code>process.exit()</code></a> method.</p>

<pre class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`About to exit with code: <span class="hljs-subst">${code}</span>`</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`About to exit with code: <span class="hljs-subst">${code}</span>`</span>);
});</code><button class="copy-button">copy</button></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 class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'This will not run'</span>);
  }, <span class="hljs-number">0</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'This will not run'</span>);
  }, <span class="hljs-number">0</span>);
});</code><button class="copy-button">copy</button></pre>
<h4>Event: <code>'message'</code><span><a class="mark" href="#all_process_event-message" id="all_process_event-message">#</a></span><a aria-hidden="true" class="legacy" id="process_event_message"></a></h4>
<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="#all_net_class-netserver" class="type">&#x3C;net.Server></a> | <a href="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a> a <a href="#all_net_class-netserver"><code>net.Server</code></a> or <a href="#all_net_class-netsocket"><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="#all_child_process_subprocesssendmessage-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="#all_child_process_advanced-serialization">Advanced serialization for <code>child_process</code></a> for more details.</p>
<h4>Event: <code>'multipleResolves'</code><span><a class="mark" href="#all_process_event-multipleresolves" id="all_process_event-multipleresolves">#</a></span><a aria-hidden="true" class="legacy" id="process_event_multipleresolves"></a></h4>
<div class="api_metadata">
<span>Added in: v10.12.0</span><span>Deprecated since: v17.6.0, v16.15.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated</div><p></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 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>
<p>Because of the unreliability of the event in cases like the
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race"><code>Promise.race()</code></a> example above it has been deprecated.</p>

<pre class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'multipleResolves'</span>, <span class="hljs-function">(<span class="hljs-params">type, promise, reason</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(type, promise, reason);
  <span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></span> process.<span class="hljs-title function_">exit</span>(<span class="hljs-number">1</span>));
});

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">main</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =></span> {
      <span class="hljs-title function_">resolve</span>(<span class="hljs-string">'First call'</span>);
      <span class="hljs-title function_">resolve</span>(<span class="hljs-string">'Swallowed resolve'</span>);
      <span class="hljs-title function_">reject</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Swallowed reject'</span>));
    });
  } <span class="hljs-keyword">catch</span> {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Failed'</span>);
  }
}

<span class="hljs-title function_">main</span>().<span class="hljs-title function_">then</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>);
<span class="hljs-comment">// resolve: Promise { 'First call' } 'Swallowed resolve'</span>
<span class="hljs-comment">// reject: Promise { 'First call' } Error: Swallowed reject</span>
<span class="hljs-comment">//     at Promise (*)</span>
<span class="hljs-comment">//     at new Promise (&#x3C;anonymous>)</span>
<span class="hljs-comment">//     at main (*)</span>
<span class="hljs-comment">// First call</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'multipleResolves'</span>, <span class="hljs-function">(<span class="hljs-params">type, promise, reason</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(type, promise, reason);
  <span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></span> process.<span class="hljs-title function_">exit</span>(<span class="hljs-number">1</span>));
});

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">main</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =></span> {
      <span class="hljs-title function_">resolve</span>(<span class="hljs-string">'First call'</span>);
      <span class="hljs-title function_">resolve</span>(<span class="hljs-string">'Swallowed resolve'</span>);
      <span class="hljs-title function_">reject</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Swallowed reject'</span>));
    });
  } <span class="hljs-keyword">catch</span> {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Failed'</span>);
  }
}

<span class="hljs-title function_">main</span>().<span class="hljs-title function_">then</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>);
<span class="hljs-comment">// resolve: Promise { 'First call' } 'Swallowed resolve'</span>
<span class="hljs-comment">// reject: Promise { 'First call' } Error: Swallowed reject</span>
<span class="hljs-comment">//     at Promise (*)</span>
<span class="hljs-comment">//     at new Promise (&#x3C;anonymous>)</span>
<span class="hljs-comment">//     at main (*)</span>
<span class="hljs-comment">// First call</span></code><button class="copy-button">copy</button></pre>
<h4>Event: <code>'rejectionHandled'</code><span><a class="mark" href="#all_process_event-rejectionhandled" id="all_process_event-rejectionhandled">#</a></span><a aria-hidden="true" class="legacy" id="process_event_rejectionhandled"></a></h4>
<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 class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-keyword">const</span> unhandledRejections = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Map</span>();
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'unhandledRejection'</span>, <span class="hljs-function">(<span class="hljs-params">reason, promise</span>) =></span> {
  unhandledRejections.<span class="hljs-title function_">set</span>(promise, reason);
});
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'rejectionHandled'</span>, <span class="hljs-function">(<span class="hljs-params">promise</span>) =></span> {
  unhandledRejections.<span class="hljs-title function_">delete</span>(promise);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-keyword">const</span> unhandledRejections = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Map</span>();
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'unhandledRejection'</span>, <span class="hljs-function">(<span class="hljs-params">reason, promise</span>) =></span> {
  unhandledRejections.<span class="hljs-title function_">set</span>(promise, reason);
});
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'rejectionHandled'</span>, <span class="hljs-function">(<span class="hljs-params">promise</span>) =></span> {
  unhandledRejections.<span class="hljs-title function_">delete</span>(promise);
});</code><button class="copy-button">copy</button></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>
<h4>Event: <code>'uncaughtException'</code><span><a class="mark" href="#all_process_event-uncaughtexception" id="all_process_event-uncaughtexception">#</a></span><a aria-hidden="true" class="legacy" id="process_event_uncaughtexception"></a></h4>
<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, v10.17.0</td>
<td><p>Added the <code>origin</code> argument.</p></td></tr>
<tr><td>v0.1.18</td>
<td><p><span>Added in: v0.1.18</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>err</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#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 a synchronous error. Can either be <code>'uncaughtException'</code> or
<code>'unhandledRejection'</code>. The latter is used when an exception happens in a
<code>Promise</code> based async context (or if a <code>Promise</code> is rejected) and
<a href="#all_cli_--unhandled-rejectionsmode"><code>--unhandled-rejections</code></a> flag set to <code>strict</code> or <code>throw</code> (which is the
default) and the rejection is not handled, or when a rejection happens during
the command line entry point's ES module static loading phase.</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="#all_process_processexitcode_1"><code>process.exitCode</code></a>.
Adding a handler for the <code>'uncaughtException'</code> event overrides this default
behavior. Alternatively, change the <a href="#all_process_processexitcode_1"><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 class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">import</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'uncaughtException'</span>, <span class="hljs-function">(<span class="hljs-params">err, origin</span>) =></span> {
  fs.<span class="hljs-title function_">writeSync</span>(
    process.<span class="hljs-property">stderr</span>.<span class="hljs-property">fd</span>,
    <span class="hljs-string">`Caught exception: <span class="hljs-subst">${err}</span>\n`</span> +
    <span class="hljs-string">`Exception origin: <span class="hljs-subst">${origin}</span>\n`</span>,
  );
});

<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'This will still run.'</span>);
}, <span class="hljs-number">500</span>);

<span class="hljs-comment">// Intentionally cause an exception, but don't catch it.</span>
<span class="hljs-title function_">nonexistentFunc</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'This will not run.'</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);

process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'uncaughtException'</span>, <span class="hljs-function">(<span class="hljs-params">err, origin</span>) =></span> {
  fs.<span class="hljs-title function_">writeSync</span>(
    process.<span class="hljs-property">stderr</span>.<span class="hljs-property">fd</span>,
    <span class="hljs-string">`Caught exception: <span class="hljs-subst">${err}</span>\n`</span> +
    <span class="hljs-string">`Exception origin: <span class="hljs-subst">${origin}</span>\n`</span>,
  );
});

<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'This will still run.'</span>);
}, <span class="hljs-number">500</span>);

<span class="hljs-comment">// Intentionally cause an exception, but don't catch it.</span>
<span class="hljs-title function_">nonexistentFunc</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'This will not run.'</span>);</code><button class="copy-button">copy</button></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>
<h5>Warning: Using <code>'uncaughtException'</code> correctly<span><a class="mark" href="#all_process_warning-using-uncaughtexception-correctly" id="all_process_warning-using-uncaughtexception-correctly">#</a></span><a aria-hidden="true" class="legacy" id="process_warning_using_uncaughtexception_correctly"></a></h5>
<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>
<h4>Event: <code>'uncaughtExceptionMonitor'</code><span><a class="mark" href="#all_process_event-uncaughtexceptionmonitor" id="all_process_event-uncaughtexceptionmonitor">#</a></span><a aria-hidden="true" class="legacy" id="process_event_uncaughtexceptionmonitor"></a></h4>
<div class="api_metadata">
<span>Added in: v13.7.0, 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>. The latter is used when an exception happens in a
<code>Promise</code> based async context (or if a <code>Promise</code> is rejected) and
<a href="#all_cli_--unhandled-rejectionsmode"><code>--unhandled-rejections</code></a> flag set to <code>strict</code> or <code>throw</code> (which is the
default) and the rejection is not handled, or when a rejection happens during
the command line entry point's ES module static loading phase.</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="#all_process_processsetuncaughtexceptioncapturecallbackfn"><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 class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'uncaughtExceptionMonitor'</span>, <span class="hljs-function">(<span class="hljs-params">err, origin</span>) =></span> {
  <span class="hljs-title class_">MyMonitoringTool</span>.<span class="hljs-title function_">logSync</span>(err, origin);
});

<span class="hljs-comment">// Intentionally cause an exception, but don't catch it.</span>
<span class="hljs-title function_">nonexistentFunc</span>();
<span class="hljs-comment">// Still crashes Node.js</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'uncaughtExceptionMonitor'</span>, <span class="hljs-function">(<span class="hljs-params">err, origin</span>) =></span> {
  <span class="hljs-title class_">MyMonitoringTool</span>.<span class="hljs-title function_">logSync</span>(err, origin);
});

<span class="hljs-comment">// Intentionally cause an exception, but don't catch it.</span>
<span class="hljs-title function_">nonexistentFunc</span>();
<span class="hljs-comment">// Still crashes Node.js</span></code><button class="copy-button">copy</button></pre>
<h4>Event: <code>'unhandledRejection'</code><span><a class="mark" href="#all_process_event-unhandledrejection" id="all_process_event-unhandledrejection">#</a></span><a aria-hidden="true" class="legacy" id="process_event_unhandledrejection"></a></h4>
<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="#all_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 class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'unhandledRejection'</span>, <span class="hljs-function">(<span class="hljs-params">reason, promise</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Unhandled Rejection at:'</span>, promise, <span class="hljs-string">'reason:'</span>, reason);
  <span class="hljs-comment">// Application specific logging, throwing an error, or other logic here</span>
});

somePromise.<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
  <span class="hljs-keyword">return</span> <span class="hljs-title function_">reportToUser</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">pasre</span>(res)); <span class="hljs-comment">// Note the typo (`pasre`)</span>
}); <span class="hljs-comment">// No `.catch()` or `.then()`</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'unhandledRejection'</span>, <span class="hljs-function">(<span class="hljs-params">reason, promise</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Unhandled Rejection at:'</span>, promise, <span class="hljs-string">'reason:'</span>, reason);
  <span class="hljs-comment">// Application specific logging, throwing an error, or other logic here</span>
});

somePromise.<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
  <span class="hljs-keyword">return</span> <span class="hljs-title function_">reportToUser</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">pasre</span>(res)); <span class="hljs-comment">// Note the typo (`pasre`)</span>
}); <span class="hljs-comment">// No `.catch()` or `.then()`</span></code><button class="copy-button">copy</button></pre>
<p>The following will also trigger the <code>'unhandledRejection'</code> event to be
emitted:</p>

<pre class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-keyword">function</span> <span class="hljs-title function_">SomeResource</span>(<span class="hljs-params"></span>) {
  <span class="hljs-comment">// Initially set the loaded status to a rejected promise</span>
  <span class="hljs-variable language_">this</span>.<span class="hljs-property">loaded</span> = <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">reject</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Resource not yet loaded!'</span>));
}

<span class="hljs-keyword">const</span> resource = <span class="hljs-keyword">new</span> <span class="hljs-title class_">SomeResource</span>();
<span class="hljs-comment">// no .catch or .then on resource.loaded for at least a turn</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-keyword">function</span> <span class="hljs-title function_">SomeResource</span>(<span class="hljs-params"></span>) {
  <span class="hljs-comment">// Initially set the loaded status to a rejected promise</span>
  <span class="hljs-variable language_">this</span>.<span class="hljs-property">loaded</span> = <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">reject</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Resource not yet loaded!'</span>));
}

<span class="hljs-keyword">const</span> resource = <span class="hljs-keyword">new</span> <span class="hljs-title class_">SomeResource</span>();
<span class="hljs-comment">// no .catch or .then on resource.loaded for at least a turn</span></code><button class="copy-button">copy</button></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>
<h4>Event: <code>'warning'</code><span><a class="mark" href="#all_process_event-warning" id="all_process_event-warning">#</a></span><a aria-hidden="true" class="legacy" id="process_event_warning"></a></h4>
<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/Reference/Global_Objects/Error" class="type">&#x3C;Error></a> Key properties of the warning are:
<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 class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'warning'</span>, <span class="hljs-function">(<span class="hljs-params">warning</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">name</span>);    <span class="hljs-comment">// Print the warning name</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">message</span>); <span class="hljs-comment">// Print the warning message</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">stack</span>);   <span class="hljs-comment">// Print the stack trace</span>
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'warning'</span>, <span class="hljs-function">(<span class="hljs-params">warning</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">name</span>);    <span class="hljs-comment">// Print the warning name</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">message</span>); <span class="hljs-comment">// Print the warning message</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">stack</span>);   <span class="hljs-comment">// Print the stack trace</span>
});</code><button class="copy-button">copy</button></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. Currently, it
is not possible to suppress specific warning types other than deprecation
warnings. To suppress deprecation warnings, check out the <a href="#all_cli_--no-deprecation"><code>--no-deprecation</code></a>
flag.</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"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node</span>
<span class="hljs-meta prompt_">> </span><span class="language-bash">events.defaultMaxListeners = 1;</span>
<span class="hljs-meta prompt_">> </span><span class="language-bash">process.on(<span class="hljs-string">'foo'</span>, () => {});</span>
<span class="hljs-meta prompt_">> </span><span class="language-bash">process.on(<span class="hljs-string">'foo'</span>, () => {});</span>
<span class="hljs-meta prompt_">> </span><span class="language-bash">(node:38638) MaxListenersExceededWarning: Possible EventEmitter memory leak</span>
detected. 2 foo listeners added. Use emitter.setMaxListeners() to increase limit</code> <button class="copy-button">copy</button></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"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node --no-warnings</span>
<span class="hljs-meta prompt_">> </span><span class="language-bash">const p = process.on(<span class="hljs-string">'warning'</span>, (warning) => console.warn(<span class="hljs-string">'Do not do that!'</span>));</span>
<span class="hljs-meta prompt_">> </span><span class="language-bash">events.defaultMaxListeners = 1;</span>
<span class="hljs-meta prompt_">> </span><span class="language-bash">process.on(<span class="hljs-string">'foo'</span>, () => {});</span>
<span class="hljs-meta prompt_">> </span><span class="language-bash">process.on(<span class="hljs-string">'foo'</span>, () => {});</span>
<span class="hljs-meta prompt_">> </span><span class="language-bash">Do not <span class="hljs-keyword">do</span> that!</span></code> <button class="copy-button">copy</button></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>
<h5>Emitting custom warnings<span><a class="mark" href="#all_process_emitting-custom-warnings" id="all_process_emitting-custom-warnings">#</a></span><a aria-hidden="true" class="legacy" id="process_emitting_custom_warnings"></a></h5>
<p>See the <a href="#all_process_processemitwarningwarning-type-code-ctor"><code>process.emitWarning()</code></a> method for issuing
custom or application-specific warnings.</p>
<h5>Node.js warning names<span><a class="mark" href="#all_process_nodejs-warning-names" id="all_process_nodejs-warning-names">#</a></span><a aria-hidden="true" class="legacy" id="process_node_js_warning_names"></a></h5>
<p>There are no strict guidelines for warning types (as identified by the <code>name</code>
property) emitted by Node.js. New types of warnings can be added at any time.
A few of the warning types that are most common include:</p>
<ul>
<li><code>'DeprecationWarning'</code> - Indicates use of a deprecated Node.js API or feature.
Such warnings must include a <code>'code'</code> property identifying the
<a href="deprecations.html">deprecation code</a>.</li>
<li><code>'ExperimentalWarning'</code> - Indicates use of an experimental Node.js API or
feature. Such features must be used with caution as they may change at any
time and are not subject to the same strict semantic-versioning and long-term
support policies as supported features.</li>
<li><code>'MaxListenersExceededWarning'</code> - Indicates that too many listeners for a
given event have been registered on either an <code>EventEmitter</code> or <code>EventTarget</code>.
This is often an indication of a memory leak.</li>
<li><code>'TimeoutOverflowWarning'</code> - Indicates that a numeric value that cannot fit
within a 32-bit signed integer has been provided to either the <code>setTimeout()</code>
or <code>setInterval()</code> functions.</li>
<li><code>'UnsupportedWarning'</code> - Indicates use of an unsupported option or feature
that will be ignored rather than treated as an error. One example is use of
the HTTP response status message when using the HTTP/2 compatibility API.</li>
</ul>
<h4>Event: <code>'worker'</code><span><a class="mark" href="#all_process_event-worker" id="all_process_event-worker">#</a></span><a aria-hidden="true" class="legacy" id="process_event_worker"></a></h4>
<div class="api_metadata">
<span>Added in: v16.2.0, v14.18.0</span>
</div>
<ul>
<li><code>worker</code> <a href="#all_worker_threads_class-worker" class="type">&#x3C;Worker></a> The <a href="#all_worker_threads_class-worker" class="type">&#x3C;Worker></a> that was created.</li>
</ul>
<p>The <code>'worker'</code> event is emitted after a new <a href="#all_worker_threads_class-worker" class="type">&#x3C;Worker></a> thread has been created.</p>
<h4>Signal events<span><a class="mark" href="#all_process_signal-events" id="all_process_signal-events">#</a></span><a aria-hidden="true" class="legacy" id="process_signal_events"></a></h4>


<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="#all_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 class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-comment">// Begin reading from stdin so the process does not exit.</span>
process.<span class="hljs-property">stdin</span>.<span class="hljs-title function_">resume</span>();

process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'SIGINT'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Received SIGINT. Press Control-D to exit.'</span>);
});

<span class="hljs-comment">// Using a single function to handle multiple signals</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">handle</span>(<span class="hljs-params">signal</span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Received <span class="hljs-subst">${signal}</span>`</span>);
}

process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'SIGINT'</span>, handle);
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'SIGTERM'</span>, handle);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-comment">// Begin reading from stdin so the process does not exit.</span>
process.<span class="hljs-property">stdin</span>.<span class="hljs-title function_">resume</span>();

process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'SIGINT'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Received SIGINT. Press Control-D to exit.'</span>);
});

<span class="hljs-comment">// Using a single function to handle multiple signals</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">handle</span>(<span class="hljs-params">signal</span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Received <span class="hljs-subst">${signal}</span>`</span>);
}

process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'SIGINT'</span>, handle);
process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'SIGTERM'</span>, handle);</code><button class="copy-button">copy</button></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 <kbd>Ctrl</kbd>+<kbd>C</kbd> (though this may be configurable).
It is not generated when <a href="#all_tty_readstreamsetrawmodemode">terminal raw mode</a> is enabled
and <kbd>Ctrl</kbd>+<kbd>C</kbd> is used.</li>
<li><code>'SIGBREAK'</code> is delivered on Windows when <kbd>Ctrl</kbd>+<kbd>Break</kbd> 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 call JS listeners. Doing so might cause the process
to stop responding.</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="#all_process_processkillpid-signal"><code>process.kill()</code></a>, and
<a href="#all_child_process_subprocesskillsignal"><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>
</section><section><h3><code>process.abort()</code><span><a class="mark" href="#all_process_processabort" id="all_process_processabort">#</a></span><a aria-hidden="true" class="legacy" id="process_process_abort"></a></h3>
<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="#all_worker_threads_class-worker"><code>Worker</code></a> threads.</p>
</section><section><h3><code>process.allowedNodeEnvironmentFlags</code><span><a class="mark" href="#all_process_processallowednodeenvironmentflags" id="all_process_processallowednodeenvironmentflags">#</a></span><a aria-hidden="true" class="legacy" id="process_process_allowednodeenvironmentflags"></a></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/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="#all_cli_node_optionsoptions"><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="#all_cli_node_optionsoptions"><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 class="with-64-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { allowedNodeEnvironmentFlags } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

allowedNodeEnvironmentFlags.<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">flag</span>) =></span> {
  <span class="hljs-comment">// -r</span>
  <span class="hljs-comment">// --inspect-brk</span>
  <span class="hljs-comment">// --abort_on_uncaught_exception</span>
  <span class="hljs-comment">// ...</span>
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { allowedNodeEnvironmentFlags } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

allowedNodeEnvironmentFlags.<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">flag</span>) =></span> {
  <span class="hljs-comment">// -r</span>
  <span class="hljs-comment">// --inspect-brk</span>
  <span class="hljs-comment">// --abort_on_uncaught_exception</span>
  <span class="hljs-comment">// ...</span>
});</code><button class="copy-button">copy</button></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="#all_cli_node_optionsoptions"><code>NODE_OPTIONS</code></a> support (shown in
<a href="#all_process_processconfig"><code>process.config</code></a>), <code>process.allowedNodeEnvironmentFlags</code> will
contain what <em>would have</em> been allowable.</p>
</section><section><h3><code>process.arch</code><span><a class="mark" href="#all_process_processarch" id="all_process_processarch">#</a></span><a aria-hidden="true" class="legacy" id="process_process_arch"></a></h3>
<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>'loong64'</code>, <code>'mips'</code>,
<code>'mipsel'</code>, <code>'ppc'</code>, <code>'ppc64'</code>, <code>'riscv64'</code>, <code>'s390'</code>, <code>'s390x'</code>, and <code>'x64'</code>.</p>

<pre class="with-41-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { arch } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`This processor architecture is <span class="hljs-subst">${arch}</span>`</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { arch } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`This processor architecture is <span class="hljs-subst">${arch}</span>`</span>);</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>process.argv</code><span><a class="mark" href="#all_process_processargv" id="all_process_processargv">#</a></span><a aria-hidden="true" class="legacy" id="process_process_argv"></a></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 <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="#all_process_processexecpath"><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 class="with-41-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { argv } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-comment">// print process.argv</span>
argv.<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">val, index</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${index}</span>: <span class="hljs-subst">${val}</span>`</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { argv } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-comment">// print process.argv</span>
argv.<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">val, index</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${index}</span>: <span class="hljs-subst">${val}</span>`</span>);
});</code><button class="copy-button">copy</button></pre>
<p>Launching the Node.js process as:</p>
<pre><code class="language-bash">node process-args.js one two=three four</code> <button class="copy-button">copy</button></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> <button class="copy-button">copy</button></pre>
</section><section><h3><code>process.argv0</code><span><a class="mark" href="#all_process_processargv0" id="all_process_processargv0">#</a></span><a aria-hidden="true" class="legacy" id="process_process_argv0"></a></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#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"><span class="hljs-meta prompt_">$ </span><span class="language-bash">bash -c <span class="hljs-string">'exec -a customArgv0 ./node'</span></span>
<span class="hljs-meta prompt_">> </span><span class="language-bash">process.argv[0]</span>
'/Volumes/code/external/node/out/Release/node'
<span class="hljs-meta prompt_">> </span><span class="language-bash">process.argv0</span>
'customArgv0'</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>process.channel</code><span><a class="mark" href="#all_process_processchannel" id="all_process_processchannel">#</a></span><a aria-hidden="true" class="legacy" id="process_process_channel"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.0.0</td>
<td><p>The object no longer accidentally exposes native C++ bindings.</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><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>
<h4><code>process.channel.ref()</code><span><a class="mark" href="#all_process_processchannelref" id="all_process_processchannelref">#</a></span><a aria-hidden="true" class="legacy" id="process_process_channel_ref"></a></h4>
<div class="api_metadata">
<span>Added in: v7.1.0</span>
</div>
<p>This method makes the IPC channel keep the event loop of the process
running if <code>.unref()</code> has been called before.</p>
<p>Typically, this is managed through the number of <code>'disconnect'</code> and <code>'message'</code>
listeners on the <code>process</code> object. However, this method can be used to
explicitly request a specific behavior.</p>
<h4><code>process.channel.unref()</code><span><a class="mark" href="#all_process_processchannelunref" id="all_process_processchannelunref">#</a></span><a aria-hidden="true" class="legacy" id="process_process_channel_unref"></a></h4>
<div class="api_metadata">
<span>Added in: v7.1.0</span>
</div>
<p>This method makes the IPC channel not keep the event loop of the process
running, and lets it finish even while the channel is open.</p>
<p>Typically, this is managed through the number of <code>'disconnect'</code> and <code>'message'</code>
listeners on the <code>process</code> object. However, this method can be used to
explicitly request a specific behavior.</p>
</section><section><h3><code>process.chdir(directory)</code><span><a class="mark" href="#all_process_processchdirdirectory" id="all_process_processchdirdirectory">#</a></span><a aria-hidden="true" class="legacy" id="process_process_chdir_directory"></a></h3>
<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 class="with-47-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { chdir, cwd } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Starting directory: <span class="hljs-subst">${cwd()}</span>`</span>);
<span class="hljs-keyword">try</span> {
  <span class="hljs-title function_">chdir</span>(<span class="hljs-string">'/tmp'</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`New directory: <span class="hljs-subst">${cwd()}</span>`</span>);
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`chdir: <span class="hljs-subst">${err}</span>`</span>);
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { chdir, cwd } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Starting directory: <span class="hljs-subst">${cwd()}</span>`</span>);
<span class="hljs-keyword">try</span> {
  <span class="hljs-title function_">chdir</span>(<span class="hljs-string">'/tmp'</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`New directory: <span class="hljs-subst">${cwd()}</span>`</span>);
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`chdir: <span class="hljs-subst">${err}</span>`</span>);
}</code><button class="copy-button">copy</button></pre>
<p>This feature is not available in <a href="#all_worker_threads_class-worker"><code>Worker</code></a> threads.</p>
</section><section><h3><code>process.config</code><span><a class="mark" href="#all_process_processconfig" id="all_process_processconfig">#</a></span><a aria-hidden="true" class="legacy" id="process_process_config"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0</td>
<td><p>The <code>process.config</code> object is now frozen.</p></td></tr>
<tr><td>v16.0.0</td>
<td><p>Modifying process.config has been deprecated.</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><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 a frozen <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">{
  <span class="hljs-attr">target_defaults</span>:
   { <span class="hljs-attr">cflags</span>: [],
     <span class="hljs-attr">default_configuration</span>: <span class="hljs-string">'Release'</span>,
     <span class="hljs-attr">defines</span>: [],
     <span class="hljs-attr">include_dirs</span>: [],
     <span class="hljs-attr">libraries</span>: [] },
  <span class="hljs-attr">variables</span>:
   {
     <span class="hljs-attr">host_arch</span>: <span class="hljs-string">'x64'</span>,
     <span class="hljs-attr">napi_build_version</span>: <span class="hljs-number">5</span>,
     <span class="hljs-attr">node_install_npm</span>: <span class="hljs-string">'true'</span>,
     <span class="hljs-attr">node_prefix</span>: <span class="hljs-string">''</span>,
     <span class="hljs-attr">node_shared_cares</span>: <span class="hljs-string">'false'</span>,
     <span class="hljs-attr">node_shared_http_parser</span>: <span class="hljs-string">'false'</span>,
     <span class="hljs-attr">node_shared_libuv</span>: <span class="hljs-string">'false'</span>,
     <span class="hljs-attr">node_shared_zlib</span>: <span class="hljs-string">'false'</span>,
     <span class="hljs-attr">node_use_openssl</span>: <span class="hljs-string">'true'</span>,
     <span class="hljs-attr">node_shared_openssl</span>: <span class="hljs-string">'false'</span>,
     <span class="hljs-attr">strict_aliasing</span>: <span class="hljs-string">'true'</span>,
     <span class="hljs-attr">target_arch</span>: <span class="hljs-string">'x64'</span>,
     <span class="hljs-attr">v8_use_snapshot</span>: <span class="hljs-number">1</span>
   }
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>process.connected</code><span><a class="mark" href="#all_process_processconnected" id="all_process_processconnected">#</a></span><a aria-hidden="true" class="legacy" id="process_process_connected"></a></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></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>
</section><section><h3><code>process.constrainedMemory()</code><span><a class="mark" href="#all_process_processconstrainedmemory" id="all_process_processconstrainedmemory">#</a></span><a aria-hidden="true" class="legacy" id="process_process_constrainedmemory"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.13.0</td>
<td><p>Aligned return value with <code>uv_get_constrained_memory</code>.</p></td></tr>
<tr><td>v19.6.0, v18.15.0</td>
<td><p><span>Added in: v19.6.0, v18.15.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_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#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>Gets the amount of memory available to the process (in bytes) based on
limits imposed by the OS. If there is no such constraint, or the constraint
is unknown, <code>0</code> is returned.</p>
<p>See <a href="https://docs.libuv.org/en/v1.x/misc.html#c.uv_get_constrained_memory"><code>uv_get_constrained_memory</code></a> for more
information.</p>
</section><section><h3><code>process.availableMemory()</code><span><a class="mark" href="#all_process_processavailablememory" id="all_process_processavailablememory">#</a></span><a aria-hidden="true" class="legacy" id="process_process_availablememory"></a></h3>
<div class="api_metadata">
<span>Added in: v20.13.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_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#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>Gets the amount of free memory that is still available to the process
(in bytes).</p>
<p>See <a href="https://docs.libuv.org/en/v1.x/misc.html#c.uv_get_available_memory"><code>uv_get_available_memory</code></a> for more
information.</p>
</section><section><h3><code>process.cpuUsage([previousValue])</code><span><a class="mark" href="#all_process_processcpuusagepreviousvalue" id="all_process_processcpuusagepreviousvalue">#</a></span><a aria-hidden="true" class="legacy" id="process_process_cpuusage_previousvalue"></a></h3>
<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>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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 class="with-45-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { cpuUsage } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-keyword">const</span> startUsage = <span class="hljs-title function_">cpuUsage</span>();
<span class="hljs-comment">// { user: 38579, system: 6986 }</span>

<span class="hljs-comment">// spin the CPU for 500 milliseconds</span>
<span class="hljs-keyword">const</span> now = <span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>();
<span class="hljs-keyword">while</span> (<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>() - now &#x3C; <span class="hljs-number">500</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">cpuUsage</span>(startUsage));
<span class="hljs-comment">// { user: 514883, system: 11226 }</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { cpuUsage } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-keyword">const</span> startUsage = <span class="hljs-title function_">cpuUsage</span>();
<span class="hljs-comment">// { user: 38579, system: 6986 }</span>

<span class="hljs-comment">// spin the CPU for 500 milliseconds</span>
<span class="hljs-keyword">const</span> now = <span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>();
<span class="hljs-keyword">while</span> (<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>() - now &#x3C; <span class="hljs-number">500</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">cpuUsage</span>(startUsage));
<span class="hljs-comment">// { user: 514883, system: 11226 }</span></code><button class="copy-button">copy</button></pre>
</section><section><h3><code>process.cwd()</code><span><a class="mark" href="#all_process_processcwd" id="all_process_processcwd">#</a></span><a aria-hidden="true" class="legacy" id="process_process_cwd"></a></h3>
<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 class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { cwd } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Current directory: <span class="hljs-subst">${cwd()}</span>`</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { cwd } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Current directory: <span class="hljs-subst">${cwd()}</span>`</span>);</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>process.debugPort</code><span><a class="mark" href="#all_process_processdebugport" id="all_process_processdebugport">#</a></span><a aria-hidden="true" class="legacy" id="process_process_debugport"></a></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#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>The port used by the Node.js debugger when enabled.</p>

<pre class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

process.<span class="hljs-property">debugPort</span> = <span class="hljs-number">5858</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

process.<span class="hljs-property">debugPort</span> = <span class="hljs-number">5858</span>;</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>process.disconnect()</code><span><a class="mark" href="#all_process_processdisconnect" id="all_process_processdisconnect">#</a></span><a aria-hidden="true" class="legacy" id="process_process_disconnect"></a></h3>
<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="#all_child_process_subprocessdisconnect"><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>
</section><section><h3><code>process.dlopen(module, filename[, flags])</code><span><a class="mark" href="#all_process_processdlopenmodule-filename-flags" id="all_process_processdlopenmodule-filename-flags">#</a></span><a aria-hidden="true" class="legacy" id="process_process_dlopen_module_filename_flags"></a></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>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="#all_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 dynamically loading 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="#all_globals_require"><code>require()</code></a> should be
preferred over <code>process.dlopen()</code> unless there are specific reasons such as
custom dlopen flags or loading from ES modules.</p>
<p>The <code>flags</code> argument is an integer that allows to specify dlopen
behavior. See the <a href="#all_os_dlopen-constants"><code>os.constants.dlopen</code></a> documentation for details.</p>
<p>An important requirement when calling <code>process.dlopen()</code> is that the <code>module</code>
instance must be passed. Functions exported by the C++ Addon are then
accessible via <code>module.exports</code>.</p>
<p>The example below shows how to load a C++ Addon, named <code>local.node</code>,
that exports a <code>foo</code> function. All the symbols are 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 class="with-43-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { dlopen } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">import</span> { constants } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:os'</span>;
<span class="hljs-keyword">import</span> { fileURLToPath } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:url'</span>;

<span class="hljs-keyword">const</span> <span class="hljs-variable language_">module</span> = { <span class="hljs-attr">exports</span>: {} };
<span class="hljs-title function_">dlopen</span>(<span class="hljs-variable language_">module</span>, <span class="hljs-title function_">fileURLToPath</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'local.node'</span>, <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>)),
       constants.<span class="hljs-property">dlopen</span>.<span class="hljs-property">RTLD_NOW</span>);
<span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span>.<span class="hljs-title function_">foo</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { dlopen } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">const</span> { constants } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:os'</span>);
<span class="hljs-keyword">const</span> { join } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:path'</span>);

<span class="hljs-keyword">const</span> <span class="hljs-variable language_">module</span> = { <span class="hljs-attr">exports</span>: {} };
<span class="hljs-title function_">dlopen</span>(<span class="hljs-variable language_">module</span>, <span class="hljs-title function_">join</span>(__dirname, <span class="hljs-string">'local.node'</span>), constants.<span class="hljs-property">dlopen</span>.<span class="hljs-property">RTLD_NOW</span>);
<span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span>.<span class="hljs-title function_">foo</span>();</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>process.emitWarning(warning[, options])</code><span><a class="mark" href="#all_process_processemitwarningwarning-options" id="all_process_processemitwarningwarning-options">#</a></span><a aria-hidden="true" class="legacy" id="process_process_emitwarning_warning_options"></a></h3>
<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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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="#all_process_event-warning"><code>'warning'</code></a> event.</p>

<pre class="with-48-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { emitWarning } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-comment">// Emit a warning with a code and additional detail.</span>
<span class="hljs-title function_">emitWarning</span>(<span class="hljs-string">'Something happened!'</span>, {
  <span class="hljs-attr">code</span>: <span class="hljs-string">'MY_WARNING'</span>,
  <span class="hljs-attr">detail</span>: <span class="hljs-string">'This is some additional information'</span>,
});
<span class="hljs-comment">// Emits:</span>
<span class="hljs-comment">// (node:56338) [MY_WARNING] Warning: Something happened!</span>
<span class="hljs-comment">// This is some additional information</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { emitWarning } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-comment">// Emit a warning with a code and additional detail.</span>
<span class="hljs-title function_">emitWarning</span>(<span class="hljs-string">'Something happened!'</span>, {
  <span class="hljs-attr">code</span>: <span class="hljs-string">'MY_WARNING'</span>,
  <span class="hljs-attr">detail</span>: <span class="hljs-string">'This is some additional information'</span>,
});
<span class="hljs-comment">// Emits:</span>
<span class="hljs-comment">// (node:56338) [MY_WARNING] Warning: Something happened!</span>
<span class="hljs-comment">// This is some additional information</span></code><button class="copy-button">copy</button></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="#all_process_event-warning"><code>'warning'</code></a> handler.</p>

<pre class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'warning'</span>, <span class="hljs-function">(<span class="hljs-params">warning</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">name</span>);    <span class="hljs-comment">// 'Warning'</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">message</span>); <span class="hljs-comment">// 'Something happened!'</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">code</span>);    <span class="hljs-comment">// 'MY_WARNING'</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">stack</span>);   <span class="hljs-comment">// Stack trace</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">detail</span>);  <span class="hljs-comment">// 'This is some additional information'</span>
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'warning'</span>, <span class="hljs-function">(<span class="hljs-params">warning</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">name</span>);    <span class="hljs-comment">// 'Warning'</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">message</span>); <span class="hljs-comment">// 'Something happened!'</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">code</span>);    <span class="hljs-comment">// 'MY_WARNING'</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">stack</span>);   <span class="hljs-comment">// Stack trace</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">detail</span>);  <span class="hljs-comment">// 'This is some additional information'</span>
});</code><button class="copy-button">copy</button></pre>
<p>If <code>warning</code> is passed as an <code>Error</code> object, the <code>options</code> argument is ignored.</p>
</section><section><h3><code>process.emitWarning(warning[, type[, code]][, ctor])</code><span><a class="mark" href="#all_process_processemitwarningwarning-type-code-ctor" id="all_process_processemitwarningwarning-type-code-ctor">#</a></span><a aria-hidden="true" class="legacy" id="process_process_emitwarning_warning_type_code_ctor"></a></h3>
<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="#all_process_event-warning"><code>'warning'</code></a> event.</p>

<pre class="with-48-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { emitWarning } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-comment">// Emit a warning using a string.</span>
<span class="hljs-title function_">emitWarning</span>(<span class="hljs-string">'Something happened!'</span>);
<span class="hljs-comment">// Emits: (node: 56338) Warning: Something happened!</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { emitWarning } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-comment">// Emit a warning using a string.</span>
<span class="hljs-title function_">emitWarning</span>(<span class="hljs-string">'Something happened!'</span>);
<span class="hljs-comment">// Emits: (node: 56338) Warning: Something happened!</span></code><button class="copy-button">copy</button></pre>

<pre class="with-48-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { emitWarning } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-comment">// Emit a warning using a string and a type.</span>
<span class="hljs-title function_">emitWarning</span>(<span class="hljs-string">'Something Happened!'</span>, <span class="hljs-string">'CustomWarning'</span>);
<span class="hljs-comment">// Emits: (node:56338) CustomWarning: Something Happened!</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { emitWarning } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-comment">// Emit a warning using a string and a type.</span>
<span class="hljs-title function_">emitWarning</span>(<span class="hljs-string">'Something Happened!'</span>, <span class="hljs-string">'CustomWarning'</span>);
<span class="hljs-comment">// Emits: (node:56338) CustomWarning: Something Happened!</span></code><button class="copy-button">copy</button></pre>

<pre class="with-48-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { emitWarning } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-title function_">emitWarning</span>(<span class="hljs-string">'Something happened!'</span>, <span class="hljs-string">'CustomWarning'</span>, <span class="hljs-string">'WARN001'</span>);
<span class="hljs-comment">// Emits: (node:56338) [WARN001] CustomWarning: Something happened!</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { emitWarning } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

process.<span class="hljs-title function_">emitWarning</span>(<span class="hljs-string">'Something happened!'</span>, <span class="hljs-string">'CustomWarning'</span>, <span class="hljs-string">'WARN001'</span>);
<span class="hljs-comment">// Emits: (node:56338) [WARN001] CustomWarning: Something happened!</span></code><button class="copy-button">copy</button></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="#all_process_event-warning"><code>'warning'</code></a>
handler.</p>

<pre class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'warning'</span>, <span class="hljs-function">(<span class="hljs-params">warning</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">name</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">message</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">code</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">stack</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'warning'</span>, <span class="hljs-function">(<span class="hljs-params">warning</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">name</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">message</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">code</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">warn</span>(warning.<span class="hljs-property">stack</span>);
});</code><button class="copy-button">copy</button></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 class="with-48-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { emitWarning } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-comment">// Emit a warning using an Error object.</span>
<span class="hljs-keyword">const</span> myWarning = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Something happened!'</span>);
<span class="hljs-comment">// Use the Error name property to specify the type name</span>
myWarning.<span class="hljs-property">name</span> = <span class="hljs-string">'CustomWarning'</span>;
myWarning.<span class="hljs-property">code</span> = <span class="hljs-string">'WARN001'</span>;

<span class="hljs-title function_">emitWarning</span>(myWarning);
<span class="hljs-comment">// Emits: (node:56338) [WARN001] CustomWarning: Something happened!</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { emitWarning } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-comment">// Emit a warning using an Error object.</span>
<span class="hljs-keyword">const</span> myWarning = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'Something happened!'</span>);
<span class="hljs-comment">// Use the Error name property to specify the type name</span>
myWarning.<span class="hljs-property">name</span> = <span class="hljs-string">'CustomWarning'</span>;
myWarning.<span class="hljs-property">code</span> = <span class="hljs-string">'WARN001'</span>;

<span class="hljs-title function_">emitWarning</span>(myWarning);
<span class="hljs-comment">// Emits: (node:56338) [WARN001] CustomWarning: Something happened!</span></code><button class="copy-button">copy</button></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>
<h4>Avoiding duplicate warnings<span><a class="mark" href="#all_process_avoiding-duplicate-warnings" id="all_process_avoiding-duplicate-warnings">#</a></span><a aria-hidden="true" class="legacy" id="process_avoiding_duplicate_warnings"></a></h4>
<p>As a best practice, warnings should be emitted only once per process. To do
so, place the <code>emitWarning()</code> behind a boolean.</p>

<pre class="with-48-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { emitWarning } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-keyword">function</span> <span class="hljs-title function_">emitMyWarning</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">if</span> (!emitMyWarning.<span class="hljs-property">warned</span>) {
    emitMyWarning.<span class="hljs-property">warned</span> = <span class="hljs-literal">true</span>;
    <span class="hljs-title function_">emitWarning</span>(<span class="hljs-string">'Only warn once!'</span>);
  }
}
<span class="hljs-title function_">emitMyWarning</span>();
<span class="hljs-comment">// Emits: (node: 56339) Warning: Only warn once!</span>
<span class="hljs-title function_">emitMyWarning</span>();
<span class="hljs-comment">// Emits nothing</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { emitWarning } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-keyword">function</span> <span class="hljs-title function_">emitMyWarning</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">if</span> (!emitMyWarning.<span class="hljs-property">warned</span>) {
    emitMyWarning.<span class="hljs-property">warned</span> = <span class="hljs-literal">true</span>;
    <span class="hljs-title function_">emitWarning</span>(<span class="hljs-string">'Only warn once!'</span>);
  }
}
<span class="hljs-title function_">emitMyWarning</span>();
<span class="hljs-comment">// Emits: (node: 56339) Warning: Only warn once!</span>
<span class="hljs-title function_">emitMyWarning</span>();
<span class="hljs-comment">// Emits nothing</span></code><button class="copy-button">copy</button></pre>
</section><section><h3><code>process.env</code><span><a class="mark" href="#all_process_processenv" id="all_process_processenv">#</a></span><a aria-hidden="true" class="legacy" id="process_process_env"></a></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>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">{
  <span class="hljs-attr">TERM</span>: <span class="hljs-string">'xterm-256color'</span>,
  <span class="hljs-attr">SHELL</span>: <span class="hljs-string">'/usr/local/bin/bash'</span>,
  <span class="hljs-attr">USER</span>: <span class="hljs-string">'maciej'</span>,
  <span class="hljs-attr">PATH</span>: <span class="hljs-string">'~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin'</span>,
  <span class="hljs-attr">PWD</span>: <span class="hljs-string">'/Users/maciej'</span>,
  <span class="hljs-attr">EDITOR</span>: <span class="hljs-string">'vim'</span>,
  <span class="hljs-attr">SHLVL</span>: <span class="hljs-string">'1'</span>,
  <span class="hljs-attr">HOME</span>: <span class="hljs-string">'/Users/maciej'</span>,
  <span class="hljs-attr">LOGNAME</span>: <span class="hljs-string">'maciej'</span>,
  <span class="hljs-attr">_</span>: <span class="hljs-string">'/usr/local/bin/node'</span>
}</code> <button class="copy-button">copy</button></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="#all_worker_threads_class-worker"><code>Worker</code></a> threads.
In other words, the following example would not work:</p>
<pre><code class="language-bash">node -e <span class="hljs-string">'process.env.foo = "bar"'</span> &#x26;&#x26; <span class="hljs-built_in">echo</span> <span class="hljs-variable">$foo</span></code> <button class="copy-button">copy</button></pre>
<p>While the following will:</p>

<pre class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { env } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

env.<span class="hljs-property">foo</span> = <span class="hljs-string">'bar'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(env.<span class="hljs-property">foo</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { env } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

env.<span class="hljs-property">foo</span> = <span class="hljs-string">'bar'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(env.<span class="hljs-property">foo</span>);</code><button class="copy-button">copy</button></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 class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { env } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

env.<span class="hljs-property">test</span> = <span class="hljs-literal">null</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(env.<span class="hljs-property">test</span>);
<span class="hljs-comment">// => 'null'</span>
env.<span class="hljs-property">test</span> = <span class="hljs-literal">undefined</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(env.<span class="hljs-property">test</span>);
<span class="hljs-comment">// => 'undefined'</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { env } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

env.<span class="hljs-property">test</span> = <span class="hljs-literal">null</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(env.<span class="hljs-property">test</span>);
<span class="hljs-comment">// => 'null'</span>
env.<span class="hljs-property">test</span> = <span class="hljs-literal">undefined</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(env.<span class="hljs-property">test</span>);
<span class="hljs-comment">// => 'undefined'</span></code><button class="copy-button">copy</button></pre>
<p>Use <code>delete</code> to delete a property from <code>process.env</code>.</p>

<pre class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { env } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

env.<span class="hljs-property">TEST</span> = <span class="hljs-number">1</span>;
<span class="hljs-keyword">delete</span> env.<span class="hljs-property">TEST</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(env.<span class="hljs-property">TEST</span>);
<span class="hljs-comment">// => undefined</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { env } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

env.<span class="hljs-property">TEST</span> = <span class="hljs-number">1</span>;
<span class="hljs-keyword">delete</span> env.<span class="hljs-property">TEST</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(env.<span class="hljs-property">TEST</span>);
<span class="hljs-comment">// => undefined</span></code><button class="copy-button">copy</button></pre>
<p>On Windows operating systems, environment variables are case-insensitive.</p>

<pre class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { env } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

env.<span class="hljs-property">TEST</span> = <span class="hljs-number">1</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(env.<span class="hljs-property">test</span>);
<span class="hljs-comment">// => 1</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { env } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

env.<span class="hljs-property">TEST</span> = <span class="hljs-number">1</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(env.<span class="hljs-property">test</span>);
<span class="hljs-comment">// => 1</span></code><button class="copy-button">copy</button></pre>
<p>Unless explicitly specified when creating a <a href="#all_worker_threads_class-worker"><code>Worker</code></a> instance,
each <a href="#all_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="#all_worker_threads_class-worker"><code>Worker</code></a> constructor. Changes to <code>process.env</code> will not be visible
across <a href="#all_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. On Windows, a copy of
<code>process.env</code> on a <a href="#all_worker_threads_class-worker"><code>Worker</code></a> instance operates in a case-sensitive manner
unlike the main thread.</p>
</section><section><h3><code>process.execArgv</code><span><a class="mark" href="#all_process_processexecargv" id="all_process_processexecargv">#</a></span><a aria-hidden="true" class="legacy" id="process_process_execargv"></a></h3>
<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="#all_process_processargv"><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-bash">node --icu-data-dir=./foo --require ./bar.js script.js --version</code> <button class="copy-button">copy</button></pre>
<p>Results in <code>process.execArgv</code>:</p>
<pre><code class="language-json"><span class="hljs-punctuation">[</span><span class="hljs-string">"--icu-data-dir=./foo"</span><span class="hljs-punctuation">,</span> <span class="hljs-string">"--require"</span><span class="hljs-punctuation">,</span> <span class="hljs-string">"./bar.js"</span><span class="hljs-punctuation">]</span></code> <button class="copy-button">copy</button></pre>
<p>And <code>process.argv</code>:</p>
<!-- eslint-disable @stylistic/js/semi -->
<pre><code class="language-js">[<span class="hljs-string">'/usr/local/bin/node'</span>, <span class="hljs-string">'script.js'</span>, <span class="hljs-string">'--version'</span>]</code> <button class="copy-button">copy</button></pre>
<p>Refer to <a href="#all_worker_threads_new-workerfilename-options"><code>Worker</code> constructor</a> for the detailed behavior of worker
threads with this property.</p>
</section><section><h3><code>process.execPath</code><span><a class="mark" href="#all_process_processexecpath" id="all_process_processexecpath">#</a></span><a aria-hidden="true" class="legacy" id="process_process_execpath"></a></h3>
<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. Symbolic links, if any, are resolved.</p>
<!-- eslint-disable @stylistic/js/semi -->
<pre><code class="language-js"><span class="hljs-string">'/usr/local/bin/node'</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>process.exit([code])</code><span><a class="mark" href="#all_process_processexitcode" id="all_process_processexitcode">#</a></span><a aria-hidden="true" class="legacy" id="process_process_exit_code"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>Only accepts a code of type number, or of type string if it represents an integer.</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><code>code</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 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> The exit code. For string type, only
integer strings (e.g.,'1') are allowed. <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="#all_process_event-exit"><code>'exit'</code></a> event listeners are
called.</p>
<p>To exit with a 'failure' code:</p>

<pre class="with-41-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { exit } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-title function_">exit</span>(<span class="hljs-number">1</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { exit } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-title function_">exit</span>(<span class="hljs-number">1</span>);</code><button class="copy-button">copy</button></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 class="with-41-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { exit } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-comment">// This is an example of what *not* to do:</span>
<span class="hljs-keyword">if</span> (<span class="hljs-title function_">someConditionNotMet</span>()) {
  <span class="hljs-title function_">printUsageToStdout</span>();
  <span class="hljs-title function_">exit</span>(<span class="hljs-number">1</span>);
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { exit } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-comment">// This is an example of what *not* to do:</span>
<span class="hljs-keyword">if</span> (<span class="hljs-title function_">someConditionNotMet</span>()) {
  <span class="hljs-title function_">printUsageToStdout</span>();
  <span class="hljs-title function_">exit</span>(<span class="hljs-number">1</span>);
}</code><button class="copy-button">copy</button></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 class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-comment">// How to properly set the exit code while letting</span>
<span class="hljs-comment">// the process exit gracefully.</span>
<span class="hljs-keyword">if</span> (<span class="hljs-title function_">someConditionNotMet</span>()) {
  <span class="hljs-title function_">printUsageToStdout</span>();
  process.<span class="hljs-property">exitCode</span> = <span class="hljs-number">1</span>;
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-comment">// How to properly set the exit code while letting</span>
<span class="hljs-comment">// the process exit gracefully.</span>
<span class="hljs-keyword">if</span> (<span class="hljs-title function_">someConditionNotMet</span>()) {
  <span class="hljs-title function_">printUsageToStdout</span>();
  process.<span class="hljs-property">exitCode</span> = <span class="hljs-number">1</span>;
}</code><button class="copy-button">copy</button></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="#all_worker_threads_class-worker"><code>Worker</code></a> threads, this function stops the current thread rather
than the current process.</p>
</section><section><h3><code>process.exitCode</code><span><a class="mark" href="#all_process_processexitcode_1" id="all_process_processexitcode_1">#</a></span><a aria-hidden="true" class="legacy" id="process_process_exitcode"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>Only accepts a code of type number, or of type string if it represents an integer.</p></td></tr>
<tr><td>v0.11.8</td>
<td><p><span>Added in: v0.11.8</span></p></td></tr>
</tbody></table>
</details>
</div>
<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#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> The exit code. For string type, only
integer strings (e.g.,'1') are allowed. <strong>Default:</strong> <code>undefined</code>.</li>
</ul>
<p>A number which will be the process exit code, when the process either
exits gracefully, or is exited via <a href="#all_process_processexitcode"><code>process.exit()</code></a> without specifying
a code.</p>
<p>Specifying a code to <a href="#all_process_processexitcode"><code>process.exit(code)</code></a> will override any
previous setting of <code>process.exitCode</code>.</p>
</section><section><h3><code>process.getActiveResourcesInfo()</code><span><a class="mark" href="#all_process_processgetactiveresourcesinfo" id="all_process_processgetactiveresourcesinfo">#</a></span><a aria-hidden="true" class="legacy" id="process_process_getactiveresourcesinfo"></a></h3>
<div class="api_metadata">
<span>Added in: v17.3.0, v16.14.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<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.getActiveResourcesInfo()</code> method returns an array of strings
containing the types of the active resources that are currently keeping the
event loop alive.</p>

<pre class="with-59-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { getActiveResourcesInfo } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-built_in">setTimeout</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:timers'</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Before:'</span>, <span class="hljs-title function_">getActiveResourcesInfo</span>());
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {}, <span class="hljs-number">1000</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'After:'</span>, <span class="hljs-title function_">getActiveResourcesInfo</span>());
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   Before: [ 'CloseReq', 'TTYWrap', 'TTYWrap', 'TTYWrap' ]</span>
<span class="hljs-comment">//   After: [ 'CloseReq', 'TTYWrap', 'TTYWrap', 'TTYWrap', 'Timeout' ]</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { getActiveResourcesInfo } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-built_in">setTimeout</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:timers'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Before:'</span>, <span class="hljs-title function_">getActiveResourcesInfo</span>());
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {}, <span class="hljs-number">1000</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'After:'</span>, <span class="hljs-title function_">getActiveResourcesInfo</span>());
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   Before: [ 'TTYWrap', 'TTYWrap', 'TTYWrap' ]</span>
<span class="hljs-comment">//   After: [ 'TTYWrap', 'TTYWrap', 'TTYWrap', 'Timeout' ]</span></code><button class="copy-button">copy</button></pre>
</section><section><h3><code>process.getBuiltinModule(id)</code><span><a class="mark" href="#all_process_processgetbuiltinmoduleid" id="all_process_processgetbuiltinmoduleid">#</a></span><a aria-hidden="true" class="legacy" id="process_process_getbuiltinmodule_id"></a></h3>
<div class="api_metadata">
<span>Added in: v20.16.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> ID of the built-in module being requested.</li>
<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#Undefined_type" class="type">&#x3C;undefined></a></li>
</ul>
<p><code>process.getBuiltinModule(id)</code> provides a way to load built-in modules
in a globally available function. ES Modules that need to support
other environments can use it to conditionally load a Node.js built-in
when it is run in Node.js, without having to deal with the resolution
error that can be thrown by <code>import</code> in a non-Node.js environment or
having to use dynamic <code>import()</code> which either turns the module into
an asynchronous module, or turns a synchronous API into an asynchronous one.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">if</span> (globalThis.<span class="hljs-property">process</span>?.<span class="hljs-property">getBuiltinModule</span>) {
  <span class="hljs-comment">// Run in Node.js, use the Node.js fs module.</span>
  <span class="hljs-keyword">const</span> fs = globalThis.<span class="hljs-property">process</span>.<span class="hljs-title function_">getBuiltinModule</span>(<span class="hljs-string">'fs'</span>);
  <span class="hljs-comment">// If `require()` is needed to load user-modules, use createRequire()</span>
  <span class="hljs-keyword">const</span> <span class="hljs-variable language_">module</span> = globalThis.<span class="hljs-property">process</span>.<span class="hljs-title function_">getBuiltinModule</span>(<span class="hljs-string">'module'</span>);
  <span class="hljs-keyword">const</span> <span class="hljs-built_in">require</span> = <span class="hljs-variable language_">module</span>.<span class="hljs-title function_">createRequire</span>(<span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>);
  <span class="hljs-keyword">const</span> foo = <span class="hljs-built_in">require</span>(<span class="hljs-string">'foo'</span>);
}</code> <button class="copy-button">copy</button></pre>
<p>If <code>id</code> specifies a built-in module available in the current Node.js process,
<code>process.getBuiltinModule(id)</code> method returns the corresponding built-in
module. If <code>id</code> does not correspond to any built-in module, <code>undefined</code>
is returned.</p>
<p><code>process.getBuiltinModule(id)</code> accepts built-in module IDs that are recognized
by <a href="#all_module_moduleisbuiltinmodulename"><code>module.isBuiltin(id)</code></a>. Some built-in modules must be loaded with the
<code>node:</code> prefix, see <a href="#all_modules_built-in-modules-with-mandatory-node-prefix">built-in modules with mandatory <code>node:</code> prefix</a>.
The references returned by <code>process.getBuiltinModule(id)</code> always point to
the built-in module corresponding to <code>id</code> even if users modify
<a href="#all_modules_requirecache"><code>require.cache</code></a> so that <code>require(id)</code> returns something else.</p>
</section><section><h3><code>process.getegid()</code><span><a class="mark" href="#all_process_processgetegid" id="all_process_processgetegid">#</a></span><a aria-hidden="true" class="legacy" id="process_process_getegid"></a></h3>
<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 class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-keyword">if</span> (process.<span class="hljs-property">getegid</span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Current gid: <span class="hljs-subst">${process.getegid()}</span>`</span>);
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-keyword">if</span> (process.<span class="hljs-property">getegid</span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Current gid: <span class="hljs-subst">${process.getegid()}</span>`</span>);
}</code><button class="copy-button">copy</button></pre>
<p>This function is only available on POSIX platforms (i.e. not Windows or
Android).</p>
</section><section><h3><code>process.geteuid()</code><span><a class="mark" href="#all_process_processgeteuid" id="all_process_processgeteuid">#</a></span><a aria-hidden="true" class="legacy" id="process_process_geteuid"></a></h3>
<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 class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-keyword">if</span> (process.<span class="hljs-property">geteuid</span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Current uid: <span class="hljs-subst">${process.geteuid()}</span>`</span>);
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-keyword">if</span> (process.<span class="hljs-property">geteuid</span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Current uid: <span class="hljs-subst">${process.geteuid()}</span>`</span>);
}</code><button class="copy-button">copy</button></pre>
<p>This function is only available on POSIX platforms (i.e. not Windows or
Android).</p>
</section><section><h3><code>process.getgid()</code><span><a class="mark" href="#all_process_processgetgid" id="all_process_processgetgid">#</a></span><a aria-hidden="true" class="legacy" id="process_process_getgid"></a></h3>
<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 class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-keyword">if</span> (process.<span class="hljs-property">getgid</span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Current gid: <span class="hljs-subst">${process.getgid()}</span>`</span>);
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-keyword">if</span> (process.<span class="hljs-property">getgid</span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Current gid: <span class="hljs-subst">${process.getgid()}</span>`</span>);
}</code><button class="copy-button">copy</button></pre>
<p>This function is only available on POSIX platforms (i.e. not Windows or
Android).</p>
</section><section><h3><code>process.getgroups()</code><span><a class="mark" href="#all_process_processgetgroups" id="all_process_processgetgroups">#</a></span><a aria-hidden="true" class="legacy" id="process_process_getgroups"></a></h3>
<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>

<pre class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-keyword">if</span> (process.<span class="hljs-property">getgroups</span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(process.<span class="hljs-title function_">getgroups</span>()); <span class="hljs-comment">// [ 16, 21, 297 ]</span>
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-keyword">if</span> (process.<span class="hljs-property">getgroups</span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(process.<span class="hljs-title function_">getgroups</span>()); <span class="hljs-comment">// [ 16, 21, 297 ]</span>
}</code><button class="copy-button">copy</button></pre>
<p>This function is only available on POSIX platforms (i.e. not Windows or
Android).</p>
</section><section><h3><code>process.getuid()</code><span><a class="mark" href="#all_process_processgetuid" id="all_process_processgetuid">#</a></span><a aria-hidden="true" class="legacy" id="process_process_getuid"></a></h3>
<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 class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-keyword">if</span> (process.<span class="hljs-property">getuid</span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Current uid: <span class="hljs-subst">${process.getuid()}</span>`</span>);
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-keyword">if</span> (process.<span class="hljs-property">getuid</span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Current uid: <span class="hljs-subst">${process.getuid()}</span>`</span>);
}</code><button class="copy-button">copy</button></pre>
<p>This function is only available on POSIX platforms (i.e. not Windows or
Android).</p>
</section><section><h3><code>process.hasUncaughtExceptionCaptureCallback()</code><span><a class="mark" href="#all_process_processhasuncaughtexceptioncapturecallback" id="all_process_processhasuncaughtexceptioncapturecallback">#</a></span><a aria-hidden="true" class="legacy" id="process_process_hasuncaughtexceptioncapturecallback"></a></h3>
<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="#all_process_processsetuncaughtexceptioncapturecallbackfn"><code>process.setUncaughtExceptionCaptureCallback()</code></a>.</p>
</section><section><h3><code>process.hrtime([time])</code><span><a class="mark" href="#all_process_processhrtimetime" id="all_process_processhrtimetime">#</a></span><a aria-hidden="true" class="legacy" id="process_process_hrtime_time"></a></h3>
<div class="api_metadata">
<span>Added in: v0.7.6</span>
</div>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy. Use <a href="#all_process_processhrtimebigint"><code>process.hrtime.bigint()</code></a> instead.</div><p></p>
<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="#all_process_processhrtimebigint"><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 class="with-43-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { hrtime } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-keyword">const</span> <span class="hljs-variable constant_">NS_PER_SEC</span> = <span class="hljs-number">1e9</span>;
<span class="hljs-keyword">const</span> time = <span class="hljs-title function_">hrtime</span>();
<span class="hljs-comment">// [ 1800216, 25 ]</span>

<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
  <span class="hljs-keyword">const</span> diff = <span class="hljs-title function_">hrtime</span>(time);
  <span class="hljs-comment">// [ 1, 552 ]</span>

  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Benchmark took <span class="hljs-subst">${diff[<span class="hljs-number">0</span>] * NS_PER_SEC + diff[<span class="hljs-number">1</span>]}</span> nanoseconds`</span>);
  <span class="hljs-comment">// Benchmark took 1000000552 nanoseconds</span>
}, <span class="hljs-number">1000</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { hrtime } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-keyword">const</span> <span class="hljs-variable constant_">NS_PER_SEC</span> = <span class="hljs-number">1e9</span>;
<span class="hljs-keyword">const</span> time = <span class="hljs-title function_">hrtime</span>();
<span class="hljs-comment">// [ 1800216, 25 ]</span>

<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
  <span class="hljs-keyword">const</span> diff = <span class="hljs-title function_">hrtime</span>(time);
  <span class="hljs-comment">// [ 1, 552 ]</span>

  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Benchmark took <span class="hljs-subst">${diff[<span class="hljs-number">0</span>] * NS_PER_SEC + diff[<span class="hljs-number">1</span>]}</span> nanoseconds`</span>);
  <span class="hljs-comment">// Benchmark took 1000000552 nanoseconds</span>
}, <span class="hljs-number">1000</span>);</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>process.hrtime.bigint()</code><span><a class="mark" href="#all_process_processhrtimebigint" id="all_process_processhrtimebigint">#</a></span><a aria-hidden="true" class="legacy" id="process_process_hrtime_bigint"></a></h3>
<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="#all_process_processhrtimetime"><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="#all_process_processhrtimetime"><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 class="with-43-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { hrtime } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-keyword">const</span> start = hrtime.<span class="hljs-title function_">bigint</span>();
<span class="hljs-comment">// 191051479007711n</span>

<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
  <span class="hljs-keyword">const</span> end = hrtime.<span class="hljs-title function_">bigint</span>();
  <span class="hljs-comment">// 191052633396993n</span>

  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Benchmark took <span class="hljs-subst">${end - start}</span> nanoseconds`</span>);
  <span class="hljs-comment">// Benchmark took 1154389282 nanoseconds</span>
}, <span class="hljs-number">1000</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { hrtime } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-keyword">const</span> start = hrtime.<span class="hljs-title function_">bigint</span>();
<span class="hljs-comment">// 191051479007711n</span>

<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
  <span class="hljs-keyword">const</span> end = hrtime.<span class="hljs-title function_">bigint</span>();
  <span class="hljs-comment">// 191052633396993n</span>

  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Benchmark took <span class="hljs-subst">${end - start}</span> nanoseconds`</span>);
  <span class="hljs-comment">// Benchmark took 1154389282 nanoseconds</span>
}, <span class="hljs-number">1000</span>);</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>process.initgroups(user, extraGroup)</code><span><a class="mark" href="#all_process_processinitgroupsuser-extragroup" id="all_process_processinitgroupsuser-extragroup">#</a></span><a aria-hidden="true" class="legacy" id="process_process_initgroups_user_extragroup"></a></h3>
<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 class="with-66-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { getgroups, initgroups, setgid } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getgroups</span>());         <span class="hljs-comment">// [ 0 ]</span>
<span class="hljs-title function_">initgroups</span>(<span class="hljs-string">'nodeuser'</span>, <span class="hljs-number">1000</span>);     <span class="hljs-comment">// switch user</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getgroups</span>());         <span class="hljs-comment">// [ 27, 30, 46, 1000, 0 ]</span>
<span class="hljs-title function_">setgid</span>(<span class="hljs-number">1000</span>);                     <span class="hljs-comment">// drop root gid</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getgroups</span>());         <span class="hljs-comment">// [ 27, 30, 46, 1000 ]</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { getgroups, initgroups, setgid } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getgroups</span>());         <span class="hljs-comment">// [ 0 ]</span>
<span class="hljs-title function_">initgroups</span>(<span class="hljs-string">'nodeuser'</span>, <span class="hljs-number">1000</span>);     <span class="hljs-comment">// switch user</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getgroups</span>());         <span class="hljs-comment">// [ 27, 30, 46, 1000, 0 ]</span>
<span class="hljs-title function_">setgid</span>(<span class="hljs-number">1000</span>);                     <span class="hljs-comment">// drop root gid</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getgroups</span>());         <span class="hljs-comment">// [ 27, 30, 46, 1000 ]</span></code><button class="copy-button">copy</button></pre>
<p>This function is only available on POSIX platforms (i.e. not Windows or
Android).
This feature is not available in <a href="#all_worker_threads_class-worker"><code>Worker</code></a> threads.</p>
</section><section><h3><code>process.kill(pid[, signal])</code><span><a class="mark" href="#all_process_processkillpid-signal" id="all_process_processkillpid-signal">#</a></span><a aria-hidden="true" class="legacy" id="process_process_kill_pid_signal"></a></h3>
<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="#all_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 class="with-45-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> process, { kill } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'SIGHUP'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Got SIGHUP signal.'</span>);
});

<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Exiting.'</span>);
  process.<span class="hljs-title function_">exit</span>(<span class="hljs-number">0</span>);
}, <span class="hljs-number">100</span>);

<span class="hljs-title function_">kill</span>(process.<span class="hljs-property">pid</span>, <span class="hljs-string">'SIGHUP'</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'SIGHUP'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Got SIGHUP signal.'</span>);
});

<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Exiting.'</span>);
  process.<span class="hljs-title function_">exit</span>(<span class="hljs-number">0</span>);
}, <span class="hljs-number">100</span>);

process.<span class="hljs-title function_">kill</span>(process.<span class="hljs-property">pid</span>, <span class="hljs-string">'SIGHUP'</span>);</code><button class="copy-button">copy</button></pre>
<p>When <code>SIGUSR1</code> is received by a Node.js process, Node.js will start the
debugger. See <a href="#all_process_signal-events">Signal Events</a>.</p>
</section><section><h3><code>process.loadEnvFile(path)</code><span><a class="mark" href="#all_process_processloadenvfilepath" id="all_process_processloadenvfilepath">#</a></span><a aria-hidden="true" class="legacy" id="process_process_loadenvfile_path"></a></h3>
<div class="api_metadata">
<span>Added in: v20.12.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active development</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="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></a> | <a href="#all_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>. <strong>Default:</strong> <code>'./.env'</code></li>
</ul>
<p>Loads the <code>.env</code> file into <code>process.env</code>. Usage of <code>NODE_OPTIONS</code>
in the <code>.env</code> file will not have any effect on Node.js.</p>

<pre class="with-48-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { loadEnvFile } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-title function_">loadEnvFile</span>();</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { loadEnvFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-title function_">loadEnvFile</span>();</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>process.mainModule</code><span><a class="mark" href="#all_process_processmainmodule" id="all_process_processmainmodule">#</a></span><a aria-hidden="true" class="legacy" id="process_process_mainmodule"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.17</span><span>Deprecated since: v14.0.0</span>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_modules_accessing-the-main-module"><code>require.main</code></a> instead.</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>The <code>process.mainModule</code> property provides an alternative way of retrieving
<a href="#all_modules_accessing-the-main-module"><code>require.main</code></a>. The difference is that if the main module changes at
runtime, <a href="#all_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="#all_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>
</section><section><h3><code>process.memoryUsage()</code><span><a class="mark" href="#all_process_processmemoryusage" id="all_process_processmemoryusage">#</a></span><a aria-hidden="true" class="legacy" id="process_process_memoryusage"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.9.0, 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>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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>Returns an object describing the memory usage of the Node.js process measured in
bytes.</p>

<pre class="with-48-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { memoryUsage } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">memoryUsage</span>());
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// {</span>
<span class="hljs-comment">//  rss: 4935680,</span>
<span class="hljs-comment">//  heapTotal: 1826816,</span>
<span class="hljs-comment">//  heapUsed: 650472,</span>
<span class="hljs-comment">//  external: 49879,</span>
<span class="hljs-comment">//  arrayBuffers: 9386</span>
<span class="hljs-comment">// }</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { memoryUsage } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">memoryUsage</span>());
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">// {</span>
<span class="hljs-comment">//  rss: 4935680,</span>
<span class="hljs-comment">//  heapTotal: 1826816,</span>
<span class="hljs-comment">//  heapUsed: 650472,</span>
<span class="hljs-comment">//  external: 49879,</span>
<span class="hljs-comment">//  arrayBuffers: 9386</span>
<span class="hljs-comment">// }</span></code><button class="copy-button">copy</button></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="#all_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>
<p>The <code>process.memoryUsage()</code> method iterates over each page to gather
information about memory usage which might be slow depending on the
program memory allocations.</p>
</section><section><h3><code>process.memoryUsage.rss()</code><span><a class="mark" href="#all_process_processmemoryusagerss" id="all_process_processmemoryusagerss">#</a></span><a aria-hidden="true" class="legacy" id="process_process_memoryusage_rss"></a></h3>
<div class="api_metadata">
<span>Added in: v15.6.0, v14.18.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>The <code>process.memoryUsage.rss()</code> method returns an integer representing the
Resident Set Size (RSS) in bytes.</p>
<p>The 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.</p>
<p>This is the same value as the <code>rss</code> property provided by <code>process.memoryUsage()</code>
but <code>process.memoryUsage.rss()</code> is faster.</p>

<pre class="with-48-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { memoryUsage } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(memoryUsage.<span class="hljs-title function_">rss</span>());
<span class="hljs-comment">// 35655680</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { memoryUsage } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(memoryUsage.<span class="hljs-title function_">rss</span>());
<span class="hljs-comment">// 35655680</span></code><button class="copy-button">copy</button></pre>
</section><section><h3><code>process.nextTick(callback[, ...args])</code><span><a class="mark" href="#all_process_processnexttickcallback-args" id="all_process_processnexttickcallback-args">#</a></span><a aria-hidden="true" class="legacy" id="process_process_nexttick_callback_args"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.18.0</td>
<td><p>Changed stability to Legacy.</p></td></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></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>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy: Use <a href="#all_globals_queuemicrotaskcallback"><code>queueMicrotask()</code></a> instead.</div><p></p>
<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/learn/asynchronous-work/event-loop-timers-and-nexttick#understanding-processnexttick">Event Loop</a> guide for more background.</p>

<pre class="with-45-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { nextTick } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'start'</span>);
<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'nextTick callback'</span>);
});
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'scheduled'</span>);
<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// start</span>
<span class="hljs-comment">// scheduled</span>
<span class="hljs-comment">// nextTick callback</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { nextTick } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'start'</span>);
<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'nextTick callback'</span>);
});
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'scheduled'</span>);
<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// start</span>
<span class="hljs-comment">// scheduled</span>
<span class="hljs-comment">// nextTick callback</span></code><button class="copy-button">copy</button></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 class="with-45-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { nextTick } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-keyword">function</span> <span class="hljs-title function_">MyThing</span>(<span class="hljs-params">options</span>) {
  <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">setupOptions</span>(options);

  <span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> {
    <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">startDoingStuff</span>();
  });
}

<span class="hljs-keyword">const</span> thing = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyThing</span>();
thing.<span class="hljs-title function_">getReadyForStuff</span>();

<span class="hljs-comment">// thing.startDoingStuff() gets called now, not before.</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { nextTick } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-keyword">function</span> <span class="hljs-title function_">MyThing</span>(<span class="hljs-params">options</span>) {
  <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">setupOptions</span>(options);

  <span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> {
    <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">startDoingStuff</span>();
  });
}

<span class="hljs-keyword">const</span> thing = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyThing</span>();
thing.<span class="hljs-title function_">getReadyForStuff</span>();

<span class="hljs-comment">// thing.startDoingStuff() gets called now, not before.</span></code><button class="copy-button">copy</button></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"><span class="hljs-comment">// WARNING!  DO NOT USE!  BAD UNSAFE HAZARD!</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">maybeSync</span>(<span class="hljs-params">arg, cb</span>) {
  <span class="hljs-keyword">if</span> (arg) {
    <span class="hljs-title function_">cb</span>();
    <span class="hljs-keyword">return</span>;
  }

  fs.<span class="hljs-title function_">stat</span>(<span class="hljs-string">'file'</span>, cb);
}</code> <button class="copy-button">copy</button></pre>
<p>This API is hazardous because in the following case:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> maybeTrue = <span class="hljs-title class_">Math</span>.<span class="hljs-title function_">random</span>() > <span class="hljs-number">0.5</span>;

<span class="hljs-title function_">maybeSync</span>(maybeTrue, <span class="hljs-function">() =></span> {
  <span class="hljs-title function_">foo</span>();
});

<span class="hljs-title function_">bar</span>();</code> <button class="copy-button">copy</button></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 class="with-45-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { nextTick } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-keyword">function</span> <span class="hljs-title function_">definitelyAsync</span>(<span class="hljs-params">arg, cb</span>) {
  <span class="hljs-keyword">if</span> (arg) {
    <span class="hljs-title function_">nextTick</span>(cb);
    <span class="hljs-keyword">return</span>;
  }

  fs.<span class="hljs-title function_">stat</span>(<span class="hljs-string">'file'</span>, cb);
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { nextTick } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-keyword">function</span> <span class="hljs-title function_">definitelyAsync</span>(<span class="hljs-params">arg, cb</span>) {
  <span class="hljs-keyword">if</span> (arg) {
    <span class="hljs-title function_">nextTick</span>(cb);
    <span class="hljs-keyword">return</span>;
  }

  fs.<span class="hljs-title function_">stat</span>(<span class="hljs-string">'file'</span>, cb);
}</code><button class="copy-button">copy</button></pre>
<h4>When to use <code>queueMicrotask()</code> vs. <code>process.nextTick()</code><span><a class="mark" href="#all_process_when-to-use-queuemicrotask-vs-processnexttick" id="all_process_when-to-use-queuemicrotask-vs-processnexttick">#</a></span><a aria-hidden="true" class="legacy" id="process_when_to_use_queuemicrotask_vs_process_nexttick"></a></h4>
<p>The <a href="#all_globals_queuemicrotaskcallback"><code>queueMicrotask()</code></a> API is an alternative to <code>process.nextTick()</code> that
also defers execution of a function using the same microtask queue used to
execute the then, catch, and finally handlers of resolved promises. Within
Node.js, every time the "next tick queue" is drained, the microtask queue
is drained immediately after.</p>

<pre class="with-45-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { nextTick } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">resolve</span>().<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-number">2</span>));
<span class="hljs-title function_">queueMicrotask</span>(<span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-number">3</span>));
<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-number">1</span>));
<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// 1</span>
<span class="hljs-comment">// 2</span>
<span class="hljs-comment">// 3</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { nextTick } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">resolve</span>().<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-number">2</span>));
<span class="hljs-title function_">queueMicrotask</span>(<span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-number">3</span>));
<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-number">1</span>));
<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// 1</span>
<span class="hljs-comment">// 2</span>
<span class="hljs-comment">// 3</span></code><button class="copy-button">copy</button></pre>
<p>For <em>most</em> userland use cases, the <code>queueMicrotask()</code> API provides a portable
and reliable mechanism for deferring execution that works across multiple
JavaScript platform environments and should be favored over <code>process.nextTick()</code>.
In simple scenarios, <code>queueMicrotask()</code> can be a drop-in replacement for
<code>process.nextTick()</code>.</p>
<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'start'</span>);
<span class="hljs-title function_">queueMicrotask</span>(<span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'microtask callback'</span>);
});
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'scheduled'</span>);
<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// start</span>
<span class="hljs-comment">// scheduled</span>
<span class="hljs-comment">// microtask callback</span></code> <button class="copy-button">copy</button></pre>
<p>One note-worthy difference between the two APIs is that <code>process.nextTick()</code>
allows specifying additional values that will be passed as arguments to the
deferred function when it is called. Achieving the same result with
<code>queueMicrotask()</code> requires using either a closure or a bound function:</p>
<pre><code class="language-js"><span class="hljs-keyword">function</span> <span class="hljs-title function_">deferred</span>(<span class="hljs-params">a, b</span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'microtask'</span>, a + b);
}

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'start'</span>);
<span class="hljs-title function_">queueMicrotask</span>(deferred.<span class="hljs-title function_">bind</span>(<span class="hljs-literal">undefined</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'scheduled'</span>);
<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// start</span>
<span class="hljs-comment">// scheduled</span>
<span class="hljs-comment">// microtask 3</span></code> <button class="copy-button">copy</button></pre>
<p>There are minor differences in the way errors raised from within the next tick
queue and microtask queue are handled. Errors thrown within a queued microtask
callback should be handled within the queued callback when possible. If they are
not, the <code>process.on('uncaughtException')</code> event handler can be used to capture
and handle the errors.</p>
<p>When in doubt, unless the specific capabilities of <code>process.nextTick()</code> are
needed, use <code>queueMicrotask()</code>.</p>
</section><section><h3><code>process.noDeprecation</code><span><a class="mark" href="#all_process_processnodeprecation" id="all_process_processnodeprecation">#</a></span><a aria-hidden="true" class="legacy" id="process_process_nodeprecation"></a></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#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="#all_process_event-warning"><code>'warning'</code> event</a> and the
<a href="#all_process_processemitwarningwarning-type-code-ctor"><code>emitWarning()</code> method</a> for more information about this
flag's behavior.</p>
</section><section><h3><code>process.permission</code><span><a class="mark" href="#all_process_processpermission" id="all_process_processpermission">#</a></span><a aria-hidden="true" class="legacy" id="process_process_permission"></a></h3>
<div class="api_metadata">
<span>Added in: v20.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>This API is available through the <a href="#all_cli_--experimental-permission"><code>--experimental-permission</code></a> flag.</p>
<p><code>process.permission</code> is an object whose methods are used to manage permissions
for the current process. Additional documentation is available in the
<a href="#all_permissions_permission-model">Permission Model</a>.</p>
<h4><code>process.permission.has(scope[, reference])</code><span><a class="mark" href="#all_process_processpermissionhasscope-reference" id="all_process_processpermissionhasscope-reference">#</a></span><a aria-hidden="true" class="legacy" id="process_process_permission_has_scope_reference"></a></h4>
<div class="api_metadata">
<span>Added in: v20.0.0</span>
</div>
<ul>
<li><code>scope</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
<li><code>reference</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>Verifies that the process is able to access the given scope and reference.
If no reference is provided, a global scope is assumed, for instance,
<code>process.permission.has('fs.read')</code> will check if the process has ALL
file system read permissions.</p>
<p>The reference has a meaning based on the provided scope. For example,
the reference when the scope is File System means files and folders.</p>
<p>The available scopes are:</p>
<ul>
<li><code>fs</code> - All File System</li>
<li><code>fs.read</code> - File System read operations</li>
<li><code>fs.write</code> - File System write operations</li>
<li><code>child</code> - Child process spawning operations</li>
<li><code>worker</code> - Worker thread spawning operation</li>
</ul>
<pre><code class="language-js"><span class="hljs-comment">// Check if the process has permission to read the README file</span>
process.<span class="hljs-property">permission</span>.<span class="hljs-title function_">has</span>(<span class="hljs-string">'fs.read'</span>, <span class="hljs-string">'./README.md'</span>);
<span class="hljs-comment">// Check if the process has read permission operations</span>
process.<span class="hljs-property">permission</span>.<span class="hljs-title function_">has</span>(<span class="hljs-string">'fs.read'</span>);</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>process.pid</code><span><a class="mark" href="#all_process_processpid" id="all_process_processpid">#</a></span><a aria-hidden="true" class="legacy" id="process_process_pid"></a></h3>
<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 class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { pid } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`This process is pid <span class="hljs-subst">${pid}</span>`</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { pid } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`This process is pid <span class="hljs-subst">${pid}</span>`</span>);</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>process.platform</code><span><a class="mark" href="#all_process_processplatform" id="all_process_processplatform">#</a></span><a aria-hidden="true" class="legacy" id="process_process_platform"></a></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 <code>process.platform</code> property returns a string identifying the operating
system platform for which the Node.js binary was compiled.</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 class="with-45-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { platform } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`This platform is <span class="hljs-subst">${platform}</span>`</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { platform } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`This platform is <span class="hljs-subst">${platform}</span>`</span>);</code><button class="copy-button">copy</button></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/HEAD/BUILDING.md#android">is experimental</a>.</p>
</section><section><h3><code>process.ppid</code><span><a class="mark" href="#all_process_processppid" id="all_process_processppid">#</a></span><a aria-hidden="true" class="legacy" id="process_process_ppid"></a></h3>
<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 parent of the
current process.</p>

<pre class="with-41-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { ppid } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`The parent process is pid <span class="hljs-subst">${ppid}</span>`</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { ppid } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`The parent process is pid <span class="hljs-subst">${ppid}</span>`</span>);</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>process.release</code><span><a class="mark" href="#all_process_processrelease" id="all_process_processrelease">#</a></span><a aria-hidden="true" class="legacy" id="process_process_release"></a></h3>
<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>.</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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> an absolute URL pointing to a <em><code>node.lib</code></em> file
matching the architecture and version of the current release. This file is
used for compiling Node.js native add-ons. <em>This property is only present on
Windows builds of Node.js and will be missing on all other platforms.</em></li>
<li><code>lts</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></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. Valid values include the
LTS Release code names (including those that are no longer supported).
<ul>
<li><code>'Fermium'</code> for the 14.x LTS line beginning with 14.15.0.</li>
<li><code>'Gallium'</code> for the 16.x LTS line beginning with 16.13.0.</li>
<li><code>'Hydrogen'</code> for the 18.x LTS line beginning with 18.12.0.
For other LTS Release code names, see <a href="https://github.com/nodejs/node/blob/HEAD/doc/changelogs/CHANGELOG_ARCHIVE.md">Node.js Changelog Archive</a></li>
</ul>
</li>
</ul>
<!-- eslint-skip -->
<pre><code class="language-js">{
  <span class="hljs-attr">name</span>: <span class="hljs-string">'node'</span>,
  <span class="hljs-attr">lts</span>: <span class="hljs-string">'Hydrogen'</span>,
  <span class="hljs-attr">sourceUrl</span>: <span class="hljs-string">'https://nodejs.org/download/release/v18.12.0/node-v18.12.0.tar.gz'</span>,
  <span class="hljs-attr">headersUrl</span>: <span class="hljs-string">'https://nodejs.org/download/release/v18.12.0/node-v18.12.0-headers.tar.gz'</span>,
  <span class="hljs-attr">libUrl</span>: <span class="hljs-string">'https://nodejs.org/download/release/v18.12.0/win-x64/node.lib'</span>
}</code> <button class="copy-button">copy</button></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>
</section><section><h3><code>process.report</code><span><a class="mark" href="#all_process_processreport" id="all_process_processreport">#</a></span><a aria-hidden="true" class="legacy" id="process_process_report"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.12.0, v12.17.0</td>
<td><p>This API is no longer 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>
<h4><code>process.report.compact</code><span><a class="mark" href="#all_process_processreportcompact" id="all_process_processreportcompact">#</a></span><a aria-hidden="true" class="legacy" id="process_process_report_compact"></a></h4>
<div class="api_metadata">
<span>Added in: v13.12.0, 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 class="with-43-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { report } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Reports are compact? <span class="hljs-subst">${report.compact}</span>`</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { report } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Reports are compact? <span class="hljs-subst">${report.compact}</span>`</span>);</code><button class="copy-button">copy</button></pre>
<h4><code>process.report.directory</code><span><a class="mark" href="#all_process_processreportdirectory" id="all_process_processreportdirectory">#</a></span><a aria-hidden="true" class="legacy" id="process_process_report_directory"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.12.0, v12.17.0</td>
<td><p>This API is no longer 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 class="with-43-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { report } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Report directory is <span class="hljs-subst">${report.directory}</span>`</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { report } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Report directory is <span class="hljs-subst">${report.directory}</span>`</span>);</code><button class="copy-button">copy</button></pre>
<h4><code>process.report.filename</code><span><a class="mark" href="#all_process_processreportfilename" id="all_process_processreportfilename">#</a></span><a aria-hidden="true" class="legacy" id="process_process_report_filename"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.12.0, v12.17.0</td>
<td><p>This API is no longer 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>
<p>If the value of <code>process.report.filename</code> is set to <code>'stdout'</code> or <code>'stderr'</code>,
the report is written to the stdout or stderr of the process respectively.</p>

<pre class="with-43-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { report } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Report filename is <span class="hljs-subst">${report.filename}</span>`</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { report } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Report filename is <span class="hljs-subst">${report.filename}</span>`</span>);</code><button class="copy-button">copy</button></pre>
<h4><code>process.report.getReport([err])</code><span><a class="mark" href="#all_process_processreportgetreporterr" id="all_process_processreportgetreporterr">#</a></span><a aria-hidden="true" class="legacy" id="process_process_report_getreport_err"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.12.0, v12.17.0</td>
<td><p>This API is no longer 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 class="with-43-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { report } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">import</span> util <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;

<span class="hljs-keyword">const</span> data = report.<span class="hljs-title function_">getReport</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data.<span class="hljs-property">header</span>.<span class="hljs-property">nodejsVersion</span>);

<span class="hljs-comment">// Similar to process.report.writeReport()</span>
<span class="hljs-keyword">import</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
fs.<span class="hljs-title function_">writeFileSync</span>(<span class="hljs-string">'my-report.log'</span>, util.<span class="hljs-title function_">inspect</span>(data), <span class="hljs-string">'utf8'</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { report } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

<span class="hljs-keyword">const</span> data = report.<span class="hljs-title function_">getReport</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data.<span class="hljs-property">header</span>.<span class="hljs-property">nodejsVersion</span>);

<span class="hljs-comment">// Similar to process.report.writeReport()</span>
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
fs.<span class="hljs-title function_">writeFileSync</span>(<span class="hljs-string">'my-report.log'</span>, util.<span class="hljs-title function_">inspect</span>(data), <span class="hljs-string">'utf8'</span>);</code><button class="copy-button">copy</button></pre>
<p>Additional documentation is available in the <a href="report.html">report documentation</a>.</p>
<h4><code>process.report.reportOnFatalError</code><span><a class="mark" href="#all_process_processreportreportonfatalerror" id="all_process_processreportreportonfatalerror">#</a></span><a aria-hidden="true" class="legacy" id="process_process_report_reportonfatalerror"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0, v14.17.0</td>
<td><p>This API is no longer 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 fatal errors, such as out of
memory errors or failed C++ assertions.</p>

<pre class="with-43-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { report } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Report on fatal error: <span class="hljs-subst">${report.reportOnFatalError}</span>`</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { report } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Report on fatal error: <span class="hljs-subst">${report.reportOnFatalError}</span>`</span>);</code><button class="copy-button">copy</button></pre>
<h4><code>process.report.reportOnSignal</code><span><a class="mark" href="#all_process_processreportreportonsignal" id="all_process_processreportreportonsignal">#</a></span><a aria-hidden="true" class="legacy" id="process_process_report_reportonsignal"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.12.0, v12.17.0</td>
<td><p>This API is no longer 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 class="with-43-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { report } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Report on signal: <span class="hljs-subst">${report.reportOnSignal}</span>`</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { report } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Report on signal: <span class="hljs-subst">${report.reportOnSignal}</span>`</span>);</code><button class="copy-button">copy</button></pre>
<h4><code>process.report.reportOnUncaughtException</code><span><a class="mark" href="#all_process_processreportreportonuncaughtexception" id="all_process_processreportreportonuncaughtexception">#</a></span><a aria-hidden="true" class="legacy" id="process_process_report_reportonuncaughtexception"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.12.0, v12.17.0</td>
<td><p>This API is no longer 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 class="with-43-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { report } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Report on exception: <span class="hljs-subst">${report.reportOnUncaughtException}</span>`</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { report } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Report on exception: <span class="hljs-subst">${report.reportOnUncaughtException}</span>`</span>);</code><button class="copy-button">copy</button></pre>
<h4><code>process.report.signal</code><span><a class="mark" href="#all_process_processreportsignal" id="all_process_processreportsignal">#</a></span><a aria-hidden="true" class="legacy" id="process_process_report_signal"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.12.0, v12.17.0</td>
<td><p>This API is no longer 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 class="with-43-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { report } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Report signal: <span class="hljs-subst">${report.signal}</span>`</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { report } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Report signal: <span class="hljs-subst">${report.signal}</span>`</span>);</code><button class="copy-button">copy</button></pre>
<h4><code>process.report.writeReport([filename][, err])</code><span><a class="mark" href="#all_process_processreportwritereportfilename-err" id="all_process_processreportwritereportfilename-err">#</a></span><a aria-hidden="true" class="legacy" id="process_process_report_writereport_filename_err"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.12.0, v12.17.0</td>
<td><p>This API is no longer 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>
<p>If the value of <code>filename</code> is set to <code>'stdout'</code> or <code>'stderr'</code>, the report is
written to the stdout or stderr of the process respectively.</p>

<pre class="with-43-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { report } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

report.<span class="hljs-title function_">writeReport</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { report } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

report.<span class="hljs-title function_">writeReport</span>();</code><button class="copy-button">copy</button></pre>
<p>Additional documentation is available in the <a href="report.html">report documentation</a>.</p>
</section><section><h3><code>process.resourceUsage()</code><span><a class="mark" href="#all_process_processresourceusage" id="all_process_processresourceusage">#</a></span><a aria-hidden="true" class="legacy" id="process_process_resourceusage"></a></h3>
<div class="api_metadata">
<span>Added in: v12.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> the resource usage for the current process. All of these
values come from the <code>uv_getrusage</code> call which returns
a <a href="https://docs.libuv.org/en/v1.x/misc.html#c.uv_rusage_t"><code>uv_rusage_t</code> struct</a>.
<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="#all_process_processcpuusagepreviousvalue"><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="#all_process_processcpuusagepreviousvalue"><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 class="with-50-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { resourceUsage } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">resourceUsage</span>());
<span class="hljs-comment">/*
  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
  }
*/</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { resourceUsage } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">resourceUsage</span>());
<span class="hljs-comment">/*
  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
  }
*/</span></code><button class="copy-button">copy</button></pre>
</section><section><h3><code>process.send(message[, sendHandle[, options]][, callback])</code><span><a class="mark" href="#all_process_processsendmessage-sendhandle-options-callback" id="all_process_processsendmessage-sendhandle-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="process_process_send_message_sendhandle_options_callback"></a></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></li>
<li><code>sendHandle</code> <a href="#all_net_class-netserver" class="type">&#x3C;net.Server></a> | <a href="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a></li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> used to parameterize the sending of certain types of
handles.<code>options</code> supports the following properties:
<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="#all_child_process_event-message"><code>'message'</code></a> event on the parent's <a href="#all_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>
</section><section><h3><code>process.setegid(id)</code><span><a class="mark" href="#all_process_processsetegidid" id="all_process_processsetegidid">#</a></span><a aria-hidden="true" class="legacy" id="process_process_setegid_id"></a></h3>
<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 class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-keyword">if</span> (process.<span class="hljs-property">getegid</span> &#x26;&#x26; process.<span class="hljs-property">setegid</span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Current gid: <span class="hljs-subst">${process.getegid()}</span>`</span>);
  <span class="hljs-keyword">try</span> {
    process.<span class="hljs-title function_">setegid</span>(<span class="hljs-number">501</span>);
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`New gid: <span class="hljs-subst">${process.getegid()}</span>`</span>);
  } <span class="hljs-keyword">catch</span> (err) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`Failed to set gid: <span class="hljs-subst">${err}</span>`</span>);
  }
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-keyword">if</span> (process.<span class="hljs-property">getegid</span> &#x26;&#x26; process.<span class="hljs-property">setegid</span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Current gid: <span class="hljs-subst">${process.getegid()}</span>`</span>);
  <span class="hljs-keyword">try</span> {
    process.<span class="hljs-title function_">setegid</span>(<span class="hljs-number">501</span>);
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`New gid: <span class="hljs-subst">${process.getegid()}</span>`</span>);
  } <span class="hljs-keyword">catch</span> (err) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`Failed to set gid: <span class="hljs-subst">${err}</span>`</span>);
  }
}</code><button class="copy-button">copy</button></pre>
<p>This function is only available on POSIX platforms (i.e. not Windows or
Android).
This feature is not available in <a href="#all_worker_threads_class-worker"><code>Worker</code></a> threads.</p>
</section><section><h3><code>process.seteuid(id)</code><span><a class="mark" href="#all_process_processseteuidid" id="all_process_processseteuidid">#</a></span><a aria-hidden="true" class="legacy" id="process_process_seteuid_id"></a></h3>
<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 class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-keyword">if</span> (process.<span class="hljs-property">geteuid</span> &#x26;&#x26; process.<span class="hljs-property">seteuid</span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Current uid: <span class="hljs-subst">${process.geteuid()}</span>`</span>);
  <span class="hljs-keyword">try</span> {
    process.<span class="hljs-title function_">seteuid</span>(<span class="hljs-number">501</span>);
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`New uid: <span class="hljs-subst">${process.geteuid()}</span>`</span>);
  } <span class="hljs-keyword">catch</span> (err) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`Failed to set uid: <span class="hljs-subst">${err}</span>`</span>);
  }
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-keyword">if</span> (process.<span class="hljs-property">geteuid</span> &#x26;&#x26; process.<span class="hljs-property">seteuid</span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Current uid: <span class="hljs-subst">${process.geteuid()}</span>`</span>);
  <span class="hljs-keyword">try</span> {
    process.<span class="hljs-title function_">seteuid</span>(<span class="hljs-number">501</span>);
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`New uid: <span class="hljs-subst">${process.geteuid()}</span>`</span>);
  } <span class="hljs-keyword">catch</span> (err) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`Failed to set uid: <span class="hljs-subst">${err}</span>`</span>);
  }
}</code><button class="copy-button">copy</button></pre>
<p>This function is only available on POSIX platforms (i.e. not Windows or
Android).
This feature is not available in <a href="#all_worker_threads_class-worker"><code>Worker</code></a> threads.</p>
</section><section><h3><code>process.setgid(id)</code><span><a class="mark" href="#all_process_processsetgidid" id="all_process_processsetgidid">#</a></span><a aria-hidden="true" class="legacy" id="process_process_setgid_id"></a></h3>
<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 class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-keyword">if</span> (process.<span class="hljs-property">getgid</span> &#x26;&#x26; process.<span class="hljs-property">setgid</span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Current gid: <span class="hljs-subst">${process.getgid()}</span>`</span>);
  <span class="hljs-keyword">try</span> {
    process.<span class="hljs-title function_">setgid</span>(<span class="hljs-number">501</span>);
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`New gid: <span class="hljs-subst">${process.getgid()}</span>`</span>);
  } <span class="hljs-keyword">catch</span> (err) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`Failed to set gid: <span class="hljs-subst">${err}</span>`</span>);
  }
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-keyword">if</span> (process.<span class="hljs-property">getgid</span> &#x26;&#x26; process.<span class="hljs-property">setgid</span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Current gid: <span class="hljs-subst">${process.getgid()}</span>`</span>);
  <span class="hljs-keyword">try</span> {
    process.<span class="hljs-title function_">setgid</span>(<span class="hljs-number">501</span>);
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`New gid: <span class="hljs-subst">${process.getgid()}</span>`</span>);
  } <span class="hljs-keyword">catch</span> (err) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`Failed to set gid: <span class="hljs-subst">${err}</span>`</span>);
  }
}</code><button class="copy-button">copy</button></pre>
<p>This function is only available on POSIX platforms (i.e. not Windows or
Android).
This feature is not available in <a href="#all_worker_threads_class-worker"><code>Worker</code></a> threads.</p>
</section><section><h3><code>process.setgroups(groups)</code><span><a class="mark" href="#all_process_processsetgroupsgroups" id="all_process_processsetgroupsgroups">#</a></span><a aria-hidden="true" class="legacy" id="process_process_setgroups_groups"></a></h3>
<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>

<pre class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-keyword">if</span> (process.<span class="hljs-property">getgroups</span> &#x26;&#x26; process.<span class="hljs-property">setgroups</span>) {
  <span class="hljs-keyword">try</span> {
    process.<span class="hljs-title function_">setgroups</span>([<span class="hljs-number">501</span>]);
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(process.<span class="hljs-title function_">getgroups</span>()); <span class="hljs-comment">// new groups</span>
  } <span class="hljs-keyword">catch</span> (err) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`Failed to set groups: <span class="hljs-subst">${err}</span>`</span>);
  }
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-keyword">if</span> (process.<span class="hljs-property">getgroups</span> &#x26;&#x26; process.<span class="hljs-property">setgroups</span>) {
  <span class="hljs-keyword">try</span> {
    process.<span class="hljs-title function_">setgroups</span>([<span class="hljs-number">501</span>]);
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(process.<span class="hljs-title function_">getgroups</span>()); <span class="hljs-comment">// new groups</span>
  } <span class="hljs-keyword">catch</span> (err) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`Failed to set groups: <span class="hljs-subst">${err}</span>`</span>);
  }
}</code><button class="copy-button">copy</button></pre>
<p>This function is only available on POSIX platforms (i.e. not Windows or
Android).
This feature is not available in <a href="#all_worker_threads_class-worker"><code>Worker</code></a> threads.</p>
</section><section><h3><code>process.setuid(id)</code><span><a class="mark" href="#all_process_processsetuidid" id="all_process_processsetuidid">#</a></span><a aria-hidden="true" class="legacy" id="process_process_setuid_id"></a></h3>
<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 class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-keyword">if</span> (process.<span class="hljs-property">getuid</span> &#x26;&#x26; process.<span class="hljs-property">setuid</span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Current uid: <span class="hljs-subst">${process.getuid()}</span>`</span>);
  <span class="hljs-keyword">try</span> {
    process.<span class="hljs-title function_">setuid</span>(<span class="hljs-number">501</span>);
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`New uid: <span class="hljs-subst">${process.getuid()}</span>`</span>);
  } <span class="hljs-keyword">catch</span> (err) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`Failed to set uid: <span class="hljs-subst">${err}</span>`</span>);
  }
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> process = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-keyword">if</span> (process.<span class="hljs-property">getuid</span> &#x26;&#x26; process.<span class="hljs-property">setuid</span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Current uid: <span class="hljs-subst">${process.getuid()}</span>`</span>);
  <span class="hljs-keyword">try</span> {
    process.<span class="hljs-title function_">setuid</span>(<span class="hljs-number">501</span>);
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`New uid: <span class="hljs-subst">${process.getuid()}</span>`</span>);
  } <span class="hljs-keyword">catch</span> (err) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`Failed to set uid: <span class="hljs-subst">${err}</span>`</span>);
  }
}</code><button class="copy-button">copy</button></pre>
<p>This function is only available on POSIX platforms (i.e. not Windows or
Android).
This feature is not available in <a href="#all_worker_threads_class-worker"><code>Worker</code></a> threads.</p>
</section><section><h3><code>process.setSourceMapsEnabled(val)</code><span><a class="mark" href="#all_process_processsetsourcemapsenabledval" id="all_process_processsetsourcemapsenabledval">#</a></span><a aria-hidden="true" class="legacy" id="process_process_setsourcemapsenabled_val"></a></h3>
<div class="api_metadata">
<span>Added in: v16.6.0, v14.18.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>val</code> <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 enables or disables the <a href="https://sourcemaps.info/spec.html">Source Map v3</a> support for
stack traces.</p>
<p>It provides same features as launching Node.js process with commandline options
<code>--enable-source-maps</code>.</p>
<p>Only source maps in JavaScript files that are loaded after source maps has been
enabled will be parsed and loaded.</p>
</section><section><h3><code>process.setUncaughtExceptionCaptureCallback(fn)</code><span><a class="mark" href="#all_process_processsetuncaughtexceptioncapturecallbackfn" id="all_process_processsetuncaughtexceptioncapturecallbackfn">#</a></span><a aria-hidden="true" class="legacy" id="process_process_setuncaughtexceptioncapturecallback_fn"></a></h3>
<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="#all_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="#all_v8_v8setflagsfromstringflags"><code>v8.setFlagsFromString()</code></a>, the process will
not abort. Actions configured to take place on exceptions such as report
generations will be affected too</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>
</section><section><h3><code>process.sourceMapsEnabled</code><span><a class="mark" href="#all_process_processsourcemapsenabled" id="all_process_processsourcemapsenabled">#</a></span><a aria-hidden="true" class="legacy" id="process_process_sourcemapsenabled"></a></h3>
<div class="api_metadata">
<span>Added in: v20.7.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_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>The <code>process.sourceMapsEnabled</code> property returns whether the
<a href="https://sourcemaps.info/spec.html">Source Map v3</a> support for stack traces is enabled.</p>
</section><section><h3><code>process.stderr</code><span><a class="mark" href="#all_process_processstderr" id="all_process_processstderr">#</a></span><a aria-hidden="true" class="legacy" id="process_process_stderr"></a></h3>
<ul>
<li><a href="#all_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="#all_net_class-netsocket"><code>net.Socket</code></a> (which is a <a href="#all_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="#all_stream_writable-streams">Writable</a> stream.</p>
<p><code>process.stderr</code> differs from other Node.js streams in important ways. See
<a href="#all_process_a-note-on-process-io">note on process I/O</a> for more information.</p>
<h4><code>process.stderr.fd</code><span><a class="mark" href="#all_process_processstderrfd" id="all_process_processstderrfd">#</a></span><a aria-hidden="true" class="legacy" id="process_process_stderr_fd"></a></h4>
<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="#all_worker_threads_class-worker"><code>Worker</code></a> threads,
this field does not exist.</p>
</section><section><h3><code>process.stdin</code><span><a class="mark" href="#all_process_processstdin" id="all_process_processstdin">#</a></span><a aria-hidden="true" class="legacy" id="process_process_stdin"></a></h3>
<ul>
<li><a href="#all_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="#all_net_class-netsocket"><code>net.Socket</code></a> (which is a <a href="#all_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="#all_stream_readable-streams">Readable</a> stream.</p>
<p>For details of how to read from <code>stdin</code> see <a href="#all_stream_readablereadsize"><code>readable.read()</code></a>.</p>
<p>As a <a href="#all_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="#all_stream_compatibility-with-older-nodejs-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>
<h4><code>process.stdin.fd</code><span><a class="mark" href="#all_process_processstdinfd" id="all_process_processstdinfd">#</a></span><a aria-hidden="true" class="legacy" id="process_process_stdin_fd"></a></h4>
<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="#all_worker_threads_class-worker"><code>Worker</code></a> threads,
this field does not exist.</p>
</section><section><h3><code>process.stdout</code><span><a class="mark" href="#all_process_processstdout" id="all_process_processstdout">#</a></span><a aria-hidden="true" class="legacy" id="process_process_stdout"></a></h3>
<ul>
<li><a href="#all_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="#all_net_class-netsocket"><code>net.Socket</code></a> (which is a <a href="#all_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="#all_stream_writable-streams">Writable</a> stream.</p>
<p>For example, to copy <code>process.stdin</code> to <code>process.stdout</code>:</p>

<pre class="with-50-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { stdin, stdout } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

stdin.<span class="hljs-title function_">pipe</span>(stdout);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { stdin, stdout } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

stdin.<span class="hljs-title function_">pipe</span>(stdout);</code><button class="copy-button">copy</button></pre>
<p><code>process.stdout</code> differs from other Node.js streams in important ways. See
<a href="#all_process_a-note-on-process-io">note on process I/O</a> for more information.</p>
<h4><code>process.stdout.fd</code><span><a class="mark" href="#all_process_processstdoutfd" id="all_process_processstdoutfd">#</a></span><a aria-hidden="true" class="legacy" id="process_process_stdout_fd"></a></h4>
<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="#all_worker_threads_class-worker"><code>Worker</code></a> threads,
this field does not exist.</p>
<h4>A note on process I/O<span><a class="mark" href="#all_process_a-note-on-process-io" id="all_process_a-note-on-process-io">#</a></span><a aria-hidden="true" class="legacy" id="process_a_note_on_process_i_o"></a></h4>
<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="#all_console_consolelogdata-args"><code>console.log()</code></a> and <a href="#all_console_consoleerrordata-args"><code>console.error()</code></a>,
respectively.</li>
<li>Writes may be synchronous depending on what the stream is connected to
and whether the system is Windows or POSIX:
<ul>
<li>Files: <em>synchronous</em> on Windows and POSIX</li>
<li>TTYs (Terminals): <em>asynchronous</em> on Windows, <em>synchronous</em> on POSIX</li>
<li>Pipes (and sockets): <em>synchronous</em> on Windows, <em>asynchronous</em> on POSIX</li>
</ul>
</li>
</ol>
<p>These behaviors are partly for historical reasons, as changing them would
create backward 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="#all_process_processexitcode"><code>process.exit()</code></a> for more information.</p>
<p><em><strong>Warning</strong></em>: 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, it's 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="#all_tty_tty">TTY</a> context, check the <code>isTTY</code>
property.</p>
<p>For instance:</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node -p <span class="hljs-string">"Boolean(process.stdin.isTTY)"</span></span>
true
<span class="hljs-meta prompt_">$ </span><span class="language-bash"><span class="hljs-built_in">echo</span> <span class="hljs-string">"foo"</span> | node -p <span class="hljs-string">"Boolean(process.stdin.isTTY)"</span></span>
false
<span class="hljs-meta prompt_">$ </span><span class="language-bash">node -p <span class="hljs-string">"Boolean(process.stdout.isTTY)"</span></span>
true
<span class="hljs-meta prompt_">$ </span><span class="language-bash">node -p <span class="hljs-string">"Boolean(process.stdout.isTTY)"</span> | <span class="hljs-built_in">cat</span></span>
false</code> <button class="copy-button">copy</button></pre>
<p>See the <a href="#all_tty_tty">TTY</a> documentation for more information.</p>
</section><section><h3><code>process.throwDeprecation</code><span><a class="mark" href="#all_process_processthrowdeprecation" id="all_process_processthrowdeprecation">#</a></span><a aria-hidden="true" class="legacy" id="process_process_throwdeprecation"></a></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#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="#all_process_event-warning"><code>'warning'</code> event</a> and the
<a href="#all_process_processemitwarningwarning-type-code-ctor"><code>emitWarning()</code> method</a> for more information.</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node --throw-deprecation -p <span class="hljs-string">"process.throwDeprecation"</span></span>
true
<span class="hljs-meta prompt_">$ </span><span class="language-bash">node -p <span class="hljs-string">"process.throwDeprecation"</span></span>
undefined
<span class="hljs-meta prompt_">$ </span><span class="language-bash">node</span>
<span class="hljs-meta prompt_">> </span><span class="language-bash">process.emitWarning(<span class="hljs-string">'test'</span>, <span class="hljs-string">'DeprecationWarning'</span>);</span>
undefined
<span class="hljs-meta prompt_">> </span><span class="language-bash">(node:26598) DeprecationWarning: <span class="hljs-built_in">test</span></span>
<span class="hljs-meta prompt_">> </span><span class="language-bash">process.throwDeprecation = <span class="hljs-literal">true</span>;</span>
true
<span class="hljs-meta prompt_">> </span><span class="language-bash">process.emitWarning(<span class="hljs-string">'test'</span>, <span class="hljs-string">'DeprecationWarning'</span>);</span>
Thrown:
[DeprecationWarning: test] { name: 'DeprecationWarning' }</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>process.title</code><span><a class="mark" href="#all_process_processtitle" id="all_process_processtitle">#</a></span><a aria-hidden="true" class="legacy" id="process_process_title"></a></h3>
<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>
<p>Assigning a value to <code>process.title</code> might not result in an accurate label
within process manager applications such as macOS Activity Monitor or Windows
Services Manager.</p>
</section><section><h3><code>process.traceDeprecation</code><span><a class="mark" href="#all_process_processtracedeprecation" id="all_process_processtracedeprecation">#</a></span><a aria-hidden="true" class="legacy" id="process_process_tracedeprecation"></a></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#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="#all_process_event-warning"><code>'warning'</code> event</a> and the
<a href="#all_process_processemitwarningwarning-type-code-ctor"><code>emitWarning()</code> method</a> for more information about this
flag's behavior.</p>
</section><section><h3><code>process.umask()</code><span><a class="mark" href="#all_process_processumask" id="all_process_processumask">#</a></span><a aria-hidden="true" class="legacy" id="process_process_umask"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.0.0, v12.19.0</td>
<td><p>Calling <code>process.umask()</code> with no arguments is deprecated.</p></td></tr>
<tr><td>v0.1.19</td>
<td><p><span>Added in: v0.1.19</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated. Calling <code>process.umask()</code> with no argument causes
the process-wide umask to be written twice. This introduces a race condition
between threads, and is a potential security vulnerability. There is no safe,
cross-platform alternative API.</div><p></p>
<p><code>process.umask()</code> returns the Node.js process's file mode creation mask. Child
processes inherit the mask from the parent process.</p>
</section><section><h3><code>process.umask(mask)</code><span><a class="mark" href="#all_process_processumaskmask" id="all_process_processumaskmask">#</a></span><a aria-hidden="true" class="legacy" id="process_process_umask_mask"></a></h3>
<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><code>process.umask(mask)</code> sets the Node.js process's file mode creation mask. Child
processes inherit the mask from the parent process. Returns the previous mask.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { umask } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-keyword">const</span> newmask = <span class="hljs-number">0o022</span>;
<span class="hljs-keyword">const</span> oldmask = <span class="hljs-title function_">umask</span>(newmask);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(
  <span class="hljs-string">`Changed umask from <span class="hljs-subst">${oldmask.toString(<span class="hljs-number">8</span>)}</span> to <span class="hljs-subst">${newmask.toString(<span class="hljs-number">8</span>)}</span>`</span>,
);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { umask } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-keyword">const</span> newmask = <span class="hljs-number">0o022</span>;
<span class="hljs-keyword">const</span> oldmask = <span class="hljs-title function_">umask</span>(newmask);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(
  <span class="hljs-string">`Changed umask from <span class="hljs-subst">${oldmask.toString(<span class="hljs-number">8</span>)}</span> to <span class="hljs-subst">${newmask.toString(<span class="hljs-number">8</span>)}</span>`</span>,
);</code><button class="copy-button">copy</button></pre>
<p>In <a href="#all_worker_threads_class-worker"><code>Worker</code></a> threads, <code>process.umask(mask)</code> will throw an exception.</p>
</section><section><h3><code>process.uptime()</code><span><a class="mark" href="#all_process_processuptime" id="all_process_processuptime">#</a></span><a aria-hidden="true" class="legacy" id="process_process_uptime"></a></h3>
<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>
</section><section><h3><code>process.version</code><span><a class="mark" href="#all_process_processversion" id="all_process_processversion">#</a></span><a aria-hidden="true" class="legacy" id="process_process_version"></a></h3>
<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 contains the Node.js version string.</p>

<pre class="with-44-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { version } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Version: <span class="hljs-subst">${version}</span>`</span>);
<span class="hljs-comment">// Version: v14.8.0</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { version } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Version: <span class="hljs-subst">${version}</span>`</span>);
<span class="hljs-comment">// Version: v14.8.0</span></code><button class="copy-button">copy</button></pre>
<p>To get the version string without the prepended <em>v</em>, use
<code>process.versions.node</code>.</p>
</section><section><h3><code>process.versions</code><span><a class="mark" href="#all_process_processversions" id="all_process_processversions">#</a></span><a aria-hidden="true" class="legacy" id="process_process_versions"></a></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>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 class="with-45-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { versions } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(versions);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { versions } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(versions);</code><button class="copy-button">copy</button></pre>
<p>Will generate an object similar to:</p>
<pre><code class="language-console">{ node: '23.0.0',
  acorn: '8.11.3',
  ada: '2.7.8',
  ares: '1.28.1',
  base64: '0.5.2',
  brotli: '1.1.0',
  cjs_module_lexer: '1.2.2',
  cldr: '45.0',
  icu: '75.1',
  llhttp: '9.2.1',
  modules: '127',
  napi: '9',
  nghttp2: '1.61.0',
  nghttp3: '0.7.0',
  ngtcp2: '1.3.0',
  openssl: '3.0.13+quic',
  simdjson: '3.8.0',
  simdutf: '5.2.4',
  tz: '2024a',
  undici: '6.13.0',
  unicode: '15.1',
  uv: '1.48.0',
  uvwasi: '0.0.20',
  v8: '12.4.254.14-node.11',
  zlib: '1.3.0.1-motley-7d77fb7' }</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Exit codes<span><a class="mark" href="#all_process_exit-codes" id="all_process_exit-codes">#</a></span><a aria-hidden="true" class="legacy" id="process_exit_codes"></a></h3>
<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="#all_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="#all_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>13</code> <strong>Unfinished Top-Level Await</strong>: <code>await</code> was used outside of a function
in the top-level code, but the passed <code>Promise</code> never resolved.</li>
<li><code>14</code> <strong>Snapshot Failure</strong>: Node.js was started to build a V8 startup
snapshot and it failed because certain requirements of the state of
the application were not met.</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></section>
        </section>
<section><h2>Punycode<span><a class="mark" href="#all_punycode_punycode" id="all_punycode_punycode">#</a></span><a aria-hidden="true" class="legacy" id="punycode_punycode"></a></h2>
<div class="api_metadata">
<span>Deprecated since: v7.0.0</span>
</div>

<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/punycode.js">lib/punycode.js</a></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. For punycode-based URL
encoding, see <a href="#all_url_urldomaintoasciidomain"><code>url.domainToASCII</code></a> or, more generally, the
<a href="#all_url_the-whatwg-url-api">WHATWG URL API</a>.</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"><span class="hljs-keyword">const</span> punycode = <span class="hljs-built_in">require</span>(<span class="hljs-string">'punycode'</span>);</code> <button class="copy-button">copy</button></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>
<section><h3><code>punycode.decode(string)</code><span><a class="mark" href="#all_punycode_punycodedecodestring" id="all_punycode_punycodedecodestring">#</a></span><a aria-hidden="true" class="legacy" id="punycode_punycode_decode_string"></a></h3>
<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.<span class="hljs-title function_">decode</span>(<span class="hljs-string">'maana-pta'</span>); <span class="hljs-comment">// 'mañana'</span>
punycode.<span class="hljs-title function_">decode</span>(<span class="hljs-string">'--dqo34k'</span>); <span class="hljs-comment">// '☃-⌘'</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>punycode.encode(string)</code><span><a class="mark" href="#all_punycode_punycodeencodestring" id="all_punycode_punycodeencodestring">#</a></span><a aria-hidden="true" class="legacy" id="punycode_punycode_encode_string"></a></h3>
<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.<span class="hljs-title function_">encode</span>(<span class="hljs-string">'mañana'</span>); <span class="hljs-comment">// 'maana-pta'</span>
punycode.<span class="hljs-title function_">encode</span>(<span class="hljs-string">'☃-⌘'</span>); <span class="hljs-comment">// '--dqo34k'</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>punycode.toASCII(domain)</code><span><a class="mark" href="#all_punycode_punycodetoasciidomain" id="all_punycode_punycodetoasciidomain">#</a></span><a aria-hidden="true" class="legacy" id="punycode_punycode_toascii_domain"></a></h3>
<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"><span class="hljs-comment">// encode domain names</span>
punycode.<span class="hljs-title function_">toASCII</span>(<span class="hljs-string">'mañana.com'</span>);  <span class="hljs-comment">// 'xn--maana-pta.com'</span>
punycode.<span class="hljs-title function_">toASCII</span>(<span class="hljs-string">'☃-⌘.com'</span>);   <span class="hljs-comment">// 'xn----dqo34k.com'</span>
punycode.<span class="hljs-title function_">toASCII</span>(<span class="hljs-string">'example.com'</span>); <span class="hljs-comment">// 'example.com'</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>punycode.toUnicode(domain)</code><span><a class="mark" href="#all_punycode_punycodetounicodedomain" id="all_punycode_punycodetounicodedomain">#</a></span><a aria-hidden="true" class="legacy" id="punycode_punycode_tounicode_domain"></a></h3>
<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"><span class="hljs-comment">// decode domain names</span>
punycode.<span class="hljs-title function_">toUnicode</span>(<span class="hljs-string">'xn--maana-pta.com'</span>); <span class="hljs-comment">// 'mañana.com'</span>
punycode.<span class="hljs-title function_">toUnicode</span>(<span class="hljs-string">'xn----dqo34k.com'</span>);  <span class="hljs-comment">// '☃-⌘.com'</span>
punycode.<span class="hljs-title function_">toUnicode</span>(<span class="hljs-string">'example.com'</span>);       <span class="hljs-comment">// 'example.com'</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>punycode.ucs2</code><span><a class="mark" href="#all_punycode_punycodeucs2" id="all_punycode_punycodeucs2">#</a></span><a aria-hidden="true" class="legacy" id="punycode_punycode_ucs2"></a></h3>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div>
<h4><code>punycode.ucs2.decode(string)</code><span><a class="mark" href="#all_punycode_punycodeucs2decodestring" id="all_punycode_punycodeucs2decodestring">#</a></span><a aria-hidden="true" class="legacy" id="punycode_punycode_ucs2_decode_string"></a></h4>
<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.<span class="hljs-property">ucs2</span>.<span class="hljs-title function_">decode</span>(<span class="hljs-string">'abc'</span>); <span class="hljs-comment">// [0x61, 0x62, 0x63]</span>
<span class="hljs-comment">// surrogate pair for U+1D306 tetragram for centre:</span>
punycode.<span class="hljs-property">ucs2</span>.<span class="hljs-title function_">decode</span>(<span class="hljs-string">'\uD834\uDF06'</span>); <span class="hljs-comment">// [0x1D306]</span></code> <button class="copy-button">copy</button></pre>
<h4><code>punycode.ucs2.encode(codePoints)</code><span><a class="mark" href="#all_punycode_punycodeucs2encodecodepoints" id="all_punycode_punycodeucs2encodecodepoints">#</a></span><a aria-hidden="true" class="legacy" id="punycode_punycode_ucs2_encode_codepoints"></a></h4>
<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.<span class="hljs-property">ucs2</span>.<span class="hljs-title function_">encode</span>([<span class="hljs-number">0x61</span>, <span class="hljs-number">0x62</span>, <span class="hljs-number">0x63</span>]); <span class="hljs-comment">// 'abc'</span>
punycode.<span class="hljs-property">ucs2</span>.<span class="hljs-title function_">encode</span>([<span class="hljs-number">0x1D306</span>]); <span class="hljs-comment">// '\uD834\uDF06'</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>punycode.version</code><span><a class="mark" href="#all_punycode_punycodeversion" id="all_punycode_punycodeversion">#</a></span><a aria-hidden="true" class="legacy" id="punycode_punycode_version"></a></h3>
<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></section>
        </section>
<section><h2>Query string<span><a class="mark" href="#all_querystring_query-string" id="all_querystring_query-string">#</a></span><a aria-hidden="true" class="legacy" id="querystring_query_string"></a></h2>

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

<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/querystring.js">lib/querystring.js</a></p>
<p>The <code>node:querystring</code> module provides utilities for parsing and formatting URL
query strings. It can be accessed using:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> querystring = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:querystring'</span>);</code> <button class="copy-button">copy</button></pre>
<p><code>querystring</code> is more performant than <a href="#all_url_class-urlsearchparams" class="type">&#x3C;URLSearchParams></a> but is not a
standardized API. Use <a href="#all_url_class-urlsearchparams" class="type">&#x3C;URLSearchParams></a> when performance is not critical or
when compatibility with browser code is desirable.</p>
<section><h3><code>querystring.decode()</code><span><a class="mark" href="#all_querystring_querystringdecode" id="all_querystring_querystringdecode">#</a></span><a aria-hidden="true" class="legacy" id="querystring_querystring_decode"></a></h3>
<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>
</section><section><h3><code>querystring.encode()</code><span><a class="mark" href="#all_querystring_querystringencode" id="all_querystring_querystringencode">#</a></span><a aria-hidden="true" class="legacy" id="querystring_querystring_encode"></a></h3>
<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>
</section><section><h3><code>querystring.escape(str)</code><span><a class="mark" href="#all_querystring_querystringescapestr" id="all_querystring_querystringescapestr">#</a></span><a aria-hidden="true" class="legacy" id="querystring_querystring_escape_str"></a></h3>
<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>
</section><section><h3><code>querystring.parse(str[, sep[, eq[, options]]])</code><span><a class="mark" href="#all_querystring_querystringparsestr-sep-eq-options" id="all_querystring_querystringparsestr-sep-eq-options">#</a></span><a aria-hidden="true" class="legacy" id="querystring_querystring_parse_str_sep_eq_options"></a></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>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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"foo"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"bar"</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"abc"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span><span class="hljs-string">"xyz"</span><span class="hljs-punctuation">,</span> <span class="hljs-string">"123"</span><span class="hljs-punctuation">]</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></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"><span class="hljs-comment">// Assuming gbkDecodeURIComponent function already exists...</span>

querystring.<span class="hljs-title function_">parse</span>(<span class="hljs-string">'w=%D6%D0%CE%C4&#x26;foo=bar'</span>, <span class="hljs-literal">null</span>, <span class="hljs-literal">null</span>,
                  { <span class="hljs-attr">decodeURIComponent</span>: gbkDecodeURIComponent });</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>querystring.stringify(obj[, sep[, eq[, options]]])</code><span><a class="mark" href="#all_querystring_querystringstringifyobj-sep-eq-options" id="all_querystring_querystringstringifyobj-sep-eq-options">#</a></span><a aria-hidden="true" class="legacy" id="querystring_querystring_stringify_obj_sep_eq_options"></a></h3>
<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><code>options</code>
<ul>
<li><code>encodeURIComponent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#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/Reference/Global_Objects/BigInt" class="type">&#x3C;bigint></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/Reference/Global_Objects/BigInt" class="type">&#x3C;bigint[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean[]></a>
The numeric values must be finite. Any other input values will be coerced to
empty strings.</p>
<pre><code class="language-js">querystring.<span class="hljs-title function_">stringify</span>({ <span class="hljs-attr">foo</span>: <span class="hljs-string">'bar'</span>, <span class="hljs-attr">baz</span>: [<span class="hljs-string">'qux'</span>, <span class="hljs-string">'quux'</span>], <span class="hljs-attr">corge</span>: <span class="hljs-string">''</span> });
<span class="hljs-comment">// Returns 'foo=bar&#x26;baz=qux&#x26;baz=quux&#x26;corge='</span>

querystring.<span class="hljs-title function_">stringify</span>({ <span class="hljs-attr">foo</span>: <span class="hljs-string">'bar'</span>, <span class="hljs-attr">baz</span>: <span class="hljs-string">'qux'</span> }, <span class="hljs-string">';'</span>, <span class="hljs-string">':'</span>);
<span class="hljs-comment">// Returns 'foo:bar;baz:qux'</span></code> <button class="copy-button">copy</button></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"><span class="hljs-comment">// Assuming gbkEncodeURIComponent function already exists,</span>

querystring.<span class="hljs-title function_">stringify</span>({ <span class="hljs-attr">w</span>: <span class="hljs-string">'中文'</span>, <span class="hljs-attr">foo</span>: <span class="hljs-string">'bar'</span> }, <span class="hljs-literal">null</span>, <span class="hljs-literal">null</span>,
                      { <span class="hljs-attr">encodeURIComponent</span>: gbkEncodeURIComponent });</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>querystring.unescape(str)</code><span><a class="mark" href="#all_querystring_querystringunescapestr" id="all_querystring_querystringunescapestr">#</a></span><a aria-hidden="true" class="legacy" id="querystring_querystring_unescape_str"></a></h3>
<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></section>
        </section>
<section><h2>Readline<span><a class="mark" href="#all_readline_readline" id="all_readline_readline">#</a></span><a aria-hidden="true" class="legacy" id="readline_readline"></a></h2>

<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/readline.js">lib/readline.js</a></p>
<p>The <code>node:readline</code> module provides an interface for reading data from a
<a href="#all_stream_readable-streams">Readable</a> stream (such as <a href="#all_process_processstdin"><code>process.stdin</code></a>) one line at a time.</p>
<p>To use the promise-based APIs:</p>

<pre class="with-51-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> readline <span class="hljs-keyword">from</span> <span class="hljs-string">'node:readline/promises'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> readline = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:readline/promises'</span>);</code><button class="copy-button">copy</button></pre>
<p>To use the callback and sync APIs:</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> readline <span class="hljs-keyword">from</span> <span class="hljs-string">'node:readline'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> readline = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:readline'</span>);</code><button class="copy-button">copy</button></pre>
<p>The following simple example illustrates the basic use of the <code>node:readline</code>
module.</p>

<pre class="with-65-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> readline <span class="hljs-keyword">from</span> <span class="hljs-string">'node:readline/promises'</span>;
<span class="hljs-keyword">import</span> { stdin <span class="hljs-keyword">as</span> input, stdout <span class="hljs-keyword">as</span> output } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-keyword">const</span> rl = readline.<span class="hljs-title function_">createInterface</span>({ input, output });

<span class="hljs-keyword">const</span> answer = <span class="hljs-keyword">await</span> rl.<span class="hljs-title function_">question</span>(<span class="hljs-string">'What do you think of Node.js? '</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Thank you for your valuable feedback: <span class="hljs-subst">${answer}</span>`</span>);

rl.<span class="hljs-title function_">close</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> readline = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:readline'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-attr">stdin</span>: input, <span class="hljs-attr">stdout</span>: output } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-keyword">const</span> rl = readline.<span class="hljs-title function_">createInterface</span>({ input, output });

rl.<span class="hljs-title function_">question</span>(<span class="hljs-string">'What do you think of Node.js? '</span>, <span class="hljs-function">(<span class="hljs-params">answer</span>) =></span> {
  <span class="hljs-comment">// <span class="hljs-doctag">TODO:</span> Log the answer in a database</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Thank you for your valuable feedback: <span class="hljs-subst">${answer}</span>`</span>);

  rl.<span class="hljs-title function_">close</span>();
});</code><button class="copy-button">copy</button></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>
<p><a id="readline_class_interface"></a></p>
<section><h3>Class: <code>InterfaceConstructor</code><span><a class="mark" href="#all_readline_class-interfaceconstructor" id="all_readline_class-interfaceconstructor">#</a></span><a aria-hidden="true" class="legacy" id="readline_class_interfaceconstructor"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.104</span>
</div>
<ul>
<li>Extends: <a href="#all_events_class-eventemitter" class="type">&#x3C;EventEmitter></a></li>
</ul>
<p>Instances of the <code>InterfaceConstructor</code> class are constructed using the
<code>readlinePromises.createInterface()</code> or <code>readline.createInterface()</code> method.
Every instance is associated with a single <code>input</code> <a href="#all_stream_readable-streams">Readable</a> stream and a
single <code>output</code> <a href="#all_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>
<h4>Event: <code>'close'</code><span><a class="mark" href="#all_readline_event-close" id="all_readline_event-close">#</a></span><a aria-hidden="true" class="legacy" id="readline_event_close"></a></h4>
<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>InterfaceConstructor</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 <kbd>Ctrl</kbd>+<kbd>D</kbd> to signal
end-of-transmission (EOT);</li>
<li>The <code>input</code> stream receives <kbd>Ctrl</kbd>+<kbd>C</kbd> to signal <code>SIGINT</code>
and there is no <code>'SIGINT'</code> event listener registered on the
<code>InterfaceConstructor</code> instance.</li>
</ul>
<p>The listener function is called without passing any arguments.</p>
<p>The <code>InterfaceConstructor</code> instance is finished once the <code>'close'</code> event is
emitted.</p>
<h4>Event: <code>'line'</code><span><a class="mark" href="#all_readline_event-line" id="all_readline_event-line">#</a></span><a aria-hidden="true" class="legacy" id="readline_event_line"></a></h4>
<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 <kbd>Enter</kbd> or <kbd>Return</kbd>.</p>
<p>The <code>'line'</code> event is also emitted if new data has been read from a stream and
that stream ends without a final end-of-line marker.</p>
<p>The listener function is called with a string containing the single line of
received input.</p>
<pre><code class="language-js">rl.<span class="hljs-title function_">on</span>(<span class="hljs-string">'line'</span>, <span class="hljs-function">(<span class="hljs-params">input</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Received: <span class="hljs-subst">${input}</span>`</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4>Event: <code>'history'</code><span><a class="mark" href="#all_readline_event-history" id="all_readline_event-history">#</a></span><a aria-hidden="true" class="legacy" id="readline_event_history"></a></h4>
<div class="api_metadata">
<span>Added in: v15.8.0, v14.18.0</span>
</div>
<p>The <code>'history'</code> event is emitted whenever the history array has changed.</p>
<p>The listener function is called with an array containing the history array.
It will reflect all changes, added lines and removed lines due to
<code>historySize</code> and <code>removeHistoryDuplicates</code>.</p>
<p>The primary purpose is to allow a listener to persist the history.
It is also possible for the listener to change the history object. This
could be useful to prevent certain lines to be added to the history, like
a password.</p>
<pre><code class="language-js">rl.<span class="hljs-title function_">on</span>(<span class="hljs-string">'history'</span>, <span class="hljs-function">(<span class="hljs-params">history</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Received: <span class="hljs-subst">${history}</span>`</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4>Event: <code>'pause'</code><span><a class="mark" href="#all_readline_event-pause" id="all_readline_event-pause">#</a></span><a aria-hidden="true" class="legacy" id="readline_event_pause"></a></h4>
<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="#all_readline_event-sigtstp"><code>'SIGTSTP'</code></a> and <a href="#all_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.<span class="hljs-title function_">on</span>(<span class="hljs-string">'pause'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Readline paused.'</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4>Event: <code>'resume'</code><span><a class="mark" href="#all_readline_event-resume" id="all_readline_event-resume">#</a></span><a aria-hidden="true" class="legacy" id="readline_event_resume"></a></h4>
<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.<span class="hljs-title function_">on</span>(<span class="hljs-string">'resume'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Readline resumed.'</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4>Event: <code>'SIGCONT'</code><span><a class="mark" href="#all_readline_event-sigcont" id="all_readline_event-sigcont">#</a></span><a aria-hidden="true" class="legacy" id="readline_event_sigcont"></a></h4>
<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 <kbd>Ctrl</kbd>+<kbd>Z</kbd> (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.<span class="hljs-title function_">on</span>(<span class="hljs-string">'SIGCONT'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-comment">// `prompt` will automatically resume the stream</span>
  rl.<span class="hljs-title function_">prompt</span>();
});</code> <button class="copy-button">copy</button></pre>
<p>The <code>'SIGCONT'</code> event is <em>not</em> supported on Windows.</p>
<h4>Event: <code>'SIGINT'</code><span><a class="mark" href="#all_readline_event-sigint" id="all_readline_event-sigint">#</a></span><a aria-hidden="true" class="legacy" id="readline_event_sigint"></a></h4>
<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 <kbd>Ctrl+C</kbd> 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.<span class="hljs-title function_">on</span>(<span class="hljs-string">'SIGINT'</span>, <span class="hljs-function">() =></span> {
  rl.<span class="hljs-title function_">question</span>(<span class="hljs-string">'Are you sure you want to exit? '</span>, <span class="hljs-function">(<span class="hljs-params">answer</span>) =></span> {
    <span class="hljs-keyword">if</span> (answer.<span class="hljs-title function_">match</span>(<span class="hljs-regexp">/^y(es)?$/i</span>)) rl.<span class="hljs-title function_">pause</span>();
  });
});</code> <button class="copy-button">copy</button></pre>
<h4>Event: <code>'SIGTSTP'</code><span><a class="mark" href="#all_readline_event-sigtstp" id="all_readline_event-sigtstp">#</a></span><a aria-hidden="true" class="legacy" id="readline_event_sigtstp"></a></h4>
<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 <kbd>Ctrl</kbd>+<kbd>Z</kbd> 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.<span class="hljs-title function_">on</span>(<span class="hljs-string">'SIGTSTP'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-comment">// This will override SIGTSTP and prevent the program from going to the</span>
  <span class="hljs-comment">// background.</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Caught SIGTSTP.'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>The <code>'SIGTSTP'</code> event is <em>not</em> supported on Windows.</p>
<h4><code>rl.close()</code><span><a class="mark" href="#all_readline_rlclose" id="all_readline_rlclose">#</a></span><a aria-hidden="true" class="legacy" id="readline_rl_close"></a></h4>
<div class="api_metadata">
<span>Added in: v0.1.98</span>
</div>
<p>The <code>rl.close()</code> method closes the <code>InterfaceConstructor</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>InterfaceConstructor</code> instance.</p>
<h4><code>rl.pause()</code><span><a class="mark" href="#all_readline_rlpause" id="all_readline_rlpause">#</a></span><a aria-hidden="true" class="legacy" id="readline_rl_pause"></a></h4>
<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>InterfaceConstructor</code> instance.</p>
<h4><code>rl.prompt([preserveCursor])</code><span><a class="mark" href="#all_readline_rlpromptpreservecursor" id="all_readline_rlpromptpreservecursor">#</a></span><a aria-hidden="true" class="legacy" id="readline_rl_prompt_preservecursor"></a></h4>
<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>InterfaceConstructor</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>InterfaceConstructor</code> was created with <code>output</code> set to <code>null</code> or
<code>undefined</code> the prompt is not written.</p>
<h4><code>rl.resume()</code><span><a class="mark" href="#all_readline_rlresume" id="all_readline_rlresume">#</a></span><a aria-hidden="true" class="legacy" id="readline_rl_resume"></a></h4>
<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>
<h4><code>rl.setPrompt(prompt)</code><span><a class="mark" href="#all_readline_rlsetpromptprompt" id="all_readline_rlsetpromptprompt">#</a></span><a aria-hidden="true" class="legacy" id="readline_rl_setprompt_prompt"></a></h4>
<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>
<h4><code>rl.getPrompt()</code><span><a class="mark" href="#all_readline_rlgetprompt" id="all_readline_rlgetprompt">#</a></span><a aria-hidden="true" class="legacy" id="readline_rl_getprompt"></a></h4>
<div class="api_metadata">
<span>Added in: v15.3.0, v14.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> the current prompt string</li>
</ul>
<p>The <code>rl.getPrompt()</code> method returns the current prompt used by <code>rl.prompt()</code>.</p>
<h4><code>rl.write(data[, key])</code><span><a class="mark" href="#all_readline_rlwritedata-key" id="all_readline_rlwritedata-key">#</a></span><a aria-hidden="true" class="legacy" id="readline_rl_write_data_key"></a></h4>
<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><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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 <kbd>Ctrl</kbd> 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 <kbd>Meta</kbd> 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 <kbd>Shift</kbd> 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="#all_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>InterfaceConstructor</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.<span class="hljs-title function_">write</span>(<span class="hljs-string">'Delete this!'</span>);
<span class="hljs-comment">// Simulate Ctrl+U to delete the line written previously</span>
rl.<span class="hljs-title function_">write</span>(<span class="hljs-literal">null</span>, { <span class="hljs-attr">ctrl</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'u'</span> });</code> <button class="copy-button">copy</button></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>
<h4><code>rl[Symbol.asyncIterator]()</code><span><a class="mark" href="#all_readline_rlsymbolasynciterator" id="all_readline_rlsymbolasynciterator">#</a></span><a aria-hidden="true" class="legacy" id="readline_rl_symbol_asynciterator"></a></h4>
<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, v10.17.0</td>
<td><p>Symbol.asyncIterator support is no longer experimental.</p></td></tr>
<tr><td>v11.4.0, v10.16.0</td>
<td><p><span>Added in: v11.4.0, v10.16.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>InterfaceConstructor</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="#all_readline_rlclose"><code>rl.close()</code></a> will be called. In other words, iterating over a
<code>InterfaceConstructor</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"><span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">processLineByLine</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">const</span> rl = readline.<span class="hljs-title function_">createInterface</span>({
    <span class="hljs-comment">// ...</span>
  });

  <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> line <span class="hljs-keyword">of</span> rl) {
    <span class="hljs-comment">// Each line in the readline input will be successively available here as</span>
    <span class="hljs-comment">// `line`.</span>
  }
}</code> <button class="copy-button">copy</button></pre>
<p><code>readline.createInterface()</code> will start to consume the input stream once
invoked. Having asynchronous operations between interface creation and
asynchronous iteration may result in missed lines.</p>
<h4><code>rl.line</code><span><a class="mark" href="#all_readline_rlline" id="all_readline_rlline">#</a></span><a aria-hidden="true" class="legacy" id="readline_rl_line"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.8.0, v14.18.0</td>
<td><p>Value will always be a string, never undefined.</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><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 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="#all_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"><span class="hljs-keyword">const</span> values = [<span class="hljs-string">'lorem ipsum'</span>, <span class="hljs-string">'dolor sit amet'</span>];
<span class="hljs-keyword">const</span> rl = readline.<span class="hljs-title function_">createInterface</span>(process.<span class="hljs-property">stdin</span>);
<span class="hljs-keyword">const</span> showResults = <span class="hljs-title function_">debounce</span>(<span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(
    <span class="hljs-string">'\n'</span>,
    values.<span class="hljs-title function_">filter</span>(<span class="hljs-function">(<span class="hljs-params">val</span>) =></span> val.<span class="hljs-title function_">startsWith</span>(rl.<span class="hljs-property">line</span>)).<span class="hljs-title function_">join</span>(<span class="hljs-string">' '</span>),
  );
}, <span class="hljs-number">300</span>);
process.<span class="hljs-property">stdin</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'keypress'</span>, <span class="hljs-function">(<span class="hljs-params">c, k</span>) =></span> {
  <span class="hljs-title function_">showResults</span>();
});</code> <button class="copy-button">copy</button></pre>
<h4><code>rl.cursor</code><span><a class="mark" href="#all_readline_rlcursor" id="all_readline_rlcursor">#</a></span><a aria-hidden="true" class="legacy" id="readline_rl_cursor"></a></h4>
<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>
<h4><code>rl.getCursorPos()</code><span><a class="mark" href="#all_readline_rlgetcursorpos" id="all_readline_rlgetcursorpos">#</a></span><a aria-hidden="true" class="legacy" id="readline_rl_getcursorpos"></a></h4>
<div class="api_metadata">
<span>Added in: v13.5.0, v12.16.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>
<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>
</section><section><h3>Promises API<span><a class="mark" href="#all_readline_promises-api" id="all_readline_promises-api">#</a></span><a aria-hidden="true" class="legacy" id="readline_promises_api"></a></h3>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<h4>Class: <code>readlinePromises.Interface</code><span><a class="mark" href="#all_readline_class-readlinepromisesinterface" id="all_readline_class-readlinepromisesinterface">#</a></span><a aria-hidden="true" class="legacy" id="readline_class_readlinepromises_interface"></a></h4>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<ul>
<li>Extends: <a href="#all_readline_class-interfaceconstructor" class="type">&#x3C;readline.InterfaceConstructor></a></li>
</ul>
<p>Instances of the <code>readlinePromises.Interface</code> class are constructed using the
<code>readlinePromises.createInterface()</code> method. Every instance is associated with a
single <code>input</code> <a href="#all_stream_readable-streams">Readable</a> stream and a single <code>output</code> <a href="#all_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>
<h5><code>rl.question(query[, options])</code><span><a class="mark" href="#all_readline_rlquestionquery-options" id="all_readline_rlquestionquery-options">#</a></span><a aria-hidden="true" class="legacy" id="readline_rl_question_query_options"></a></h5>
<div class="api_metadata">
<span>Added in: v17.0.0</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>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> Optionally allows the <code>question()</code> to be canceled
using an <code>AbortSignal</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> A promise that is fulfilled 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>readlinePromises.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>If the question is called after <code>rl.close()</code>, it returns a rejected promise.</p>
<p>Example usage:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">const</span> answer = <span class="hljs-keyword">await</span> rl.<span class="hljs-title function_">question</span>(<span class="hljs-string">'What is your favorite food? '</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Oh, so your favorite food is <span class="hljs-subst">${answer}</span>`</span>);</code> <button class="copy-button">copy</button></pre>
<p>Using an <code>AbortSignal</code> to cancel a question.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">const</span> signal = <span class="hljs-title class_">AbortSignal</span>.<span class="hljs-title function_">timeout</span>(<span class="hljs-number">10_000</span>);

signal.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">'abort'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'The food question timed out'</span>);
}, { <span class="hljs-attr">once</span>: <span class="hljs-literal">true</span> });

<span class="hljs-keyword">const</span> answer = <span class="hljs-keyword">await</span> rl.<span class="hljs-title function_">question</span>(<span class="hljs-string">'What is your favorite food? '</span>, { signal });
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Oh, so your favorite food is <span class="hljs-subst">${answer}</span>`</span>);</code> <button class="copy-button">copy</button></pre>
<h4>Class: <code>readlinePromises.Readline</code><span><a class="mark" href="#all_readline_class-readlinepromisesreadline" id="all_readline_class-readlinepromisesreadline">#</a></span><a aria-hidden="true" class="legacy" id="readline_class_readlinepromises_readline"></a></h4>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<h5><code>new readlinePromises.Readline(stream[, options])</code><span><a class="mark" href="#all_readline_new-readlinepromisesreadlinestream-options" id="all_readline_new-readlinepromisesreadlinestream-options">#</a></span><a aria-hidden="true" class="legacy" id="readline_new_readlinepromises_readline_stream_options"></a></h5>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<ul>
<li><code>stream</code> <a href="#all_stream_class-streamwritable" class="type">&#x3C;stream.Writable></a> A <a href="tty.html">TTY</a> stream.</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>
<ul>
<li><code>autoCommit</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>, no need to call <code>rl.commit()</code>.</li>
</ul>
</li>
</ul>
<h5><code>rl.clearLine(dir)</code><span><a class="mark" href="#all_readline_rlclearlinedir" id="all_readline_rlclearlinedir">#</a></span><a aria-hidden="true" class="legacy" id="readline_rl_clearline_dir"></a></h5>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<ul>
<li><code>dir</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a>
<ul>
<li><code>-1</code>: to the left from cursor</li>
<li><code>1</code>: to the right from cursor</li>
<li><code>0</code>: the entire line</li>
</ul>
</li>
<li>Returns: this</li>
</ul>
<p>The <code>rl.clearLine()</code> method adds to the internal list of pending action an
action that clears current line of the associated <code>stream</code> in a specified
direction identified by <code>dir</code>.
Call <code>rl.commit()</code> to see the effect of this method, unless <code>autoCommit: true</code>
was passed to the constructor.</p>
<h5><code>rl.clearScreenDown()</code><span><a class="mark" href="#all_readline_rlclearscreendown" id="all_readline_rlclearscreendown">#</a></span><a aria-hidden="true" class="legacy" id="readline_rl_clearscreendown"></a></h5>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<ul>
<li>Returns: this</li>
</ul>
<p>The <code>rl.clearScreenDown()</code> method adds to the internal list of pending action an
action that clears the associated stream from the current position of the
cursor down.
Call <code>rl.commit()</code> to see the effect of this method, unless <code>autoCommit: true</code>
was passed to the constructor.</p>
<h5><code>rl.commit()</code><span><a class="mark" href="#all_readline_rlcommit" id="all_readline_rlcommit">#</a></span><a aria-hidden="true" class="legacy" id="readline_rl_commit"></a></h5>
<div class="api_metadata">
<span>Added in: v17.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>The <code>rl.commit()</code> method sends all the pending actions to the associated
<code>stream</code> and clears the internal list of pending actions.</p>
<h5><code>rl.cursorTo(x[, y])</code><span><a class="mark" href="#all_readline_rlcursortox-y" id="all_readline_rlcursortox-y">#</a></span><a aria-hidden="true" class="legacy" id="readline_rl_cursorto_x_y"></a></h5>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<ul>
<li><code>x</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>y</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li>Returns: this</li>
</ul>
<p>The <code>rl.cursorTo()</code> method adds to the internal list of pending action an action
that moves cursor to the specified position in the associated <code>stream</code>.
Call <code>rl.commit()</code> to see the effect of this method, unless <code>autoCommit: true</code>
was passed to the constructor.</p>
<h5><code>rl.moveCursor(dx, dy)</code><span><a class="mark" href="#all_readline_rlmovecursordx-dy" id="all_readline_rlmovecursordx-dy">#</a></span><a aria-hidden="true" class="legacy" id="readline_rl_movecursor_dx_dy"></a></h5>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<ul>
<li><code>dx</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li><code>dy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a></li>
<li>Returns: this</li>
</ul>
<p>The <code>rl.moveCursor()</code> method adds to the internal list of pending action an
action that moves the cursor <em>relative</em> to its current position in the
associated <code>stream</code>.
Call <code>rl.commit()</code> to see the effect of this method, unless <code>autoCommit: true</code>
was passed to the constructor.</p>
<h5><code>rl.rollback()</code><span><a class="mark" href="#all_readline_rlrollback" id="all_readline_rlrollback">#</a></span><a aria-hidden="true" class="legacy" id="readline_rl_rollback"></a></h5>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<ul>
<li>Returns: this</li>
</ul>
<p>The <code>rl.rollback</code> methods clears the internal list of pending actions without
sending it to the associated <code>stream</code>.</p>
<h4><code>readlinePromises.createInterface(options)</code><span><a class="mark" href="#all_readline_readlinepromisescreateinterfaceoptions" id="all_readline_readlinepromisescreateinterfaceoptions">#</a></span><a aria-hidden="true" class="legacy" id="readline_readlinepromises_createinterface_options"></a></h4>
<div class="api_metadata">
<span>Added in: v17.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>
<ul>
<li><code>input</code> <a href="#all_stream_class-streamreadable" class="type">&#x3C;stream.Readable></a> The <a href="#all_stream_readable-streams">Readable</a> stream to listen to. This option
is <em>required</em>.</li>
<li><code>output</code> <a href="#all_stream_class-streamwritable" class="type">&#x3C;stream.Writable></a> The <a href="#all_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>history</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> Initial list of history lines. 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>[]</code>.</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>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>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="#all_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>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>readlinePromises</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>
<li><code>tabSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> The number of spaces a tab is equal to (minimum 1).
<strong>Default:</strong> <code>8</code>.</li>
</ul>
</li>
<li>Returns: <a href="#all_readline_class-readlinepromisesinterface" class="type">&#x3C;readlinePromises.Interface></a></li>
</ul>
<p>The <code>readlinePromises.createInterface()</code> method creates a new <code>readlinePromises.Interface</code>
instance.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> readlinePromises = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:readline/promises'</span>);
<span class="hljs-keyword">const</span> rl = readlinePromises.<span class="hljs-title function_">createInterface</span>({
  <span class="hljs-attr">input</span>: process.<span class="hljs-property">stdin</span>,
  <span class="hljs-attr">output</span>: process.<span class="hljs-property">stdout</span>,
});</code> <button class="copy-button">copy</button></pre>
<p>Once the <code>readlinePromises.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.<span class="hljs-title function_">on</span>(<span class="hljs-string">'line'</span>, <span class="hljs-function">(<span class="hljs-params">line</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Received: <span class="hljs-subst">${line}</span>`</span>);
});</code> <button class="copy-button">copy</button></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="#all_process_processstdout"><code>process.stdout</code></a> does this automatically when it is a TTY).</p>
<h5>Use of the <code>completer</code> function<span><a class="mark" href="#all_readline_use-of-the-completer-function" id="all_readline_use-of-the-completer-function">#</a></span><a aria-hidden="true" class="legacy" id="readline_use_of_the_completer_function"></a></h5>
<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"><span class="hljs-keyword">function</span> <span class="hljs-title function_">completer</span>(<span class="hljs-params">line</span>) {
  <span class="hljs-keyword">const</span> completions = <span class="hljs-string">'.help .error .exit .quit .q'</span>.<span class="hljs-title function_">split</span>(<span class="hljs-string">' '</span>);
  <span class="hljs-keyword">const</span> hits = completions.<span class="hljs-title function_">filter</span>(<span class="hljs-function">(<span class="hljs-params">c</span>) =></span> c.<span class="hljs-title function_">startsWith</span>(line));
  <span class="hljs-comment">// Show all completions if none found</span>
  <span class="hljs-keyword">return</span> [hits.<span class="hljs-property">length</span> ? hits : completions, line];
}</code> <button class="copy-button">copy</button></pre>
<p>The <code>completer</code> function can also return a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a>, or be asynchronous:</p>
<pre><code class="language-js"><span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">completer</span>(<span class="hljs-params">linePartial</span>) {
  <span class="hljs-keyword">await</span> <span class="hljs-title function_">someAsyncWork</span>();
  <span class="hljs-keyword">return</span> [[<span class="hljs-string">'123'</span>], linePartial];
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Callback API<span><a class="mark" href="#all_readline_callback-api" id="all_readline_callback-api">#</a></span><a aria-hidden="true" class="legacy" id="readline_callback_api"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.104</span>
</div>
<h4>Class: <code>readline.Interface</code><span><a class="mark" href="#all_readline_class-readlineinterface" id="all_readline_class-readlineinterface">#</a></span><a aria-hidden="true" class="legacy" id="readline_class_readline_interface"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.0.0</td>
<td><p>The class <code>readline.Interface</code> now inherits from <code>Interface</code>.</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>Extends: <a href="#all_readline_class-interfaceconstructor" class="type">&#x3C;readline.InterfaceConstructor></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="#all_stream_readable-streams">Readable</a> stream and a single <code>output</code> <a href="#all_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>
<h5><code>rl.question(query[, options], callback)</code><span><a class="mark" href="#all_readline_rlquestionquery-options-callback" id="all_readline_rlquestionquery-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="readline_rl_question_query_options_callback"></a></h5>
<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>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> Optionally allows the <code>question()</code> to be canceled
using an <code>AbortController</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 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>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>
<p>An error will be thrown if calling <code>rl.question()</code> after <code>rl.close()</code>.</p>
<p>Example usage:</p>
<pre><code class="language-js">rl.<span class="hljs-title function_">question</span>(<span class="hljs-string">'What is your favorite food? '</span>, <span class="hljs-function">(<span class="hljs-params">answer</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Oh, so your favorite food is <span class="hljs-subst">${answer}</span>`</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>Using an <code>AbortController</code> to cancel a question.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> ac = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
<span class="hljs-keyword">const</span> signal = ac.<span class="hljs-property">signal</span>;

rl.<span class="hljs-title function_">question</span>(<span class="hljs-string">'What is your favorite food? '</span>, { signal }, <span class="hljs-function">(<span class="hljs-params">answer</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Oh, so your favorite food is <span class="hljs-subst">${answer}</span>`</span>);
});

signal.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">'abort'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'The food question timed out'</span>);
}, { <span class="hljs-attr">once</span>: <span class="hljs-literal">true</span> });

<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> ac.<span class="hljs-title function_">abort</span>(), <span class="hljs-number">10000</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>readline.clearLine(stream, dir[, callback])</code><span><a class="mark" href="#all_readline_readlineclearlinestream-dir-callback" id="all_readline_readlineclearlinestream-dir-callback">#</a></span><a aria-hidden="true" class="legacy" id="readline_readline_clearline_stream_dir_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></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="#all_stream_class-streamwritable" class="type">&#x3C;stream.Writable></a></li>
<li><code>dir</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a>
<ul>
<li><code>-1</code>: to the left from cursor</li>
<li><code>1</code>: to the right from cursor</li>
<li><code>0</code>: the entire line</li>
</ul>
</li>
<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>
<h4><code>readline.clearScreenDown(stream[, callback])</code><span><a class="mark" href="#all_readline_readlineclearscreendownstream-callback" id="all_readline_readlineclearscreendownstream-callback">#</a></span><a aria-hidden="true" class="legacy" id="readline_readline_clearscreendown_stream_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></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="#all_stream_class-streamwritable" 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>
<h4><code>readline.createInterface(options)</code><span><a class="mark" href="#all_readline_readlinecreateinterfaceoptions" id="all_readline_readlinecreateinterfaceoptions">#</a></span><a aria-hidden="true" class="legacy" id="readline_readline_createinterface_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.14.0, v14.18.0</td>
<td><p>The <code>signal</code> option is supported now.</p></td></tr>
<tr><td>v15.8.0, v14.18.0</td>
<td><p>The <code>history</code> option is supported now.</p></td></tr>
<tr><td>v13.9.0</td>
<td><p>The <code>tabSize</code> option is supported now.</p></td></tr>
<tr><td>v8.3.0, v6.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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>input</code> <a href="#all_stream_class-streamreadable" class="type">&#x3C;stream.Readable></a> The <a href="#all_stream_readable-streams">Readable</a> stream to listen to. This option
is <em>required</em>.</li>
<li><code>output</code> <a href="#all_stream_class-streamwritable" class="type">&#x3C;stream.Writable></a> The <a href="#all_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>history</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> Initial list of history lines. 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>[]</code>.</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>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>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="#all_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>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>
<li><code>tabSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> The number of spaces a tab is equal to (minimum 1).
<strong>Default:</strong> <code>8</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> Allows closing the interface using an AbortSignal.
Aborting the signal will internally call <code>close</code> on the interface.</li>
</ul>
</li>
<li>Returns: <a href="#all_readline_class-readlineinterface" class="type">&#x3C;readline.Interface></a></li>
</ul>
<p>The <code>readline.createInterface()</code> method creates a new <code>readline.Interface</code>
instance.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> readline = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:readline'</span>);
<span class="hljs-keyword">const</span> rl = readline.<span class="hljs-title function_">createInterface</span>({
  <span class="hljs-attr">input</span>: process.<span class="hljs-property">stdin</span>,
  <span class="hljs-attr">output</span>: process.<span class="hljs-property">stdout</span>,
});</code> <button class="copy-button">copy</button></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.<span class="hljs-title function_">on</span>(<span class="hljs-string">'line'</span>, <span class="hljs-function">(<span class="hljs-params">line</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Received: <span class="hljs-subst">${line}</span>`</span>);
});</code> <button class="copy-button">copy</button></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="#all_process_processstdout"><code>process.stdout</code></a> does this automatically when it is a TTY).</p>
<p>When creating a <code>readline.Interface</code> using <code>stdin</code> as input, the program
will not terminate until it receives an <a href="https://en.wikipedia.org/wiki/End-of-file#EOF_character">EOF character</a>. To exit without
waiting for user input, call <code>process.stdin.unref()</code>.</p>
<h5>Use of the <code>completer</code> function<span><a class="mark" href="#all_readline_use-of-the-completer-function_1" id="all_readline_use-of-the-completer-function_1">#</a></span><a aria-hidden="true" class="legacy" id="readline_use_of_the_completer_function_1"></a></h5>
<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"><span class="hljs-keyword">function</span> <span class="hljs-title function_">completer</span>(<span class="hljs-params">line</span>) {
  <span class="hljs-keyword">const</span> completions = <span class="hljs-string">'.help .error .exit .quit .q'</span>.<span class="hljs-title function_">split</span>(<span class="hljs-string">' '</span>);
  <span class="hljs-keyword">const</span> hits = completions.<span class="hljs-title function_">filter</span>(<span class="hljs-function">(<span class="hljs-params">c</span>) =></span> c.<span class="hljs-title function_">startsWith</span>(line));
  <span class="hljs-comment">// Show all completions if none found</span>
  <span class="hljs-keyword">return</span> [hits.<span class="hljs-property">length</span> ? hits : completions, line];
}</code> <button class="copy-button">copy</button></pre>
<p>The <code>completer</code> function can be called asynchronously if it accepts two
arguments:</p>
<pre><code class="language-js"><span class="hljs-keyword">function</span> <span class="hljs-title function_">completer</span>(<span class="hljs-params">linePartial, callback</span>) {
  <span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, [[<span class="hljs-string">'123'</span>], linePartial]);
}</code> <button class="copy-button">copy</button></pre>
<h4><code>readline.cursorTo(stream, x[, y][, callback])</code><span><a class="mark" href="#all_readline_readlinecursortostream-x-y-callback" id="all_readline_readlinecursortostream-x-y-callback">#</a></span><a aria-hidden="true" class="legacy" id="readline_readline_cursorto_stream_x_y_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></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="#all_stream_class-streamwritable" 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>
<h4><code>readline.moveCursor(stream, dx, dy[, callback])</code><span><a class="mark" href="#all_readline_readlinemovecursorstream-dx-dy-callback" id="all_readline_readlinemovecursorstream-dx-dy-callback">#</a></span><a aria-hidden="true" class="legacy" id="readline_readline_movecursor_stream_dx_dy_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></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="#all_stream_class-streamwritable" 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>
</section><section><h3><code>readline.emitKeypressEvents(stream[, interface])</code><span><a class="mark" href="#all_readline_readlineemitkeypresseventsstream-interface" id="all_readline_readlineemitkeypresseventsstream-interface">#</a></span><a aria-hidden="true" class="legacy" id="readline_readline_emitkeypressevents_stream_interface"></a></h3>
<div class="api_metadata">
<span>Added in: v0.7.7</span>
</div>
<ul>
<li><code>stream</code> <a href="#all_stream_class-streamreadable" class="type">&#x3C;stream.Readable></a></li>
<li><code>interface</code> <a href="#all_readline_class-interfaceconstructor" class="type">&#x3C;readline.InterfaceConstructor></a></li>
</ul>
<p>The <code>readline.emitKeypressEvents()</code> method causes the given <a href="#all_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.<span class="hljs-title function_">emitKeypressEvents</span>(process.<span class="hljs-property">stdin</span>);
<span class="hljs-keyword">if</span> (process.<span class="hljs-property">stdin</span>.<span class="hljs-property">isTTY</span>)
  process.<span class="hljs-property">stdin</span>.<span class="hljs-title function_">setRawMode</span>(<span class="hljs-literal">true</span>);</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Example: Tiny CLI<span><a class="mark" href="#all_readline_example-tiny-cli" id="all_readline_example-tiny-cli">#</a></span><a aria-hidden="true" class="legacy" id="readline_example_tiny_cli"></a></h3>
<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"><span class="hljs-keyword">const</span> readline = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:readline'</span>);
<span class="hljs-keyword">const</span> rl = readline.<span class="hljs-title function_">createInterface</span>({
  <span class="hljs-attr">input</span>: process.<span class="hljs-property">stdin</span>,
  <span class="hljs-attr">output</span>: process.<span class="hljs-property">stdout</span>,
  <span class="hljs-attr">prompt</span>: <span class="hljs-string">'OHAI> '</span>,
});

rl.<span class="hljs-title function_">prompt</span>();

rl.<span class="hljs-title function_">on</span>(<span class="hljs-string">'line'</span>, <span class="hljs-function">(<span class="hljs-params">line</span>) =></span> {
  <span class="hljs-keyword">switch</span> (line.<span class="hljs-title function_">trim</span>()) {
    <span class="hljs-keyword">case</span> <span class="hljs-string">'hello'</span>:
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'world!'</span>);
      <span class="hljs-keyword">break</span>;
    <span class="hljs-attr">default</span>:
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Say what? I might have heard '<span class="hljs-subst">${line.trim()}</span>'`</span>);
      <span class="hljs-keyword">break</span>;
  }
  rl.<span class="hljs-title function_">prompt</span>();
}).<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Have a great day!'</span>);
  process.<span class="hljs-title function_">exit</span>(<span class="hljs-number">0</span>);
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Example: Read file stream line-by-Line<span><a class="mark" href="#all_readline_example-read-file-stream-line-by-line" id="all_readline_example-read-file-stream-line-by-line">#</a></span><a aria-hidden="true" class="legacy" id="readline_example_read_file_stream_line_by_line"></a></h3>
<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="#all_fs_class-fsreadstream"><code>fs.ReadStream</code></a> API as
well as a <code>for await...of</code> loop:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> readline = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:readline'</span>);

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">processLineByLine</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">const</span> fileStream = fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'input.txt'</span>);

  <span class="hljs-keyword">const</span> rl = readline.<span class="hljs-title function_">createInterface</span>({
    <span class="hljs-attr">input</span>: fileStream,
    <span class="hljs-attr">crlfDelay</span>: <span class="hljs-title class_">Infinity</span>,
  });
  <span class="hljs-comment">// Note: we use the crlfDelay option to recognize all instances of CR LF</span>
  <span class="hljs-comment">// ('\r\n') in input.txt as a single line break.</span>

  <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> line <span class="hljs-keyword">of</span> rl) {
    <span class="hljs-comment">// Each line in input.txt will be successively available here as `line`.</span>
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Line from file: <span class="hljs-subst">${line}</span>`</span>);
  }
}

<span class="hljs-title function_">processLineByLine</span>();</code> <button class="copy-button">copy</button></pre>
<p>Alternatively, one could use the <a href="#all_readline_event-line"><code>'line'</code></a> event:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> readline = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:readline'</span>);

<span class="hljs-keyword">const</span> rl = readline.<span class="hljs-title function_">createInterface</span>({
  <span class="hljs-attr">input</span>: fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'sample.txt'</span>),
  <span class="hljs-attr">crlfDelay</span>: <span class="hljs-title class_">Infinity</span>,
});

rl.<span class="hljs-title function_">on</span>(<span class="hljs-string">'line'</span>, <span class="hljs-function">(<span class="hljs-params">line</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Line from file: <span class="hljs-subst">${line}</span>`</span>);
});</code> <button class="copy-button">copy</button></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"><span class="hljs-keyword">const</span> { once } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);
<span class="hljs-keyword">const</span> { createReadStream } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> { createInterface } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:readline'</span>);

(<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">processLineByLine</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> rl = <span class="hljs-title function_">createInterface</span>({
      <span class="hljs-attr">input</span>: <span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'big-file.txt'</span>),
      <span class="hljs-attr">crlfDelay</span>: <span class="hljs-title class_">Infinity</span>,
    });

    rl.<span class="hljs-title function_">on</span>(<span class="hljs-string">'line'</span>, <span class="hljs-function">(<span class="hljs-params">line</span>) =></span> {
      <span class="hljs-comment">// Process the line.</span>
    });

    <span class="hljs-keyword">await</span> <span class="hljs-title function_">once</span>(rl, <span class="hljs-string">'close'</span>);

    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'File processed.'</span>);
  } <span class="hljs-keyword">catch</span> (err) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err);
  }
})();</code> <button class="copy-button">copy</button></pre>
</section><section><h3>TTY keybindings<span><a class="mark" href="#all_readline_tty-keybindings" id="all_readline_tty-keybindings">#</a></span><a aria-hidden="true" class="legacy" id="readline_tty_keybindings"></a></h3>
<table>
  <tbody><tr>
    <th>Keybindings</th>
    <th>Description</th>
    <th>Notes</th>
  </tr>
  <tr>
    <td><kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>Backspace</kbd></td>
    <td>Delete line left</td>
    <td>Doesn't work on Linux, Mac and Windows</td>
  </tr>
  <tr>
    <td><kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>Delete</kbd></td>
    <td>Delete line right</td>
    <td>Doesn't work on Mac</td>
  </tr>
  <tr>
    <td><kbd>Ctrl</kbd>+<kbd>C</kbd></td>
    <td>Emit <code>SIGINT</code> or close the readline instance</td>
    <td></td>
  </tr>
  <tr>
    <td><kbd>Ctrl</kbd>+<kbd>H</kbd></td>
    <td>Delete left</td>
    <td></td>
  </tr>
  <tr>
    <td><kbd>Ctrl</kbd>+<kbd>D</kbd></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><kbd>Ctrl</kbd>+<kbd>U</kbd></td>
    <td>Delete from the current position to the line start</td>
    <td></td>
  </tr>
  <tr>
    <td><kbd>Ctrl</kbd>+<kbd>K</kbd></td>
    <td>Delete from the current position to the end of line</td>
    <td></td>
  </tr>
  <tr>
    <td><kbd>Ctrl</kbd>+<kbd>Y</kbd></td>
    <td>Yank (Recall) the previously deleted text</td>
    <td>Only works with text deleted by <kbd>Ctrl</kbd>+<kbd>U</kbd> or <kbd>Ctrl</kbd>+<kbd>K</kbd></td>
  </tr>
  <tr>
    <td><kbd>Meta</kbd>+<kbd>Y</kbd></td>
    <td>Cycle among previously deleted texts</td>
    <td>Only available when the last keystroke is <kbd>Ctrl</kbd>+<kbd>Y</kbd> or <kbd>Meta</kbd>+<kbd>Y</kbd></td>
  </tr>
  <tr>
    <td><kbd>Ctrl</kbd>+<kbd>A</kbd></td>
    <td>Go to start of line</td>
    <td></td>
  </tr>
  <tr>
    <td><kbd>Ctrl</kbd>+<kbd>E</kbd></td>
    <td>Go to end of line</td>
    <td></td>
  </tr>
  <tr>
    <td><kbd>Ctrl</kbd>+<kbd>B</kbd></td>
    <td>Back one character</td>
    <td></td>
  </tr>
  <tr>
    <td><kbd>Ctrl</kbd>+<kbd>F</kbd></td>
    <td>Forward one character</td>
    <td></td>
  </tr>
  <tr>
    <td><kbd>Ctrl</kbd>+<kbd>L</kbd></td>
    <td>Clear screen</td>
    <td></td>
  </tr>
  <tr>
    <td><kbd>Ctrl</kbd>+<kbd>N</kbd></td>
    <td>Next history item</td>
    <td></td>
  </tr>
  <tr>
    <td><kbd>Ctrl</kbd>+<kbd>P</kbd></td>
    <td>Previous history item</td>
    <td></td>
  </tr>
  <tr>
    <td><kbd>Ctrl</kbd>+<kbd>-</kbd></td>
    <td>Undo previous change</td>
    <td>Any keystroke that emits key code <code>0x1F</code> will do this action.
    In many terminals, for example <code>xterm</code>,
    this is bound to <kbd>Ctrl</kbd>+<kbd>-</kbd>.</td>
  </tr>
  <tr>
    <td><kbd>Ctrl</kbd>+<kbd>6</kbd></td>
    <td>Redo previous change</td>
    <td>Many terminals don't have a default redo keystroke.
    We choose key code <code>0x1E</code> to perform redo.
    In <code>xterm</code>, it is bound to <kbd>Ctrl</kbd>+<kbd>6</kbd>
    by default.</td>
  </tr>
  <tr>
    <td><kbd>Ctrl</kbd>+<kbd>Z</kbd></td>
    <td>Moves running process into background. Type
    <code>fg</code> and press <kbd>Enter</kbd>
    to return.</td>
    <td>Doesn't work on Windows</td>
  </tr>
  <tr>
    <td><kbd>Ctrl</kbd>+<kbd>W</kbd> or <kbd>Ctrl</kbd>
   +<kbd>Backspace</kbd></td>
    <td>Delete backward to a word boundary</td>
    <td><kbd>Ctrl</kbd>+<kbd>Backspace</kbd> Doesn't
    work on Linux, Mac and Windows</td>
  </tr>
  <tr>
    <td><kbd>Ctrl</kbd>+<kbd>Delete</kbd></td>
    <td>Delete forward to a word boundary</td>
    <td>Doesn't work on Mac</td>
  </tr>
  <tr>
    <td><kbd>Ctrl</kbd>+<kbd>Left arrow</kbd> or
    <kbd>Meta</kbd>+<kbd>B</kbd></td>
    <td>Word left</td>
    <td><kbd>Ctrl</kbd>+<kbd>Left arrow</kbd> Doesn't work
    on Mac</td>
  </tr>
  <tr>
    <td><kbd>Ctrl</kbd>+<kbd>Right arrow</kbd> or
    <kbd>Meta</kbd>+<kbd>F</kbd></td>
    <td>Word right</td>
    <td><kbd>Ctrl</kbd>+<kbd>Right arrow</kbd> Doesn't work
    on Mac</td>
  </tr>
  <tr>
    <td><kbd>Meta</kbd>+<kbd>D</kbd> or <kbd>Meta</kbd>
   +<kbd>Delete</kbd></td>
    <td>Delete word right</td>
    <td><kbd>Meta</kbd>+<kbd>Delete</kbd> Doesn't work
    on windows</td>
  </tr>
  <tr>
    <td><kbd>Meta</kbd>+<kbd>Backspace</kbd></td>
    <td>Delete word left</td>
    <td>Doesn't work on Mac</td>
  </tr>
</tbody></table></section>
        </section>
<section><h2>REPL<span><a class="mark" href="#all_repl_repl" id="all_repl_repl">#</a></span><a aria-hidden="true" class="legacy" id="repl_repl"></a></h2>

<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/repl.js">lib/repl.js</a></p>
<p>The <code>node: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"><span class="hljs-keyword">const</span> repl = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:repl'</span>);</code> <button class="copy-button">copy</button></pre>
<section><h3>Design and features<span><a class="mark" href="#all_repl_design-and-features" id="all_repl_design-and-features">#</a></span><a aria-hidden="true" class="legacy" id="repl_design_and_features"></a></h3>
<p>The <code>node:repl</code> module exports the <a href="#all_repl_class-replserver"><code>repl.REPLServer</code></a> class. While running,
instances of <a href="#all_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="#all_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>
<h4>Commands and special keys<span><a class="mark" href="#all_repl_commands-and-special-keys" id="all_repl_commands-and-special-keys">#</a></span><a aria-hidden="true" class="legacy" id="repl_commands_and_special_keys"></a></h4>
<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, enter
the <code>.break</code> command (or press <kbd>Ctrl</kbd>+<kbd>C</kbd>) to 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 (<kbd>Ctrl</kbd>+<kbd>D</kbd> to
finish, <kbd>Ctrl</kbd>+<kbd>C</kbd> to cancel).</li>
</ul>
<pre><code class="language-console"><span class="hljs-meta prompt_">> </span><span class="language-bash">.editor</span>
// Entering editor mode (^D to finish, ^C to cancel)
function welcome(name) {
  return `Hello ${name}!`;
}

welcome('Node.js User');

// ^D
'Hello Node.js User!'
<span class="hljs-meta prompt_">></span></code> <button class="copy-button">copy</button></pre>
<p>The following key combinations in the REPL have these special effects:</p>
<ul>
<li><kbd>Ctrl</kbd>+<kbd>C</kbd>: 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><kbd>Ctrl</kbd>+<kbd>D</kbd>: Has the same effect as the <code>.exit</code> command.</li>
<li><kbd>Tab</kbd>: 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="#all_repl_reverse-i-search"><code>reverse-i-search</code></a>.
For all other key bindings, see <a href="#all_readline_tty-keybindings">TTY keybindings</a>.</p>
<h4>Default evaluation<span><a class="mark" href="#all_repl_default-evaluation" id="all_repl_default-evaluation">#</a></span><a aria-hidden="true" class="legacy" id="repl_default_evaluation"></a></h4>
<p>By default, all instances of <a href="#all_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="#all_repl_class-replserver"><code>repl.REPLServer</code></a> instance is created.</p>
<h5>JavaScript expressions<span><a class="mark" href="#all_repl_javascript-expressions" id="all_repl_javascript-expressions">#</a></span><a aria-hidden="true" class="legacy" id="repl_javascript_expressions"></a></h5>
<p>The default evaluator supports direct evaluation of JavaScript expressions:</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">> </span><span class="language-bash">1 + 1</span>
2
<span class="hljs-meta prompt_">> </span><span class="language-bash">const m = 2</span>
undefined
<span class="hljs-meta prompt_">> </span><span class="language-bash">m + 1</span>
3</code> <button class="copy-button">copy</button></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>
<h5>Global and local scope<span><a class="mark" href="#all_repl_global-and-local-scope" id="all_repl_global-and-local-scope">#</a></span><a aria-hidden="true" class="legacy" id="repl_global_and_local_scope"></a></h5>
<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"><span class="hljs-keyword">const</span> repl = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:repl'</span>);
<span class="hljs-keyword">const</span> msg = <span class="hljs-string">'message'</span>;

repl.<span class="hljs-title function_">start</span>(<span class="hljs-string">'> '</span>).<span class="hljs-property">context</span>.<span class="hljs-property">m</span> = msg;</code> <button class="copy-button">copy</button></pre>
<p>Properties in the <code>context</code> object appear as local within the REPL:</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node repl_test.js</span>
<span class="hljs-meta prompt_">> </span><span class="language-bash">m</span>
'message'</code> <button class="copy-button">copy</button></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"><span class="hljs-keyword">const</span> repl = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:repl'</span>);
<span class="hljs-keyword">const</span> msg = <span class="hljs-string">'message'</span>;

<span class="hljs-keyword">const</span> r = repl.<span class="hljs-title function_">start</span>(<span class="hljs-string">'> '</span>);
<span class="hljs-title class_">Object</span>.<span class="hljs-title function_">defineProperty</span>(r.<span class="hljs-property">context</span>, <span class="hljs-string">'m'</span>, {
  <span class="hljs-attr">configurable</span>: <span class="hljs-literal">false</span>,
  <span class="hljs-attr">enumerable</span>: <span class="hljs-literal">true</span>,
  <span class="hljs-attr">value</span>: msg,
});</code> <button class="copy-button">copy</button></pre>
<h5>Accessing core Node.js modules<span><a class="mark" href="#all_repl_accessing-core-nodejs-modules" id="all_repl_accessing-core-nodejs-modules">#</a></span><a aria-hidden="true" class="legacy" id="repl_accessing_core_node_js_modules"></a></h5>
<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('node:fs')</code>.</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">> </span><span class="language-bash">fs.createReadStream(<span class="hljs-string">'./some/file'</span>);</span></code> <button class="copy-button">copy</button></pre>
<h5>Global uncaught exceptions<span><a class="mark" href="#all_repl_global-uncaught-exceptions" id="all_repl_global-uncaught-exceptions">#</a></span><a aria-hidden="true" class="legacy" id="repl_global_uncaught_exceptions"></a></h5>
<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>
<p>Uncaught exceptions only emit the <a href="#all_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 results in <a href="#all_errors_err_invalid_repl_input"><code>ERR_INVALID_REPL_INPUT</code></a>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> r = repl.<span class="hljs-title function_">start</span>();

r.<span class="hljs-title function_">write</span>(<span class="hljs-string">'process.on("uncaughtException", () => console.log("Foobar"));\n'</span>);
<span class="hljs-comment">// Output stream includes:</span>
<span class="hljs-comment">//   TypeError [ERR_INVALID_REPL_INPUT]: Listeners for `uncaughtException`</span>
<span class="hljs-comment">//   cannot be used in the REPL</span>

r.<span class="hljs-title function_">close</span>();</code> <button class="copy-button">copy</button></pre>
</li>
<li>
<p>Trying to use <a href="#all_process_processsetuncaughtexceptioncapturecallbackfn"><code>process.setUncaughtExceptionCaptureCallback()</code></a> throws
an <a href="#all_errors_err_domain_cannot_set_uncaught_exception_capture"><code>ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE</code></a> error.</p>
</li>
</ul>
<h5>Assignment of the <code>_</code> (underscore) variable<span><a class="mark" href="#all_repl_assignment-of-the-_-underscore-variable" id="all_repl_assignment-of-the-_-underscore-variable">#</a></span><a aria-hidden="true" class="legacy" id="repl_assignment_of_the_underscore_variable"></a></h5>
<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"><span class="hljs-meta prompt_">> </span><span class="language-bash">[ <span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span> ]</span>
[ 'a', 'b', 'c' ]
<span class="hljs-meta prompt_">> </span><span class="language-bash">_.length</span>
3
<span class="hljs-meta prompt_">> </span><span class="language-bash">_ += 1</span>
Expression assignment to _ now disabled.
4
<span class="hljs-meta prompt_">> </span><span class="language-bash">1 + 1</span>
2
<span class="hljs-meta prompt_">> </span><span class="language-bash">_</span>
4</code> <button class="copy-button">copy</button></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"><span class="hljs-meta prompt_">> </span><span class="language-bash">throw new Error(<span class="hljs-string">'foo'</span>);</span>
Uncaught Error: foo
<span class="hljs-meta prompt_">> </span><span class="language-bash">_error.message</span>
'foo'</code> <button class="copy-button">copy</button></pre>
<h5><code>await</code> keyword<span><a class="mark" href="#all_repl_await-keyword" id="all_repl_await-keyword">#</a></span><a aria-hidden="true" class="legacy" id="repl_await_keyword"></a></h5>
<p>Support for the <code>await</code> keyword is enabled at the top level.</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">> </span><span class="language-bash">await Promise.resolve(123)</span>
123
<span class="hljs-meta prompt_">> </span><span class="language-bash">await Promise.reject(new Error(<span class="hljs-string">'REPL await'</span>))</span>
Uncaught Error: REPL await
    at REPL2:1:54
<span class="hljs-meta prompt_">> </span><span class="language-bash">const <span class="hljs-built_in">timeout</span> = util.promisify(setTimeout);</span>
undefined
<span class="hljs-meta prompt_">> </span><span class="language-bash">const old = Date.now(); await <span class="hljs-built_in">timeout</span>(1000); console.log(Date.now() - old);</span>
1002
undefined</code> <button class="copy-button">copy</button></pre>
<p>One known limitation of using the <code>await</code> keyword in the REPL is that
it will invalidate the lexical scoping of the <code>const</code> and <code>let</code>
keywords.</p>
<p>For example:</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">> </span><span class="language-bash">const m = await Promise.resolve(123)</span>
undefined
<span class="hljs-meta prompt_">> </span><span class="language-bash">m</span>
123
<span class="hljs-meta prompt_">> </span><span class="language-bash">const m = await Promise.resolve(234)</span>
undefined
<span class="hljs-meta prompt_">> </span><span class="language-bash">m</span>
234</code> <button class="copy-button">copy</button></pre>
<p><a href="#all_cli_--no-experimental-repl-await"><code>--no-experimental-repl-await</code></a> shall disable top-level await in REPL.</p>
<h4>Reverse-i-search<span><a class="mark" href="#all_repl_reverse-i-search" id="all_repl_reverse-i-search">#</a></span><a aria-hidden="true" class="legacy" id="repl_reverse_i_search"></a></h4>
<div class="api_metadata">
<span>Added in: v13.6.0, 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 <kbd>Ctrl</kbd>+<kbd>R</kbd> to search backward
and <kbd>Ctrl</kbd>+<kbd>S</kbd> to search forwards.</p>
<p>Duplicated history entries will be skipped.</p>
<p>Entries are accepted as soon as any key is pressed that doesn't correspond
with the reverse search. Cancelling is possible by pressing <kbd>Esc</kbd>
or <kbd>Ctrl</kbd>+<kbd>C</kbd>.</p>
<p>Changing the direction immediately searches for the next entry in the expected
direction from the current position on.</p>
<h4>Custom evaluation functions<span><a class="mark" href="#all_repl_custom-evaluation-functions" id="all_repl_custom-evaluation-functions">#</a></span><a aria-hidden="true" class="legacy" id="repl_custom_evaluation_functions"></a></h4>
<p>When a new <a href="#all_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"><span class="hljs-keyword">const</span> repl = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:repl'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Translator</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'translator'</span>);

<span class="hljs-keyword">const</span> myTranslator = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Translator</span>(<span class="hljs-string">'en'</span>, <span class="hljs-string">'fr'</span>);

<span class="hljs-keyword">function</span> <span class="hljs-title function_">myEval</span>(<span class="hljs-params">cmd, context, filename, callback</span>) {
  <span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, myTranslator.<span class="hljs-title function_">translate</span>(cmd));
}

repl.<span class="hljs-title function_">start</span>({ <span class="hljs-attr">prompt</span>: <span class="hljs-string">'> '</span>, <span class="hljs-attr">eval</span>: myEval });</code> <button class="copy-button">copy</button></pre>
<h5>Recoverable errors<span><a class="mark" href="#all_repl_recoverable-errors" id="all_repl_recoverable-errors">#</a></span><a aria-hidden="true" class="legacy" id="repl_recoverable_errors"></a></h5>
<p>At the REPL prompt, pressing <kbd>Enter</kbd> sends the current line of input to
the <code>eval</code> function. In order to support multi-line input, the <code>eval</code> function
can return an instance of <code>repl.Recoverable</code> to the provided callback function:</p>
<pre><code class="language-js"><span class="hljs-keyword">function</span> <span class="hljs-title function_">myEval</span>(<span class="hljs-params">cmd, context, filename, callback</span>) {
  <span class="hljs-keyword">let</span> result;
  <span class="hljs-keyword">try</span> {
    result = vm.<span class="hljs-title function_">runInThisContext</span>(cmd);
  } <span class="hljs-keyword">catch</span> (e) {
    <span class="hljs-keyword">if</span> (<span class="hljs-title function_">isRecoverableError</span>(e)) {
      <span class="hljs-keyword">return</span> <span class="hljs-title function_">callback</span>(<span class="hljs-keyword">new</span> repl.<span class="hljs-title class_">Recoverable</span>(e));
    }
  }
  <span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, result);
}

<span class="hljs-keyword">function</span> <span class="hljs-title function_">isRecoverableError</span>(<span class="hljs-params">error</span>) {
  <span class="hljs-keyword">if</span> (error.<span class="hljs-property">name</span> === <span class="hljs-string">'SyntaxError'</span>) {
    <span class="hljs-keyword">return</span> <span class="hljs-regexp">/^(Unexpected end of input|Unexpected token)/</span>.<span class="hljs-title function_">test</span>(error.<span class="hljs-property">message</span>);
  }
  <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
}</code> <button class="copy-button">copy</button></pre>
<h4>Customizing REPL output<span><a class="mark" href="#all_repl_customizing-repl-output" id="all_repl_customizing-repl-output">#</a></span><a aria-hidden="true" class="legacy" id="repl_customizing_repl_output"></a></h4>
<p>By default, <a href="#all_repl_class-replserver"><code>repl.REPLServer</code></a> instances format output using the
<a href="#all_util_utilinspectobject-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="#all_util_utilinspectobject-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="#all_util_utilinspectobject-options"><code>util.inspect()</code></a>.</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">> </span><span class="language-bash">util.inspect.replDefaults.compact = <span class="hljs-literal">false</span>;</span>
false
<span class="hljs-meta prompt_">> </span><span class="language-bash">[1]</span>
[
  1
]
<span class="hljs-meta prompt_">></span></code> <button class="copy-button">copy</button></pre>
<p>To fully customize the output of a <a href="#all_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"><span class="hljs-keyword">const</span> repl = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:repl'</span>);

<span class="hljs-keyword">const</span> r = repl.<span class="hljs-title function_">start</span>({ <span class="hljs-attr">prompt</span>: <span class="hljs-string">'> '</span>, <span class="hljs-attr">eval</span>: myEval, <span class="hljs-attr">writer</span>: myWriter });

<span class="hljs-keyword">function</span> <span class="hljs-title function_">myEval</span>(<span class="hljs-params">cmd, context, filename, callback</span>) {
  <span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, cmd);
}

<span class="hljs-keyword">function</span> <span class="hljs-title function_">myWriter</span>(<span class="hljs-params">output</span>) {
  <span class="hljs-keyword">return</span> output.<span class="hljs-title function_">toUpperCase</span>();
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>REPLServer</code><span><a class="mark" href="#all_repl_class-replserver" id="all_repl_class-replserver">#</a></span><a aria-hidden="true" class="legacy" id="repl_class_replserver"></a></h3>
<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="#all_repl_replstartoptions"><code>repl.start()</code></a></li>
<li>Extends: <a href="#all_readline_class-readlineinterface" class="type">&#x3C;readline.Interface></a></li>
</ul>
<p>Instances of <code>repl.REPLServer</code> are created using the <a href="#all_repl_replstartoptions"><code>repl.start()</code></a> method
or directly using the JavaScript <code>new</code> keyword.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> repl = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:repl'</span>);

<span class="hljs-keyword">const</span> options = { <span class="hljs-attr">useColors</span>: <span class="hljs-literal">true</span> };

<span class="hljs-keyword">const</span> firstInstance = repl.<span class="hljs-title function_">start</span>(options);
<span class="hljs-keyword">const</span> secondInstance = <span class="hljs-keyword">new</span> repl.<span class="hljs-title class_">REPLServer</span>(options);</code> <button class="copy-button">copy</button></pre>
<h4>Event: <code>'exit'</code><span><a class="mark" href="#all_repl_event-exit" id="all_repl_event-exit">#</a></span><a aria-hidden="true" class="legacy" id="repl_event_exit"></a></h4>
<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 <kbd>Ctrl</kbd>+<kbd>C</kbd> twice
to signal <code>SIGINT</code>,
or by pressing <kbd>Ctrl</kbd>+<kbd>D</kbd> to signal <code>'end'</code> on the input
stream. The listener
callback is invoked without any arguments.</p>
<pre><code class="language-js">replServer.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Received "exit" event from repl!'</span>);
  process.<span class="hljs-title function_">exit</span>();
});</code> <button class="copy-button">copy</button></pre>
<h4>Event: <code>'reset'</code><span><a class="mark" href="#all_repl_event-reset" id="all_repl_event-reset">#</a></span><a aria-hidden="true" class="legacy" id="repl_event_reset"></a></h4>
<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"><span class="hljs-keyword">const</span> repl = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:repl'</span>);

<span class="hljs-keyword">function</span> <span class="hljs-title function_">initializeContext</span>(<span class="hljs-params">context</span>) {
  context.<span class="hljs-property">m</span> = <span class="hljs-string">'test'</span>;
}

<span class="hljs-keyword">const</span> r = repl.<span class="hljs-title function_">start</span>({ <span class="hljs-attr">prompt</span>: <span class="hljs-string">'> '</span> });
<span class="hljs-title function_">initializeContext</span>(r.<span class="hljs-property">context</span>);

r.<span class="hljs-title function_">on</span>(<span class="hljs-string">'reset'</span>, initializeContext);</code> <button class="copy-button">copy</button></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"><span class="hljs-meta prompt_">$ </span><span class="language-bash">./node example.js</span>
<span class="hljs-meta prompt_">> </span><span class="language-bash">m</span>
'test'
<span class="hljs-meta prompt_">> </span><span class="language-bash">m = 1</span>
1
<span class="hljs-meta prompt_">> </span><span class="language-bash">m</span>
1
<span class="hljs-meta prompt_">> </span><span class="language-bash">.clear</span>
Clearing context...
<span class="hljs-meta prompt_">> </span><span class="language-bash">m</span>
'test'
<span class="hljs-meta prompt_">></span></code> <button class="copy-button">copy</button></pre>
<h4><code>replServer.defineCommand(keyword, cmd)</code><span><a class="mark" href="#all_repl_replserverdefinecommandkeyword-cmd" id="all_repl_replserverdefinecommandkeyword-cmd">#</a></span><a aria-hidden="true" class="legacy" id="repl_replserver_definecommand_keyword_cmd"></a></h4>
<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"><span class="hljs-keyword">const</span> repl = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:repl'</span>);

<span class="hljs-keyword">const</span> replServer = repl.<span class="hljs-title function_">start</span>({ <span class="hljs-attr">prompt</span>: <span class="hljs-string">'> '</span> });
replServer.<span class="hljs-title function_">defineCommand</span>(<span class="hljs-string">'sayhello'</span>, {
  <span class="hljs-attr">help</span>: <span class="hljs-string">'Say hello'</span>,
  <span class="hljs-title function_">action</span>(<span class="hljs-params">name</span>) {
    <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">clearBufferedCommand</span>();
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>);
    <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">displayPrompt</span>();
  },
});
replServer.<span class="hljs-title function_">defineCommand</span>(<span class="hljs-string">'saybye'</span>, <span class="hljs-keyword">function</span> <span class="hljs-title function_">saybye</span>(<span class="hljs-params"></span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Goodbye!'</span>);
  <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">close</span>();
});</code> <button class="copy-button">copy</button></pre>
<p>The new commands can then be used from within the REPL instance:</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">> </span><span class="language-bash">.sayhello Node.js User</span>
Hello, Node.js User!
<span class="hljs-meta prompt_">> </span><span class="language-bash">.saybye</span>
Goodbye!</code> <button class="copy-button">copy</button></pre>
<h4><code>replServer.displayPrompt([preserveCursor])</code><span><a class="mark" href="#all_repl_replserverdisplaypromptpreservecursor" id="all_repl_replserverdisplaypromptpreservecursor">#</a></span><a aria-hidden="true" class="legacy" id="repl_replserver_displayprompt_preservecursor"></a></h4>
<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>
<h4><code>replServer.clearBufferedCommand()</code><span><a class="mark" href="#all_repl_replserverclearbufferedcommand" id="all_repl_replserverclearbufferedcommand">#</a></span><a aria-hidden="true" class="legacy" id="repl_replserver_clearbufferedcommand"></a></h4>
<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>
<h4><code>replServer.parseREPLKeyword(keyword[, rest])</code><span><a class="mark" href="#all_repl_replserverparsereplkeywordkeyword-rest" id="all_repl_replserverparsereplkeywordkeyword-rest">#</a></span><a aria-hidden="true" class="legacy" id="repl_replserver_parsereplkeyword_keyword_rest"></a></h4>
<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="#all_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>
<h4><code>replServer.setupHistory(historyPath, callback)</code><span><a class="mark" href="#all_repl_replserversetuphistoryhistorypath-callback" id="all_repl_replserversetuphistoryhistorypath-callback">#</a></span><a aria-hidden="true" class="legacy" id="repl_replserver_setuphistory_historypath_callback"></a></h4>
<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><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
<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="#all_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>
</section><section><h3><code>repl.builtinModules</code><span><a class="mark" href="#all_repl_replbuiltinmodules" id="all_repl_replbuiltinmodules">#</a></span><a aria-hidden="true" class="legacy" id="repl_repl_builtinmodules"></a></h3>
<div class="api_metadata">
<span>Added in: v14.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>A list of the names of all Node.js modules, e.g., <code>'http'</code>.</p>
</section><section><h3><code>repl.start([options])</code><span><a class="mark" href="#all_repl_replstartoptions" id="all_repl_replstartoptions">#</a></span><a aria-hidden="true" class="legacy" id="repl_repl_start_options"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.4.0, 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>v6.3.0</td>
<td><p>The <code>breakEvalOnSigint</code> option is supported now.</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><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>
<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="#all_stream_class-streamreadable" 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="#all_stream_class-streamwritable" 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="#all_util_utilinspectobject-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="#all_readline_use-of-the-completer-function"><code>readline.InterfaceCompleter</code></a> for an example.</li>
<li><code>replMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Symbol_type" class="type">&#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:
<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 <kbd>Ctrl</kbd>+<kbd>C</kbd> 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="#all_repl_class-replserver" class="type">&#x3C;repl.REPLServer></a></li>
</ul>
<p>The <code>repl.start()</code> method creates and starts a <a href="#all_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"><span class="hljs-keyword">const</span> repl = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:repl'</span>);

<span class="hljs-comment">// a Unix style prompt</span>
repl.<span class="hljs-title function_">start</span>(<span class="hljs-string">'$ '</span>);</code> <button class="copy-button">copy</button></pre>
</section><section><h3>The Node.js REPL<span><a class="mark" href="#all_repl_the-nodejs-repl" id="all_repl_the-nodejs-repl">#</a></span><a aria-hidden="true" class="legacy" id="repl_the_node_js_repl"></a></h3>
<p>Node.js itself uses the <code>node: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"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node</span>
<span class="hljs-meta prompt_">> </span><span class="language-bash">const a = [1, 2, 3];</span>
undefined
<span class="hljs-meta prompt_">> </span><span class="language-bash">a</span>
[ 1, 2, 3 ]
<span class="hljs-meta prompt_">> </span><span class="language-bash">a.forEach((v) => {</span>
...   console.log(v);
...   });
1
2
3</code> <button class="copy-button">copy</button></pre>
<h4>Environment variable options<span><a class="mark" href="#all_repl_environment-variable-options" id="all_repl_environment-variable-options">#</a></span><a aria-hidden="true" class="legacy" id="repl_environment_variable_options"></a></h4>
<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>
<h4>Persistent history<span><a class="mark" href="#all_repl_persistent-history" id="all_repl_persistent-history">#</a></span><a aria-hidden="true" class="legacy" id="repl_persistent_history"></a></h4>
<p>By default, the Node.js REPL will persist history between <code>node</code> REPL sessions
by saving inputs to a <code>.node_repl_history</code> file located in the user's home
directory. This can be disabled by setting the environment variable
<code>NODE_REPL_HISTORY=''</code>.</p>
<h4>Using the Node.js REPL with advanced line-editors<span><a class="mark" href="#all_repl_using-the-nodejs-repl-with-advanced-line-editors" id="all_repl_using-the-nodejs-repl-with-advanced-line-editors">#</a></span><a aria-hidden="true" class="legacy" id="repl_using_the_node_js_repl_with_advanced_line_editors"></a></h4>
<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-bash"><span class="hljs-built_in">alias</span> node=<span class="hljs-string">"env NODE_NO_READLINE=1 rlwrap node"</span></code> <button class="copy-button">copy</button></pre>
<h4>Starting multiple REPL instances against a single running instance<span><a class="mark" href="#all_repl_starting-multiple-repl-instances-against-a-single-running-instance" id="all_repl_starting-multiple-repl-instances-against-a-single-running-instance">#</a></span><a aria-hidden="true" class="legacy" id="repl_starting_multiple_repl_instances_against_a_single_running_instance"></a></h4>
<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"><span class="hljs-keyword">const</span> net = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:net'</span>);
<span class="hljs-keyword">const</span> repl = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:repl'</span>);
<span class="hljs-keyword">let</span> connections = <span class="hljs-number">0</span>;

repl.<span class="hljs-title function_">start</span>({
  <span class="hljs-attr">prompt</span>: <span class="hljs-string">'Node.js via stdin> '</span>,
  <span class="hljs-attr">input</span>: process.<span class="hljs-property">stdin</span>,
  <span class="hljs-attr">output</span>: process.<span class="hljs-property">stdout</span>,
});

net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">socket</span>) =></span> {
  connections += <span class="hljs-number">1</span>;
  repl.<span class="hljs-title function_">start</span>({
    <span class="hljs-attr">prompt</span>: <span class="hljs-string">'Node.js via Unix socket> '</span>,
    <span class="hljs-attr">input</span>: socket,
    <span class="hljs-attr">output</span>: socket,
  }).<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">() =></span> {
    socket.<span class="hljs-title function_">end</span>();
  });
}).<span class="hljs-title function_">listen</span>(<span class="hljs-string">'/tmp/node-repl-sock'</span>);

net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">socket</span>) =></span> {
  connections += <span class="hljs-number">1</span>;
  repl.<span class="hljs-title function_">start</span>({
    <span class="hljs-attr">prompt</span>: <span class="hljs-string">'Node.js via TCP socket> '</span>,
    <span class="hljs-attr">input</span>: socket,
    <span class="hljs-attr">output</span>: socket,
  }).<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">() =></span> {
    socket.<span class="hljs-title function_">end</span>();
  });
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">5001</span>);</code> <button class="copy-button">copy</button></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"><code>curl(1)</code></a>, see:
<a href="https://gist.github.com/TooTallNate/2053342">https://gist.github.com/TooTallNate/2053342</a>.</p>
<p>This example is intended purely for educational purposes to demonstrate how
Node.js REPLs can be started using different I/O streams.
It should <strong>not</strong> be used in production environments or any context where security
is a concern without additional protective measures.
If you need to implement REPLs in a real-world application, consider alternative
approaches that mitigate these risks, such as using secure input mechanisms and
avoiding open network interfaces.</p></section>
        </section>
<section><h2>Diagnostic report<span><a class="mark" href="#all_report_diagnostic-report" id="all_report_diagnostic-report">#</a></span><a aria-hidden="true" class="legacy" id="report_diagnostic_report"></a></h2>


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

<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.13.0</td>
<td><p>Added <code>--report-exclude-network</code> option for excluding networking operations that can slow down report generation in some cases.</p></td></tr>
</tbody></table>
</details>
</div>
<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"><span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"header"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"reportVersion"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">3</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"event"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"exception"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"trigger"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"Exception"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"filename"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"report.20181221.005011.8974.0.001.json"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"dumpEventTime"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"2018-12-21T00:50:11Z"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"dumpEventTimeStamp"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"1545371411331"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"processId"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">8974</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"cwd"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/home/nodeuser/project/node"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"commandLine"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
      <span class="hljs-string">"/home/nodeuser/project/node/out/Release/node"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-string">"--report-uncaught-exception"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-string">"/home/nodeuser/project/node/test/report/test-exception.js"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-string">"child"</span>
    <span class="hljs-punctuation">]</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"nodejsVersion"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"v12.0.0-pre"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"glibcVersionRuntime"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"2.17"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"glibcVersionCompiler"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"2.17"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"wordSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"64 bit"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"arch"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"x64"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"platform"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"linux"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"componentVersions"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"node"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"12.0.0-pre"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"v8"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"7.1.302.28-node.5"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"uv"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"1.24.1"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"zlib"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"1.2.11"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"ares"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"1.15.0"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"modules"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"68"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"nghttp2"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"1.34.0"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"napi"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"3"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"llhttp"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"1.0.1"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"openssl"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"1.1.0j"</span>
    <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"release"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"node"</span>
    <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"osName"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"Linux"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"osRelease"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"3.10.0-862.el7.x86_64"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"osVersion"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"#1 SMP Wed Mar 21 18:14:51 EDT 2018"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"osMachine"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"x86_64"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"cpus"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
      <span class="hljs-punctuation">{</span>
        <span class="hljs-attr">"model"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz"</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"speed"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">2700</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"user"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">88902660</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"nice"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"sys"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">50902570</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"idle"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">241732220</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"irq"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span>
      <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
      <span class="hljs-punctuation">{</span>
        <span class="hljs-attr">"model"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz"</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"speed"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">2700</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"user"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">88902660</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"nice"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"sys"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">50902570</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"idle"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">241732220</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"irq"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span>
      <span class="hljs-punctuation">}</span>
    <span class="hljs-punctuation">]</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"networkInterfaces"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
      <span class="hljs-punctuation">{</span>
        <span class="hljs-attr">"name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"en0"</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"internal"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">false</span></span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"mac"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"13:10:de:ad:be:ef"</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"address"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"10.0.0.37"</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"netmask"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"255.255.255.0"</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"family"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"IPv4"</span>
      <span class="hljs-punctuation">}</span>
    <span class="hljs-punctuation">]</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"host"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"test_machine"</span>
  <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"javascriptStack"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"message"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"Error: *** test-exception.js: throwing uncaught Error"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"stack"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
      <span class="hljs-string">"at myException (/home/nodeuser/project/node/test/report/test-exception.js:9:11)"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-string">"at Object.&#x3C;anonymous> (/home/nodeuser/project/node/test/report/test-exception.js:12:3)"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-string">"at Module._compile (internal/modules/cjs/loader.js:718:30)"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-string">"at Object.Module._extensions..js (internal/modules/cjs/loader.js:729:10)"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-string">"at Module.load (internal/modules/cjs/loader.js:617:32)"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-string">"at tryModuleLoad (internal/modules/cjs/loader.js:560:12)"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-string">"at Function.Module._load (internal/modules/cjs/loader.js:552:3)"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-string">"at Function.Module.runMain (internal/modules/cjs/loader.js:771:12)"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-string">"at executeUserCode (internal/bootstrap/node.js:332:15)"</span>
    <span class="hljs-punctuation">]</span>
  <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"nativeStack"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
    <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"pc"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"0x000055b57f07a9ef"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"symbol"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"report::GetNodeReport(v8::Isolate*, node::Environment*, char const*, char const*, v8::Local&#x3C;v8::String>, std::ostream&#x26;) [./node]"</span>
    <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
    <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"pc"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"0x000055b57f07cf03"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"symbol"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"report::GetReport(v8::FunctionCallbackInfo&#x3C;v8::Value> const&#x26;) [./node]"</span>
    <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
    <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"pc"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"0x000055b57f1bccfd"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"symbol"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">" [./node]"</span>
    <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
    <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"pc"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"0x000055b57f1be048"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"symbol"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"v8::internal::Builtin_HandleApiCall(int, v8::internal::Object**, v8::internal::Isolate*) [./node]"</span>
    <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
    <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"pc"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"0x000055b57feeda0e"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"symbol"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">" [./node]"</span>
    <span class="hljs-punctuation">}</span>
  <span class="hljs-punctuation">]</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"javascriptHeap"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"totalMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">5660672</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"executableMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">524288</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"totalCommittedMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">5488640</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"availableMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">4341379928</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"totalGlobalHandlesMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">8192</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"usedGlobalHandlesMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">3136</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"usedMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">4816432</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"memoryLimit"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">4345298944</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"mallocedMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">254128</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"externalMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">315644</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"peakMallocedMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">98752</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"nativeContextCount"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"detachedContextCount"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"doesZapGarbage"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"heapSpaces"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"read_only_space"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
        <span class="hljs-attr">"memorySize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">524288</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"committedMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">39208</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"capacity"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">515584</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"used"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">30504</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"available"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">485080</span>
      <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"new_space"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
        <span class="hljs-attr">"memorySize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">2097152</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"committedMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">2019312</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"capacity"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1031168</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"used"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">985496</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"available"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">45672</span>
      <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"old_space"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
        <span class="hljs-attr">"memorySize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">2273280</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"committedMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1769008</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"capacity"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1974640</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"used"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1725488</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"available"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">249152</span>
      <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"code_space"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
        <span class="hljs-attr">"memorySize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">696320</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"committedMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">184896</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"capacity"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">152128</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"used"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">152128</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"available"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span>
      <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"map_space"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
        <span class="hljs-attr">"memorySize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">536576</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"committedMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">344928</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"capacity"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">327520</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"used"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">327520</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"available"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span>
      <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"large_object_space"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
        <span class="hljs-attr">"memorySize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"committedMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"capacity"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1520590336</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"used"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"available"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1520590336</span>
      <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"new_large_object_space"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
        <span class="hljs-attr">"memorySize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"committedMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"capacity"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"used"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"available"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span>
      <span class="hljs-punctuation">}</span>
    <span class="hljs-punctuation">}</span>
  <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"resourceUsage"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"rss"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"35766272"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"free_memory"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"1598337024"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"total_memory"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"17179869184"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"available_memory"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"1598337024"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"maxRss"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"36624662528"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"constrained_memory"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"36624662528"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"userCpuSeconds"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0.040072</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"kernelCpuSeconds"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0.016029</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"cpuConsumptionPercent"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">5.6101</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"userCpuConsumptionPercent"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">4.0072</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"kernelCpuConsumptionPercent"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1.6029</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"pageFaults"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"IORequired"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"IONotRequired"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">4610</span>
    <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"fsActivity"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"reads"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"writes"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span>
    <span class="hljs-punctuation">}</span>
  <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"uvthreadResourceUsage"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"userCpuSeconds"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0.039843</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"kernelCpuSeconds"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0.015937</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"cpuConsumptionPercent"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">5.578</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"userCpuConsumptionPercent"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">3.9843</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"kernelCpuConsumptionPercent"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1.5937</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"fsActivity"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"reads"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"writes"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span>
    <span class="hljs-punctuation">}</span>
  <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"libuv"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
    <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"type"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"async"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"is_active"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"is_referenced"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">false</span></span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"address"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"0x0000000102910900"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"details"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">""</span>
    <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
    <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"type"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"timer"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"is_active"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">false</span></span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"is_referenced"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">false</span></span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"address"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"0x00007fff5fbfeab0"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"repeat"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"firesInMsFromNow"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">94403548320796</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"expired"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span>
    <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
    <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"type"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"check"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"is_active"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"is_referenced"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">false</span></span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"address"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"0x00007fff5fbfeb48"</span>
    <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
    <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"type"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"idle"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"is_active"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">false</span></span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"is_referenced"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"address"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"0x00007fff5fbfebc0"</span>
    <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
    <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"type"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"prepare"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"is_active"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">false</span></span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"is_referenced"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">false</span></span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"address"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"0x00007fff5fbfec38"</span>
    <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
    <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"type"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"check"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"is_active"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">false</span></span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"is_referenced"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">false</span></span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"address"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"0x00007fff5fbfecb0"</span>
    <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
    <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"type"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"async"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"is_active"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"is_referenced"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">false</span></span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"address"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"0x000000010188f2e0"</span>
    <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
    <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"type"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"tty"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"is_active"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">false</span></span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"is_referenced"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"address"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"0x000055b581db0e18"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"width"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">204</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"height"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">55</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"fd"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">17</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"writeQueueSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"readable"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"writable"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span>
    <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
    <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"type"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"signal"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"is_active"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"is_referenced"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">false</span></span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"address"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"0x000055b581d80010"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"signum"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">28</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"signal"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"SIGWINCH"</span>
    <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
    <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"type"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"tty"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"is_active"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"is_referenced"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"address"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"0x000055b581df59f8"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"width"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">204</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"height"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">55</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"fd"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">19</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"writeQueueSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"readable"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"writable"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span>
    <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
    <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"type"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"loop"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"is_active"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"address"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"0x000055fc7b2cb180"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"loopIdleTimeSeconds"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">22644.8</span>
    <span class="hljs-punctuation">}</span>
  <span class="hljs-punctuation">]</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"workers"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span><span class="hljs-punctuation">]</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"environmentVariables"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"REMOTEHOST"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"REMOVED"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"MANPATH"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/opt/rh/devtoolset-3/root/usr/share/man:"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"XDG_SESSION_ID"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"66126"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"HOSTNAME"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"test_machine"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"HOST"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"test_machine"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"TERM"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"xterm-256color"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"SHELL"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/bin/csh"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"SSH_CLIENT"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"REMOVED"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"PERL5LIB"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/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"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"OLDPWD"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/home/nodeuser/project/node/src"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"JAVACONFDIRS"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/opt/rh/devtoolset-3/root/etc/java:/etc/java"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"SSH_TTY"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/dev/pts/0"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"PCP_DIR"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/opt/rh/devtoolset-3/root"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"GROUP"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"normaluser"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"USER"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"nodeuser"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"LD_LIBRARY_PATH"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/opt/rh/devtoolset-3/root/usr/lib64:/opt/rh/devtoolset-3/root/usr/lib"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"HOSTTYPE"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"x86_64-linux"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"XDG_CONFIG_DIRS"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/opt/rh/devtoolset-3/root/etc/xdg:/etc/xdg"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"MAIL"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/var/spool/mail/nodeuser"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"PATH"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/home/nodeuser/project/node:/opt/rh/devtoolset-3/root/usr/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"PWD"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/home/nodeuser/project/node"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"LANG"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"en_US.UTF-8"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"PS1"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"\\u@\\h : \\[\\e[31m\\]\\w\\[\\e[m\\] >  "</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"SHLVL"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"2"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"HOME"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/home/nodeuser"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"OSTYPE"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"linux"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"VENDOR"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"unknown"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"PYTHONPATH"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/opt/rh/devtoolset-3/root/usr/lib64/python2.7/site-packages:/opt/rh/devtoolset-3/root/usr/lib/python2.7/site-packages"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"MACHTYPE"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"x86_64"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"LOGNAME"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"nodeuser"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"XDG_DATA_DIRS"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/opt/rh/devtoolset-3/root/usr/share:/usr/local/share:/usr/share"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"LESSOPEN"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"||/usr/bin/lesspipe.sh %s"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"INFOPATH"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/opt/rh/devtoolset-3/root/usr/share/info"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"XDG_RUNTIME_DIR"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/run/user/50141"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"_"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"./node"</span>
  <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"userLimits"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"core_file_size_blocks"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"soft"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">""</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"hard"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"unlimited"</span>
    <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"data_seg_size_kbytes"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"soft"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"unlimited"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"hard"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"unlimited"</span>
    <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"file_size_blocks"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"soft"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"unlimited"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"hard"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"unlimited"</span>
    <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"max_locked_memory_bytes"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"soft"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"unlimited"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"hard"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">65536</span>
    <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"max_memory_size_kbytes"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"soft"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"unlimited"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"hard"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"unlimited"</span>
    <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"open_files"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"soft"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"unlimited"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"hard"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">4096</span>
    <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"stack_size_bytes"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"soft"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"unlimited"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"hard"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"unlimited"</span>
    <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"cpu_time_seconds"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"soft"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"unlimited"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"hard"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"unlimited"</span>
    <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"max_user_processes"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"soft"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"unlimited"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"hard"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">4127290</span>
    <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"virtual_memory_kbytes"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"soft"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"unlimited"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"hard"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"unlimited"</span>
    <span class="hljs-punctuation">}</span>
  <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"sharedObjects"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
    <span class="hljs-string">"/lib64/libdl.so.2"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-string">"/lib64/librt.so.1"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-string">"/lib64/libstdc++.so.6"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-string">"/lib64/libm.so.6"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-string">"/lib64/libgcc_s.so.1"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-string">"/lib64/libpthread.so.0"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-string">"/lib64/libc.so.6"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-string">"/lib64/ld-linux-x86-64.so.2"</span>
  <span class="hljs-punctuation">]</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<section><h3>Usage<span><a class="mark" href="#all_report_usage" id="all_report_usage">#</a></span><a aria-hidden="true" class="legacy" id="report_usage"></a></h3>
<pre><code class="language-bash">node --report-uncaught-exception --report-on-signal \
--report-on-fatalerror app.js</code> <button class="copy-button">copy</button></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>
<li>
<p><code>--report-exclude-network</code> Exclude <code>header.networkInterfaces</code> from the
diagnostic report. By default this is not set and the network interfaces
are included.</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.<span class="hljs-property">report</span>.<span class="hljs-title function_">writeReport</span>();</code> <button class="copy-button">copy</button></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.<span class="hljs-property">report</span>.<span class="hljs-title function_">writeReport</span>(<span class="hljs-string">'./foo.json'</span>);</code> <button class="copy-button">copy</button></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"><span class="hljs-keyword">try</span> {
  process.<span class="hljs-title function_">chdir</span>(<span class="hljs-string">'/non-existent-path'</span>);
} <span class="hljs-keyword">catch</span> (err) {
  process.<span class="hljs-property">report</span>.<span class="hljs-title function_">writeReport</span>(err);
}
<span class="hljs-comment">// Any other code</span></code> <button class="copy-button">copy</button></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"><span class="hljs-keyword">try</span> {
  process.<span class="hljs-title function_">chdir</span>(<span class="hljs-string">'/non-existent-path'</span>);
} <span class="hljs-keyword">catch</span> (err) {
  process.<span class="hljs-property">report</span>.<span class="hljs-title function_">writeReport</span>(filename, err);
}
<span class="hljs-comment">// Any other code</span></code> <button class="copy-button">copy</button></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"><span class="hljs-keyword">const</span> report = process.<span class="hljs-property">report</span>.<span class="hljs-title function_">getReport</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-keyword">typeof</span> report === <span class="hljs-string">'object'</span>); <span class="hljs-comment">// true</span>

<span class="hljs-comment">// Similar to process.report.writeReport() output</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(report, <span class="hljs-literal">null</span>, <span class="hljs-number">2</span>));</code> <button class="copy-button">copy</button></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"><span class="hljs-keyword">const</span> report = process.<span class="hljs-property">report</span>.<span class="hljs-title function_">getReport</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'custom error'</span>));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-keyword">typeof</span> report === <span class="hljs-string">'object'</span>); <span class="hljs-comment">// true</span></code> <button class="copy-button">copy</button></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"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node</span>
<span class="hljs-meta prompt_">> </span><span class="language-bash">process.report.writeReport();</span>
Writing Node.js report to file: report.20181126.091102.8480.0.001.json
Node.js report completed
<span class="hljs-meta prompt_">></span></code> <button class="copy-button">copy</button></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>
<p>Diagnostic report has an associated single-digit version number (<code>report.header.reportVersion</code>),
uniquely representing the report format. The version number is bumped
when new key is added or removed, or the data type of a value is changed.
Report version definitions are consistent across LTS releases.</p>
</section><section><h3>Configuration<span><a class="mark" href="#all_report_configuration" id="all_report_configuration">#</a></span><a aria-hidden="true" class="legacy" id="report_configuration"></a></h3>
<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 file system directory where the report will be
written. URLs are not supported. Defaults to the current working directory of
the Node.js process.</p>
<p><code>excludeNetwork</code> excludes <code>header.networkInterfaces</code> from the diagnostic report.</p>
<pre><code class="language-js"><span class="hljs-comment">// Trigger report only on uncaught exceptions.</span>
process.<span class="hljs-property">report</span>.<span class="hljs-property">reportOnFatalError</span> = <span class="hljs-literal">false</span>;
process.<span class="hljs-property">report</span>.<span class="hljs-property">reportOnSignal</span> = <span class="hljs-literal">false</span>;
process.<span class="hljs-property">report</span>.<span class="hljs-property">reportOnUncaughtException</span> = <span class="hljs-literal">true</span>;

<span class="hljs-comment">// Trigger report for both internal errors as well as external signal.</span>
process.<span class="hljs-property">report</span>.<span class="hljs-property">reportOnFatalError</span> = <span class="hljs-literal">true</span>;
process.<span class="hljs-property">report</span>.<span class="hljs-property">reportOnSignal</span> = <span class="hljs-literal">true</span>;
process.<span class="hljs-property">report</span>.<span class="hljs-property">reportOnUncaughtException</span> = <span class="hljs-literal">false</span>;

<span class="hljs-comment">// Change the default signal to 'SIGQUIT' and enable it.</span>
process.<span class="hljs-property">report</span>.<span class="hljs-property">reportOnFatalError</span> = <span class="hljs-literal">false</span>;
process.<span class="hljs-property">report</span>.<span class="hljs-property">reportOnUncaughtException</span> = <span class="hljs-literal">false</span>;
process.<span class="hljs-property">report</span>.<span class="hljs-property">reportOnSignal</span> = <span class="hljs-literal">true</span>;
process.<span class="hljs-property">report</span>.<span class="hljs-property">signal</span> = <span class="hljs-string">'SIGQUIT'</span>;

<span class="hljs-comment">// Disable network interfaces reporting</span>
process.<span class="hljs-property">report</span>.<span class="hljs-property">excludeNetwork</span> = <span class="hljs-literal">true</span>;</code> <button class="copy-button">copy</button></pre>
<p>Configuration on module initialization is also available via
environment variables:</p>
<pre><code class="language-bash">NODE_OPTIONS=<span class="hljs-string">"--report-uncaught-exception \
  --report-on-fatalerror --report-on-signal \
  --report-signal=SIGUSR2  --report-filename=./report.json \
  --report-directory=/home/nodeuser"</span></code> <button class="copy-button">copy</button></pre>
<p>Specific API documentation can be found under
<a href="process.html"><code>process API documentation</code></a> section.</p>
</section><section><h3>Interaction with workers<span><a class="mark" href="#all_report_interaction-with-workers" id="all_report_interaction-with-workers">#</a></span><a aria-hidden="true" class="legacy" id="report_interaction_with_workers"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.9.0, 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></section>
        </section>
<section><h2>Single executable applications<span><a class="mark" href="#all_single-executable-applications_single-executable-applications" id="all_single-executable-applications_single-executable-applications">#</a></span><a aria-hidden="true" class="legacy" id="single_executable_applications_single_executable_applications"></a></h2>

<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.6.0</td>
<td><p>Added support for "useSnapshot".</p></td></tr>
<tr><td>v20.6.0</td>
<td><p>Added support for "useCodeCache".</p></td></tr>
<tr><td>v19.7.0, v18.16.0</td>
<td><p><span>Added in: v19.7.0, v18.16.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active development</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/src/node_sea.cc">src/node_sea.cc</a></p>
<p>This feature allows the distribution of a Node.js application conveniently to a
system that does not have Node.js installed.</p>
<p>Node.js supports the creation of <a href="https://github.com/nodejs/single-executable">single executable applications</a> by allowing
the injection of a blob prepared by Node.js, which can contain a bundled script,
into the <code>node</code> binary. During start up, the program checks if anything has been
injected. If the blob is found, it executes the script in the blob. Otherwise
Node.js operates as it normally does.</p>
<p>The single executable application feature currently only supports running a
single embedded script using the <a href="#all_modules_modules-commonjs-modules">CommonJS</a> module system.</p>
<p>Users can create a single executable application from their bundled script
with the <code>node</code> binary itself and any tool which can inject resources into the
binary.</p>
<p>Here are the steps for creating a single executable application using one such
tool, <a href="https://github.com/nodejs/postject">postject</a>:</p>
<ol>
<li>
<p>Create a JavaScript file:</p>
<pre><code class="language-bash"><span class="hljs-built_in">echo</span> <span class="hljs-string">'console.log(`Hello, ${process.argv[2]}!`);'</span> > hello.js</code> <button class="copy-button">copy</button></pre>
</li>
<li>
<p>Create a configuration file building a blob that can be injected into the
single executable application (see
<a href="#all_single-executable-applications_generating-single-executable-preparation-blobs">Generating single executable preparation blobs</a> for details):</p>
<pre><code class="language-bash"><span class="hljs-built_in">echo</span> <span class="hljs-string">'{ "main": "hello.js", "output": "sea-prep.blob" }'</span> > sea-config.json</code> <button class="copy-button">copy</button></pre>
</li>
<li>
<p>Generate the blob to be injected:</p>
<pre><code class="language-bash">node --experimental-sea-config sea-config.json</code> <button class="copy-button">copy</button></pre>
</li>
<li>
<p>Create a copy of the <code>node</code> executable and name it according to your needs:</p>
<ul>
<li>On systems other than Windows:</li>
</ul>
<pre><code class="language-bash"><span class="hljs-built_in">cp</span> $(<span class="hljs-built_in">command</span> -v node) hello</code> <button class="copy-button">copy</button></pre>
<ul>
<li>On Windows:</li>
</ul>
<pre><code class="language-text">node -e "require('fs').copyFileSync(process.execPath, 'hello.exe')"</code> <button class="copy-button">copy</button></pre>
<p>The <code>.exe</code> extension is necessary.</p>
</li>
<li>
<p>Remove the signature of the binary (macOS and Windows only):</p>
<ul>
<li>On macOS:</li>
</ul>
<pre><code class="language-bash">codesign --remove-signature hello</code> <button class="copy-button">copy</button></pre>
<ul>
<li>On Windows (optional):</li>
</ul>
<p><a href="https://learn.microsoft.com/en-us/windows/win32/seccrypto/signtool">signtool</a> can be used from the installed <a href="https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/">Windows SDK</a>. If this step is
skipped, ignore any signature-related warning from postject.</p>
<pre><code class="language-powershell">signtool remove /s hello.exe</code> <button class="copy-button">copy</button></pre>
</li>
<li>
<p>Inject the blob into the copied binary by running <code>postject</code> with
the following options:</p>
<ul>
<li><code>hello</code> / <code>hello.exe</code> - The name of the copy of the <code>node</code> executable
created in step 4.</li>
<li><code>NODE_SEA_BLOB</code> - The name of the resource / note / section in the binary
where the contents of the blob will be stored.</li>
<li><code>sea-prep.blob</code> - The name of the blob created in step 1.</li>
<li><code>--sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2</code> - The
<a href="https://www.electronjs.org/docs/latest/tutorial/fuses">fuse</a> used by the Node.js project to detect if a file has been injected.</li>
<li><code>--macho-segment-name NODE_SEA</code> (only needed on macOS) - The name of the
segment in the binary where the contents of the blob will be
stored.</li>
</ul>
<p>To summarize, here is the required command for each platform:</p>
<ul>
<li>
<p>On Linux:</p>
<pre><code class="language-bash">npx postject hello NODE_SEA_BLOB sea-prep.blob \
    --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2</code> <button class="copy-button">copy</button></pre>
</li>
<li>
<p>On Windows - PowerShell:</p>
<pre><code class="language-powershell">npx postject hello.exe NODE_SEA_BLOB sea<span class="hljs-literal">-prep</span>.blob `
    <span class="hljs-literal">--sentinel-fuse</span> NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2</code> <button class="copy-button">copy</button></pre>
</li>
<li>
<p>On Windows - Command Prompt:</p>
<pre><code class="language-text">npx postject hello.exe NODE_SEA_BLOB sea-prep.blob ^
    --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2</code> <button class="copy-button">copy</button></pre>
</li>
<li>
<p>On macOS:</p>
<pre><code class="language-bash">npx postject hello NODE_SEA_BLOB sea-prep.blob \
    --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 \
    --macho-segment-name NODE_SEA</code> <button class="copy-button">copy</button></pre>
</li>
</ul>
</li>
<li>
<p>Sign the binary (macOS and Windows only):</p>
<ul>
<li>On macOS:</li>
</ul>
<pre><code class="language-bash">codesign --sign - hello</code> <button class="copy-button">copy</button></pre>
<ul>
<li>On Windows (optional):</li>
</ul>
<p>A certificate needs to be present for this to work. However, the unsigned
binary would still be runnable.</p>
<pre><code class="language-powershell">signtool sign /fd SHA256 hello.exe</code> <button class="copy-button">copy</button></pre>
</li>
<li>
<p>Run the binary:</p>
<ul>
<li>On systems other than Windows</li>
</ul>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">./hello world</span>
Hello, world!</code> <button class="copy-button">copy</button></pre>
<ul>
<li>On Windows</li>
</ul>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">.\hello.exe world</span>
Hello, world!</code> <button class="copy-button">copy</button></pre>
</li>
</ol>
<section><h3>Generating single executable preparation blobs<span><a class="mark" href="#all_single-executable-applications_generating-single-executable-preparation-blobs" id="all_single-executable-applications_generating-single-executable-preparation-blobs">#</a></span><a aria-hidden="true" class="legacy" id="single_executable_applications_generating_single_executable_preparation_blobs"></a></h3>
<p>Single executable preparation blobs that are injected into the application can
be generated using the <code>--experimental-sea-config</code> flag of the Node.js binary
that will be used to build the single executable. It takes a path to a
configuration file in JSON format. If the path passed to it isn't absolute,
Node.js will use the path relative to the current working directory.</p>
<p>The configuration currently reads the following top-level fields:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"main"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/path/to/bundled/script.js"</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"output"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/path/to/write/the/generated/blob.blob"</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"disableExperimentalSEAWarning"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span> <span class="hljs-comment">// Default: false</span>
  <span class="hljs-attr">"useSnapshot"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">false</span></span><span class="hljs-punctuation">,</span>  <span class="hljs-comment">// Default: false</span>
  <span class="hljs-attr">"useCodeCache"</span><span class="hljs-punctuation">:</span> <span class="hljs-literal"><span class="hljs-keyword">true</span></span><span class="hljs-punctuation">,</span> <span class="hljs-comment">// Default: false</span>
  <span class="hljs-attr">"assets"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>  <span class="hljs-comment">// Optional</span>
    <span class="hljs-attr">"a.dat"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/path/to/a.dat"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"b.txt"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/path/to/b.txt"</span>
  <span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>If the paths are not absolute, Node.js will use the path relative to the
current working directory. The version of the Node.js binary used to produce
the blob must be the same as the one to which the blob will be injected.</p>
<p>Note: When generating cross-platform SEAs (e.g., generating a SEA
for <code>linux-x64</code> on <code>darwin-arm64</code>), <code>useCodeCache</code> and <code>useSnapshot</code>
must be set to false to avoid generating incompatible executables.
Since code cache and snapshots can only be loaded on the same platform
where they are compiled, the generated executable might crash on startup when
trying to load code cache or snapshots built on a different platform.</p>
<h4>Assets<span><a class="mark" href="#all_single-executable-applications_assets" id="all_single-executable-applications_assets">#</a></span><a aria-hidden="true" class="legacy" id="single_executable_applications_assets"></a></h4>
<p>Users can include assets by adding a key-path dictionary to the configuration
as the <code>assets</code> field. At build time, Node.js would read the assets from the
specified paths and bundle them into the preparation blob. In the generated
executable, users can retrieve the assets using the <a href="#all_single-executable-applications_seagetassetkey-encoding"><code>sea.getAsset()</code></a> and
<a href="#all_single-executable-applications_seagetassetasblobkey-options"><code>sea.getAssetAsBlob()</code></a> APIs.</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"main"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/path/to/bundled/script.js"</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"output"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/path/to/write/the/generated/blob.blob"</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"assets"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"a.jpg"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/path/to/a.jpg"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"b.txt"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"/path/to/b.txt"</span>
  <span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>The single-executable application can access the assets as follows:</p>
<pre><code class="language-js cjs"><span class="hljs-keyword">const</span> { getAsset, getAssetAsBlob, getRawAsset } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:sea'</span>);
<span class="hljs-comment">// Returns a copy of the data in an ArrayBuffer.</span>
<span class="hljs-keyword">const</span> image = <span class="hljs-title function_">getAsset</span>(<span class="hljs-string">'a.jpg'</span>);
<span class="hljs-comment">// Returns a string decoded from the asset as UTF8.</span>
<span class="hljs-keyword">const</span> text = <span class="hljs-title function_">getAsset</span>(<span class="hljs-string">'b.txt'</span>, <span class="hljs-string">'utf8'</span>);
<span class="hljs-comment">// Returns a Blob containing the asset.</span>
<span class="hljs-keyword">const</span> blob = <span class="hljs-title function_">getAssetAsBlob</span>(<span class="hljs-string">'a.jpg'</span>);
<span class="hljs-comment">// Returns an ArrayBuffer containing the raw asset without copying.</span>
<span class="hljs-keyword">const</span> raw = <span class="hljs-title function_">getRawAsset</span>(<span class="hljs-string">'a.jpg'</span>);</code> <button class="copy-button">copy</button></pre>
<p>See documentation of the <a href="#all_single-executable-applications_seagetassetkey-encoding"><code>sea.getAsset()</code></a>, <a href="#all_single-executable-applications_seagetassetasblobkey-options"><code>sea.getAssetAsBlob()</code></a> and <a href="#all_single-executable-applications_seagetrawassetkey"><code>sea.getRawAsset()</code></a>
APIs for more information.</p>
<h4>Startup snapshot support<span><a class="mark" href="#all_single-executable-applications_startup-snapshot-support" id="all_single-executable-applications_startup-snapshot-support">#</a></span><a aria-hidden="true" class="legacy" id="single_executable_applications_startup_snapshot_support"></a></h4>
<p>The <code>useSnapshot</code> field can be used to enable startup snapshot support. In this
case the <code>main</code> script would not be when the final executable is launched.
Instead, it would be run when the single executable application preparation
blob is generated on the building machine. The generated preparation blob would
then include a snapshot capturing the states initialized by the <code>main</code> script.
The final executable with the preparation blob injected would deserialize
the snapshot at run time.</p>
<p>When <code>useSnapshot</code> is true, the main script must invoke the
<a href="#all_v8_v8startupsnapshotsetdeserializemainfunctioncallback-data"><code>v8.startupSnapshot.setDeserializeMainFunction()</code></a> API to configure code
that needs to be run when the final executable is launched by the users.</p>
<p>The typical pattern for an application to use snapshot in a single executable
application is:</p>
<ol>
<li>At build time, on the building machine, the main script is run to
initialize the heap to a state that's ready to take user input. The script
should also configure a main function with
<a href="#all_v8_v8startupsnapshotsetdeserializemainfunctioncallback-data"><code>v8.startupSnapshot.setDeserializeMainFunction()</code></a>. This function will be
compiled and serialized into the snapshot, but not invoked at build time.</li>
<li>At run time, the main function will be run on top of the deserialized heap
on the user machine to process user input and generate output.</li>
</ol>
<p>The general constraints of the startup snapshot scripts also apply to the main
script when it's used to build snapshot for the single executable application,
and the main script can use the <a href="#all_v8_startup-snapshot-api"><code>v8.startupSnapshot</code> API</a> to adapt to
these constraints. See
<a href="#all_cli_--build-snapshot">documentation about startup snapshot support in Node.js</a>.</p>
<h4>V8 code cache support<span><a class="mark" href="#all_single-executable-applications_v8-code-cache-support" id="all_single-executable-applications_v8-code-cache-support">#</a></span><a aria-hidden="true" class="legacy" id="single_executable_applications_v8_code_cache_support"></a></h4>
<p>When <code>useCodeCache</code> is set to <code>true</code> in the configuration, during the generation
of the single executable preparation blob, Node.js will compile the <code>main</code>
script to generate the V8 code cache. The generated code cache would be part of
the preparation blob and get injected into the final executable. When the single
executable application is launched, instead of compiling the <code>main</code> script from
scratch, Node.js would use the code cache to speed up the compilation, then
execute the script, which would improve the startup performance.</p>
<p><strong>Note:</strong> <code>import()</code> does not work when <code>useCodeCache</code> is <code>true</code>.</p>
</section><section><h3>In the injected main script<span><a class="mark" href="#all_single-executable-applications_in-the-injected-main-script" id="all_single-executable-applications_in-the-injected-main-script">#</a></span><a aria-hidden="true" class="legacy" id="single_executable_applications_in_the_injected_main_script"></a></h3>
<h4>Single-executable application API<span><a class="mark" href="#all_single-executable-applications_single-executable-application-api" id="all_single-executable-applications_single-executable-application-api">#</a></span><a aria-hidden="true" class="legacy" id="single_executable_applications_single_executable_application_api"></a></h4>
<p>The <code>node:sea</code> builtin allows interaction with the single-executable application
from the JavaScript main script embedded into the executable.</p>
<h5><code>sea.isSea()</code><span><a class="mark" href="#all_single-executable-applications_seaissea" id="all_single-executable-applications_seaissea">#</a></span><a aria-hidden="true" class="legacy" id="single_executable_applications_sea_issea"></a></h5>
<div class="api_metadata">
<span>Added in: v20.12.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> Whether this script is running inside a single-executable
application.</li>
</ul>
<h4><code>sea.getAsset(key[, encoding])</code><span><a class="mark" href="#all_single-executable-applications_seagetassetkey-encoding" id="all_single-executable-applications_seagetassetkey-encoding">#</a></span><a aria-hidden="true" class="legacy" id="single_executable_applications_sea_getasset_key_encoding"></a></h4>
<div class="api_metadata">
<span>Added in: v20.12.0</span>
</div>
<p>This method can be used to retrieve the assets configured to be bundled into the
single-executable application at build time.
An error is thrown when no matching asset can be found.</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> the key for the asset in the dictionary specified by the
<code>assets</code> field in the single-executable application configuration.</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, the asset will be decoded as
a string. Any encoding supported by the <code>TextDecoder</code> is accepted.
If unspecified, an <code>ArrayBuffer</code> containing a copy of the asset would be
returned instead.</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/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a></li>
</ul>
<h4><code>sea.getAssetAsBlob(key[, options])</code><span><a class="mark" href="#all_single-executable-applications_seagetassetasblobkey-options" id="all_single-executable-applications_seagetassetasblobkey-options">#</a></span><a aria-hidden="true" class="legacy" id="single_executable_applications_sea_getassetasblob_key_options"></a></h4>
<div class="api_metadata">
<span>Added in: v20.12.0</span>
</div>
<p>Similar to <a href="#all_single-executable-applications_seagetassetkey-encoding"><code>sea.getAsset()</code></a>, but returns the result in a <a href="https://developer.mozilla.org/en-US/docs/Web/API/Blob"><code>Blob</code></a>.
An error is thrown when no matching asset can be found.</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> the key for the asset in the dictionary specified by the
<code>assets</code> field in the single-executable application configuration.</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>
<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> An optional mime type for the blob.</li>
</ul>
</li>
<li>Returns: <a href="#all_buffer_class-blob" class="type">&#x3C;Blob></a></li>
</ul>
<h4><code>sea.getRawAsset(key)</code><span><a class="mark" href="#all_single-executable-applications_seagetrawassetkey" id="all_single-executable-applications_seagetrawassetkey">#</a></span><a aria-hidden="true" class="legacy" id="single_executable_applications_sea_getrawasset_key"></a></h4>
<div class="api_metadata">
<span>Added in: v20.12.0</span>
</div>
<p>This method can be used to retrieve the assets configured to be bundled into the
single-executable application at build time.
An error is thrown when no matching asset can be found.</p>
<p>Unlike <code>sea.getAsset()</code> or <code>sea.getAssetAsBlob()</code>, this method does not
return a copy. Instead, it returns the raw asset bundled inside the executable.</p>
<p>For now, users should avoid writing to the returned array buffer. If the
injected section is not marked as writable or not aligned properly,
writes to the returned array buffer is likely to result in a crash.</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> the key for the asset in the dictionary specified by the
<code>assets</code> field in the single-executable application configuration.</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/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a></li>
</ul>
<h4><code>require(id)</code> in the injected main script is not file based<span><a class="mark" href="#all_single-executable-applications_requireid-in-the-injected-main-script-is-not-file-based" id="all_single-executable-applications_requireid-in-the-injected-main-script-is-not-file-based">#</a></span><a aria-hidden="true" class="legacy" id="single_executable_applications_require_id_in_the_injected_main_script_is_not_file_based"></a></h4>
<p><code>require()</code> in the injected main script is not the same as the <a href="#all_modules_requireid"><code>require()</code></a>
available to modules that are not injected. It also does not have any of the
properties that non-injected <a href="#all_modules_requireid"><code>require()</code></a> has except <a href="#all_modules_accessing-the-main-module"><code>require.main</code></a>. It
can only be used to load built-in modules. Attempting to load a module that can
only be found in the file system will throw an error.</p>
<p>Instead of relying on a file based <code>require()</code>, users can bundle their
application into a standalone JavaScript file to inject into the executable.
This also ensures a more deterministic dependency graph.</p>
<p>However, if a file based <code>require()</code> is still needed, that can also be achieved:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { createRequire } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:module'</span>);
<span class="hljs-built_in">require</span> = <span class="hljs-title function_">createRequire</span>(__filename);</code> <button class="copy-button">copy</button></pre>
<h4><code>__filename</code> and <code>module.filename</code> in the injected main script<span><a class="mark" href="#all_single-executable-applications___filename-and-modulefilename-in-the-injected-main-script" id="all_single-executable-applications___filename-and-modulefilename-in-the-injected-main-script">#</a></span><a aria-hidden="true" class="legacy" id="single_executable_applications_filename_and_module_filename_in_the_injected_main_script"></a></h4>
<p>The values of <code>__filename</code> and <code>module.filename</code> in the injected main script
are equal to <a href="#all_process_processexecpath"><code>process.execPath</code></a>.</p>
<h4><code>__dirname</code> in the injected main script<span><a class="mark" href="#all_single-executable-applications___dirname-in-the-injected-main-script" id="all_single-executable-applications___dirname-in-the-injected-main-script">#</a></span><a aria-hidden="true" class="legacy" id="single_executable_applications_dirname_in_the_injected_main_script"></a></h4>
<p>The value of <code>__dirname</code> in the injected main script is equal to the directory
name of <a href="#all_process_processexecpath"><code>process.execPath</code></a>.</p>
</section><section><h3>Notes<span><a class="mark" href="#all_single-executable-applications_notes" id="all_single-executable-applications_notes">#</a></span><a aria-hidden="true" class="legacy" id="single_executable_applications_notes"></a></h3>
<h4>Single executable application creation process<span><a class="mark" href="#all_single-executable-applications_single-executable-application-creation-process" id="all_single-executable-applications_single-executable-application-creation-process">#</a></span><a aria-hidden="true" class="legacy" id="single_executable_applications_single_executable_application_creation_process"></a></h4>
<p>A tool aiming to create a single executable Node.js application must
inject the contents of the blob prepared with <code>--experimental-sea-config"</code>
into:</p>
<ul>
<li>a resource named <code>NODE_SEA_BLOB</code> if the <code>node</code> binary is a <a href="https://en.wikipedia.org/wiki/Portable_Executable">PE</a> file</li>
<li>a section named <code>NODE_SEA_BLOB</code> in the <code>NODE_SEA</code> segment if the <code>node</code> binary
is a <a href="https://en.wikipedia.org/wiki/Mach-O">Mach-O</a> file</li>
<li>a note named <code>NODE_SEA_BLOB</code> if the <code>node</code> binary is an <a href="https://en.wikipedia.org/wiki/Executable_and_Linkable_Format">ELF</a> file</li>
</ul>
<p>Search the binary for the
<code>NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2:0</code> <a href="https://www.electronjs.org/docs/latest/tutorial/fuses">fuse</a> string and flip the
last character to <code>1</code> to indicate that a resource has been injected.</p>
<h4>Platform support<span><a class="mark" href="#all_single-executable-applications_platform-support" id="all_single-executable-applications_platform-support">#</a></span><a aria-hidden="true" class="legacy" id="single_executable_applications_platform_support"></a></h4>
<p>Single-executable support is tested regularly on CI only on the following
platforms:</p>
<ul>
<li>Windows</li>
<li>macOS</li>
<li>Linux (all distributions <a href="https://github.com/nodejs/node/blob/main/BUILDING.md#platform-list">supported by Node.js</a> except Alpine and all
architectures <a href="https://github.com/nodejs/node/blob/main/BUILDING.md#platform-list">supported by Node.js</a> except s390x)</li>
</ul>
<p>This is due to a lack of better tools to generate single-executables that can be
used to test this feature on other platforms.</p>
<p>Suggestions for other resource injection tools/workflows are welcomed. Please
start a discussion at <a href="https://github.com/nodejs/single-executable/discussions">https://github.com/nodejs/single-executable/discussions</a>
to help us document them.</p></section>
        </section>
<section><h2>Stream<a class="srclink" href="https://github.com/nodejs/node/blob/7eebd17fa2c1e48e4534f3a69560388fab2f2c07/lib/stream.js#L55">[src]</a><span><a class="mark" href="#all_stream_stream" id="all_stream_stream">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream"></a></h2>

<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/stream.js">lib/stream.js</a></p>
<p>A stream is an abstract interface for working with streaming data in Node.js.
The <code>node: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="#all_http_class-httpincomingmessage">request to an HTTP server</a> and <a href="#all_process_processstdout"><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="#all_events_class-eventemitter"><code>EventEmitter</code></a>.</p>
<p>To access the <code>node:stream</code> module:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> stream = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);</code> <button class="copy-button">copy</button></pre>
<p>The <code>node:stream</code> module is useful for creating new types of stream instances.
It is usually not necessary to use the <code>node:stream</code> module to consume streams.</p>
<section><h3>Organization of this document<span><a class="mark" href="#all_stream_organization-of-this-document" id="all_stream_organization-of-this-document">#</a></span><a aria-hidden="true" class="legacy" id="stream_organization_of_this_document"></a></h3>
<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>
</section><section><h3>Types of streams<span><a class="mark" href="#all_stream_types-of-streams" id="all_stream_types-of-streams">#</a></span><a aria-hidden="true" class="legacy" id="stream_types_of_streams"></a></h3>
<p>There are four fundamental stream types within Node.js:</p>
<ul>
<li><a href="#all_stream_class-streamwritable"><code>Writable</code></a>: streams to which data can be written (for example,
<a href="#all_fs_fscreatewritestreampath-options"><code>fs.createWriteStream()</code></a>).</li>
<li><a href="#all_stream_class-streamreadable"><code>Readable</code></a>: streams from which data can be read (for example,
<a href="#all_fs_fscreatereadstreampath-options"><code>fs.createReadStream()</code></a>).</li>
<li><a href="#all_stream_class-streamduplex"><code>Duplex</code></a>: streams that are both <code>Readable</code> and <code>Writable</code> (for example,
<a href="#all_net_class-netsocket"><code>net.Socket</code></a>).</li>
<li><a href="#all_stream_class-streamtransform"><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="#all_zlib_zlibcreatedeflateoptions"><code>zlib.createDeflate()</code></a>).</li>
</ul>
<p>Additionally, this module includes the utility functions
<a href="#all_stream_streamduplexpairoptions"><code>stream.duplexPair()</code></a>,
<a href="#all_stream_streampipelinesource-transforms-destination-callback"><code>stream.pipeline()</code></a>,
<a href="#all_stream_streamfinishedstream-options-callback"><code>stream.finished()</code></a>
<a href="#all_stream_streamreadablefromiterable-options"><code>stream.Readable.from()</code></a>, and
<a href="#all_stream_streamaddabortsignalsignal-stream"><code>stream.addAbortSignal()</code></a>.</p>
<h4>Streams Promises API<span><a class="mark" href="#all_stream_streams-promises-api" id="all_stream_streams-promises-api">#</a></span><a aria-hidden="true" class="legacy" id="stream_streams_promises_api"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>The <code>stream/promises</code> API provides an alternative set of asynchronous utility
functions for streams that return <code>Promise</code> objects rather than using
callbacks. The API is accessible via <code>require('node:stream/promises')</code>
or <code>require('node:stream').promises</code>.</p>
<h4><code>stream.pipeline(source[, ...transforms], destination[, options])</code><span><a class="mark" href="#all_stream_streampipelinesource-transforms-destination-options" id="all_stream_streampipelinesource-transforms-destination-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_pipeline_source_transforms_destination_options"></a></h4>
<h4><code>stream.pipeline(streams[, options])</code><span><a class="mark" href="#all_stream_streampipelinestreams-options" id="all_stream_streampipelinestreams-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_pipeline_streams_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0, v17.2.0, v16.14.0</td>
<td><p>Add the <code>end</code> option, which can be set to <code>false</code> to prevent automatically closing the destination stream when the source ends.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p><span>Added in: v15.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>streams</code> <a href="#all_stream_stream" class="type">&#x3C;Stream[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol" class="type">&#x3C;Iterable[]></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type">&#x3C;AsyncIterable[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function[]></a></li>
<li><code>source</code> <a href="#all_stream_stream" class="type">&#x3C;Stream></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol" class="type">&#x3C;Iterable></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type">&#x3C;AsyncIterable></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type">&#x3C;AsyncIterable></a></li>
</ul>
</li>
<li><code>...transforms</code> <a href="#all_stream_stream" class="type">&#x3C;Stream></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<ul>
<li><code>source</code> <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type">&#x3C;AsyncIterable></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type">&#x3C;AsyncIterable></a></li>
</ul>
</li>
<li><code>destination</code> <a href="#all_stream_stream" class="type">&#x3C;Stream></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<ul>
<li><code>source</code> <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type">&#x3C;AsyncIterable></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type">&#x3C;AsyncIterable></a></li>
</ul>
</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> Pipeline options
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a></li>
<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 destination stream when the source stream ends.
Transform streams are always ended, even if this value is <code>false</code>.
<strong>Default:</strong> <code>true</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> Fulfills when the pipeline is complete.</li>
</ul>

<pre class="with-62-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { pipeline } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/promises'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> zlib = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:zlib'</span>);

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">run</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">await</span> <span class="hljs-title function_">pipeline</span>(
    fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'archive.tar'</span>),
    zlib.<span class="hljs-title function_">createGzip</span>(),
    fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'archive.tar.gz'</span>),
  );
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Pipeline succeeded.'</span>);
}

<span class="hljs-title function_">run</span>().<span class="hljs-title function_">catch</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">error</span>);</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { pipeline } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/promises'</span>;
<span class="hljs-keyword">import</span> { createReadStream, createWriteStream } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">import</span> { createGzip } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:zlib'</span>;

<span class="hljs-keyword">await</span> <span class="hljs-title function_">pipeline</span>(
  <span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'archive.tar'</span>),
  <span class="hljs-title function_">createGzip</span>(),
  <span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'archive.tar.gz'</span>),
);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Pipeline succeeded.'</span>);</code><button class="copy-button">copy</button></pre>
<p>To use an <code>AbortSignal</code>, pass it inside an options object, as the last argument.
When the signal is aborted, <code>destroy</code> will be called on the underlying pipeline,
with an <code>AbortError</code>.</p>

<pre class="with-62-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { pipeline } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/promises'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> zlib = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:zlib'</span>);

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">run</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">const</span> ac = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
  <span class="hljs-keyword">const</span> signal = ac.<span class="hljs-property">signal</span>;

  <span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></span> ac.<span class="hljs-title function_">abort</span>());
  <span class="hljs-keyword">await</span> <span class="hljs-title function_">pipeline</span>(
    fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'archive.tar'</span>),
    zlib.<span class="hljs-title function_">createGzip</span>(),
    fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'archive.tar.gz'</span>),
    { signal },
  );
}

<span class="hljs-title function_">run</span>().<span class="hljs-title function_">catch</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">error</span>); <span class="hljs-comment">// AbortError</span></code><code class="language-js mjs"><span class="hljs-keyword">import</span> { pipeline } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/promises'</span>;
<span class="hljs-keyword">import</span> { createReadStream, createWriteStream } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">import</span> { createGzip } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:zlib'</span>;

<span class="hljs-keyword">const</span> ac = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
<span class="hljs-keyword">const</span> { signal } = ac;
<span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></span> ac.<span class="hljs-title function_">abort</span>());
<span class="hljs-keyword">try</span> {
  <span class="hljs-keyword">await</span> <span class="hljs-title function_">pipeline</span>(
    <span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'archive.tar'</span>),
    <span class="hljs-title function_">createGzip</span>(),
    <span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'archive.tar.gz'</span>),
    { signal },
  );
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err); <span class="hljs-comment">// AbortError</span>
}</code><button class="copy-button">copy</button></pre>
<p>The <code>pipeline</code> API also supports async generators:</p>

<pre class="with-62-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { pipeline } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/promises'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">run</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">await</span> <span class="hljs-title function_">pipeline</span>(
    fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'lowercase.txt'</span>),
    <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>* (source, { signal }) {
      source.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>);  <span class="hljs-comment">// Work with strings rather than `Buffer`s.</span>
      <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> source) {
        <span class="hljs-keyword">yield</span> <span class="hljs-keyword">await</span> <span class="hljs-title function_">processChunk</span>(chunk, { signal });
      }
    },
    fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'uppercase.txt'</span>),
  );
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Pipeline succeeded.'</span>);
}

<span class="hljs-title function_">run</span>().<span class="hljs-title function_">catch</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">error</span>);</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { pipeline } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/promises'</span>;
<span class="hljs-keyword">import</span> { createReadStream, createWriteStream } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-keyword">await</span> <span class="hljs-title function_">pipeline</span>(
  <span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'lowercase.txt'</span>),
  <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>* (source, { signal }) {
    source.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>);  <span class="hljs-comment">// Work with strings rather than `Buffer`s.</span>
    <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> source) {
      <span class="hljs-keyword">yield</span> <span class="hljs-keyword">await</span> <span class="hljs-title function_">processChunk</span>(chunk, { signal });
    }
  },
  <span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'uppercase.txt'</span>),
);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Pipeline succeeded.'</span>);</code><button class="copy-button">copy</button></pre>
<p>Remember to handle the <code>signal</code> argument passed into the async generator.
Especially in the case where the async generator is the source for the
pipeline (i.e. first argument) or the pipeline will never complete.</p>

<pre class="with-53-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { pipeline } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/promises'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">run</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">await</span> <span class="hljs-title function_">pipeline</span>(
    <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>* ({ signal }) {
      <span class="hljs-keyword">await</span> <span class="hljs-title function_">someLongRunningfn</span>({ signal });
      <span class="hljs-keyword">yield</span> <span class="hljs-string">'asd'</span>;
    },
    fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'uppercase.txt'</span>),
  );
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Pipeline succeeded.'</span>);
}

<span class="hljs-title function_">run</span>().<span class="hljs-title function_">catch</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">error</span>);</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { pipeline } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/promises'</span>;
<span class="hljs-keyword">import</span> fs <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;
<span class="hljs-keyword">await</span> <span class="hljs-title function_">pipeline</span>(
  <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>* ({ signal }) {
    <span class="hljs-keyword">await</span> <span class="hljs-title function_">someLongRunningfn</span>({ signal });
    <span class="hljs-keyword">yield</span> <span class="hljs-string">'asd'</span>;
  },
  fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'uppercase.txt'</span>),
);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Pipeline succeeded.'</span>);</code><button class="copy-button">copy</button></pre>
<p>The <code>pipeline</code> API provides <a href="#all_stream_streampipelinesource-transforms-destination-callback">callback version</a>:</p>
<h4><code>stream.finished(stream[, options])</code><span><a class="mark" href="#all_stream_streamfinishedstream-options" id="all_stream_streamfinishedstream-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_finished_stream_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.5.0, v18.14.0</td>
<td><p>Added support for <code>ReadableStream</code> and <code>WritableStream</code>.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p><span>Added in: v15.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>stream</code> <a href="#all_stream_stream" class="type">&#x3C;Stream></a> | <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a> | <a href="#all_webstreams_class-writablestream" class="type">&#x3C;WritableStream></a> A readable and/or writable
stream/webstream.</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>
<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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a></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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a></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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a></li>
<li><code>signal</code>: <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a></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> Fulfills when the stream is no
longer readable or writable.</li>
</ul>

<pre class="with-53-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { finished } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/promises'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);

<span class="hljs-keyword">const</span> rs = fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'archive.tar'</span>);

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">run</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">await</span> <span class="hljs-title function_">finished</span>(rs);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Stream is done reading.'</span>);
}

<span class="hljs-title function_">run</span>().<span class="hljs-title function_">catch</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">error</span>);
rs.<span class="hljs-title function_">resume</span>(); <span class="hljs-comment">// Drain the stream.</span></code><code class="language-js mjs"><span class="hljs-keyword">import</span> { finished } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/promises'</span>;
<span class="hljs-keyword">import</span> { createReadStream } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-keyword">const</span> rs = <span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'archive.tar'</span>);

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">run</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">await</span> <span class="hljs-title function_">finished</span>(rs);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Stream is done reading.'</span>);
}

<span class="hljs-title function_">run</span>().<span class="hljs-title function_">catch</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">error</span>);
rs.<span class="hljs-title function_">resume</span>(); <span class="hljs-comment">// Drain the stream.</span></code><button class="copy-button">copy</button></pre>
<p>The <code>finished</code> API also provides a <a href="#all_stream_streamfinishedstream-options-callback">callback version</a>.</p>
<h4>Object mode<span><a class="mark" href="#all_stream_object-mode" id="all_stream_object-mode">#</a></span><a aria-hidden="true" class="legacy" id="stream_object_mode"></a></h4>
<p>All streams created by Node.js APIs operate exclusively on strings, <a href="#all_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> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> objects:</p>
<ul>
<li><code>Strings</code> and <code>Buffers</code> are the most common types used with streams.</li>
<li><code>TypedArray</code> and <code>DataView</code> lets you handle binary data with types like
<code>Int32Array</code> or <code>Uint8Array</code>. When you write a TypedArray or DataView to a
stream, Node.js processes
the raw bytes.</li>
</ul>
<p>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>
<h4>Buffering<span><a class="mark" href="#all_stream_buffering" id="all_stream_buffering">#</a></span><a aria-hidden="true" class="legacy" id="stream_buffering"></a></h4>

<p>Both <a href="#all_stream_class-streamwritable"><code>Writable</code></a> and <a href="#all_stream_class-streamreadable"><code>Readable</code></a> streams will store data in an internal
buffer.</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="#all_stream_highwatermark-discrepancy-after-calling-readablesetencoding">total number of bytes</a>. For streams operating
in object mode, the <code>highWaterMark</code> specifies a total number of objects. For
streams operating on (but not decoding) strings, the <code>highWaterMark</code> specifies
a total number of UTF-16 code units.</p>
<p>Data is buffered in <code>Readable</code> streams when the implementation calls
<a href="#all_stream_readablepushchunk-encoding"><code>stream.push(chunk)</code></a>. If the consumer of the Stream does not
call <a href="#all_stream_readablereadsize"><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="#all_stream_readable_readsize"><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="#all_stream_writablewritechunk-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="#all_stream_readablepipedestination-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="#all_stream_class-streamduplex"><code>Duplex</code></a> and <a href="#all_stream_class-streamtransform"><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="#all_net_class-netsocket"><code>net.Socket</code></a> instances are <a href="#all_stream_class-streamduplex"><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>
<p>The mechanics of the internal buffering are an internal implementation detail
and may be changed at any time. However, for certain advanced implementations,
the internal buffers can be retrieved using <code>writable.writableBuffer</code> or
<code>readable.readableBuffer</code>. Use of these undocumented properties is discouraged.</p>
</section><section><h3>API for stream consumers<span><a class="mark" href="#all_stream_api-for-stream-consumers" id="all_stream_api-for-stream-consumers">#</a></span><a aria-hidden="true" class="legacy" id="stream_api_for_stream_consumers"></a></h3>

<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"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);

<span class="hljs-keyword">const</span> server = http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
  <span class="hljs-comment">// `req` is an http.IncomingMessage, which is a readable stream.</span>
  <span class="hljs-comment">// `res` is an http.ServerResponse, which is a writable stream.</span>

  <span class="hljs-keyword">let</span> body = <span class="hljs-string">''</span>;
  <span class="hljs-comment">// Get the data as utf8 strings.</span>
  <span class="hljs-comment">// If an encoding is not set, Buffer objects will be received.</span>
  req.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>);

  <span class="hljs-comment">// Readable streams emit 'data' events once a listener is added.</span>
  req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> {
    body += chunk;
  });

  <span class="hljs-comment">// The 'end' event indicates that the entire body has been received.</span>
  req.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> {
    <span class="hljs-keyword">try</span> {
      <span class="hljs-keyword">const</span> data = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(body);
      <span class="hljs-comment">// Write back something interesting to the user:</span>
      res.<span class="hljs-title function_">write</span>(<span class="hljs-keyword">typeof</span> data);
      res.<span class="hljs-title function_">end</span>();
    } <span class="hljs-keyword">catch</span> (er) {
      <span class="hljs-comment">// uh oh! bad json!</span>
      res.<span class="hljs-property">statusCode</span> = <span class="hljs-number">400</span>;
      <span class="hljs-keyword">return</span> res.<span class="hljs-title function_">end</span>(<span class="hljs-string">`error: <span class="hljs-subst">${er.message}</span>`</span>);
    }
  });
});

server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">1337</span>);

<span class="hljs-comment">// $ curl localhost:1337 -d "{}"</span>
<span class="hljs-comment">// object</span>
<span class="hljs-comment">// $ curl localhost:1337 -d "\"foo\""</span>
<span class="hljs-comment">// string</span>
<span class="hljs-comment">// $ curl localhost:1337 -d "not json"</span>
<span class="hljs-comment">// error: Unexpected token 'o', "not json" is not valid JSON</span></code> <button class="copy-button">copy</button></pre>
<p><a href="#all_stream_class-streamwritable"><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="#all_stream_class-streamreadable"><code>Readable</code></a> streams use the <a href="#all_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="#all_stream_class-streamwritable"><code>Writable</code></a> and <a href="#all_stream_class-streamreadable"><code>Readable</code></a> streams use the <a href="#all_events_class-eventemitter"><code>EventEmitter</code></a> API in
various ways to communicate the current state of the stream.</p>
<p><a href="#all_stream_class-streamduplex"><code>Duplex</code></a> and <a href="#all_stream_class-streamtransform"><code>Transform</code></a> streams are both <a href="#all_stream_class-streamwritable"><code>Writable</code></a> and
<a href="#all_stream_class-streamreadable"><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('node:stream')</code>.</p>
<p>Developers wishing to implement new types of streams should refer to the
section <a href="#all_stream_api-for-stream-implementers">API for stream implementers</a>.</p>
<h4>Writable streams<span><a class="mark" href="#all_stream_writable-streams" id="all_stream_writable-streams">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_streams"></a></h4>
<p>Writable streams are an abstraction for a <em>destination</em> to which data is
written.</p>
<p>Examples of <a href="#all_stream_class-streamwritable"><code>Writable</code></a> streams include:</p>
<ul>
<li><a href="#all_http_class-httpclientrequest">HTTP requests, on the client</a></li>
<li><a href="#all_http_class-httpserverresponse">HTTP responses, on the server</a></li>
<li><a href="#all_fs_class-fswritestream">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="#all_net_class-netsocket">TCP sockets</a></li>
<li><a href="#all_child_process_subprocessstdin">child process stdin</a></li>
<li><a href="#all_process_processstdout"><code>process.stdout</code></a>, <a href="#all_process_processstderr"><code>process.stderr</code></a></li>
</ul>
<p>Some of these examples are actually <a href="#all_stream_class-streamduplex"><code>Duplex</code></a> streams that implement the
<a href="#all_stream_class-streamwritable"><code>Writable</code></a> interface.</p>
<p>All <a href="#all_stream_class-streamwritable"><code>Writable</code></a> streams implement the interface defined by the
<code>stream.Writable</code> class.</p>
<p>While specific instances of <a href="#all_stream_class-streamwritable"><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"><span class="hljs-keyword">const</span> myStream = <span class="hljs-title function_">getWritableStreamSomehow</span>();
myStream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some data'</span>);
myStream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some more data'</span>);
myStream.<span class="hljs-title function_">end</span>(<span class="hljs-string">'done writing data'</span>);</code> <button class="copy-button">copy</button></pre>
<h5>Class: <code>stream.Writable</code><span><a class="mark" href="#all_stream_class-streamwritable" id="all_stream_class-streamwritable">#</a></span><a aria-hidden="true" class="legacy" id="stream_class_stream_writable"></a></h5>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>

<h6>Event: <code>'close'</code><span><a class="mark" href="#all_stream_event-close" id="all_stream_event-close">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_close"></a></h6>
<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="#all_stream_class-streamwritable"><code>Writable</code></a> stream will always emit the <code>'close'</code> event if it is
created with the <code>emitClose</code> option.</p>
<h6>Event: <code>'drain'</code><span><a class="mark" href="#all_stream_event-drain" id="all_stream_event-drain">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_drain"></a></h6>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<p>If a call to <a href="#all_stream_writablewritechunk-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"><span class="hljs-comment">// Write the data to the supplied writable stream one million times.</span>
<span class="hljs-comment">// Be attentive to back-pressure.</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">writeOneMillionTimes</span>(<span class="hljs-params">writer, data, encoding, callback</span>) {
  <span class="hljs-keyword">let</span> i = <span class="hljs-number">1000000</span>;
  <span class="hljs-title function_">write</span>();
  <span class="hljs-keyword">function</span> <span class="hljs-title function_">write</span>(<span class="hljs-params"></span>) {
    <span class="hljs-keyword">let</span> ok = <span class="hljs-literal">true</span>;
    <span class="hljs-keyword">do</span> {
      i--;
      <span class="hljs-keyword">if</span> (i === <span class="hljs-number">0</span>) {
        <span class="hljs-comment">// Last time!</span>
        writer.<span class="hljs-title function_">write</span>(data, encoding, callback);
      } <span class="hljs-keyword">else</span> {
        <span class="hljs-comment">// See if we should continue, or wait.</span>
        <span class="hljs-comment">// Don't pass the callback, because we're not done yet.</span>
        ok = writer.<span class="hljs-title function_">write</span>(data, encoding);
      }
    } <span class="hljs-keyword">while</span> (i > <span class="hljs-number">0</span> &#x26;&#x26; ok);
    <span class="hljs-keyword">if</span> (i > <span class="hljs-number">0</span>) {
      <span class="hljs-comment">// Had to stop early!</span>
      <span class="hljs-comment">// Write some more once it drains.</span>
      writer.<span class="hljs-title function_">once</span>(<span class="hljs-string">'drain'</span>, write);
    }
  }
}</code> <button class="copy-button">copy</button></pre>
<h6>Event: <code>'error'</code><span><a class="mark" href="#all_stream_event-error" id="all_stream_event-error">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_error"></a></h6>
<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 closed when the <code>'error'</code> event is emitted unless the
<a href="#all_stream_new-streamwritableoptions"><code>autoDestroy</code></a> option was set to <code>false</code> when creating the
stream.</p>
<p>After <code>'error'</code>, no further events other than <code>'close'</code> <em>should</em> be emitted
(including <code>'error'</code> events).</p>
<h6>Event: <code>'finish'</code><span><a class="mark" href="#all_stream_event-finish" id="all_stream_event-finish">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_finish"></a></h6>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<p>The <code>'finish'</code> event is emitted after the <a href="#all_stream_writableendchunk-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"><span class="hljs-keyword">const</span> writer = <span class="hljs-title function_">getWritableStreamSomehow</span>();
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; <span class="hljs-number">100</span>; i++) {
  writer.<span class="hljs-title function_">write</span>(<span class="hljs-string">`hello, #<span class="hljs-subst">${i}</span>!\n`</span>);
}
writer.<span class="hljs-title function_">on</span>(<span class="hljs-string">'finish'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'All writes are now complete.'</span>);
});
writer.<span class="hljs-title function_">end</span>(<span class="hljs-string">'This is the end\n'</span>);</code> <button class="copy-button">copy</button></pre>
<h6>Event: <code>'pipe'</code><span><a class="mark" href="#all_stream_event-pipe" id="all_stream_event-pipe">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_pipe"></a></h6>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<ul>
<li><code>src</code> <a href="#all_stream_class-streamreadable" 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="#all_stream_readablepipedestination-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"><span class="hljs-keyword">const</span> writer = <span class="hljs-title function_">getWritableStreamSomehow</span>();
<span class="hljs-keyword">const</span> reader = <span class="hljs-title function_">getReadableStreamSomehow</span>();
writer.<span class="hljs-title function_">on</span>(<span class="hljs-string">'pipe'</span>, <span class="hljs-function">(<span class="hljs-params">src</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Something is piping into the writer.'</span>);
  assert.<span class="hljs-title function_">equal</span>(src, reader);
});
reader.<span class="hljs-title function_">pipe</span>(writer);</code> <button class="copy-button">copy</button></pre>
<h6>Event: <code>'unpipe'</code><span><a class="mark" href="#all_stream_event-unpipe" id="all_stream_event-unpipe">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_unpipe"></a></h6>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<ul>
<li><code>src</code> <a href="#all_stream_class-streamreadable" class="type">&#x3C;stream.Readable></a> The source stream that
<a href="#all_stream_readableunpipedestination">unpiped</a> this writable</li>
</ul>
<p>The <code>'unpipe'</code> event is emitted when the <a href="#all_stream_readableunpipedestination"><code>stream.unpipe()</code></a> method is called
on a <a href="#all_stream_class-streamreadable"><code>Readable</code></a> stream, removing this <a href="#all_stream_class-streamwritable"><code>Writable</code></a> from its set of
destinations.</p>
<p>This is also emitted in case this <a href="#all_stream_class-streamwritable"><code>Writable</code></a> stream emits an error when a
<a href="#all_stream_class-streamreadable"><code>Readable</code></a> stream pipes into it.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> writer = <span class="hljs-title function_">getWritableStreamSomehow</span>();
<span class="hljs-keyword">const</span> reader = <span class="hljs-title function_">getReadableStreamSomehow</span>();
writer.<span class="hljs-title function_">on</span>(<span class="hljs-string">'unpipe'</span>, <span class="hljs-function">(<span class="hljs-params">src</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Something has stopped piping into the writer.'</span>);
  assert.<span class="hljs-title function_">equal</span>(src, reader);
});
reader.<span class="hljs-title function_">pipe</span>(writer);
reader.<span class="hljs-title function_">unpipe</span>(writer);</code> <button class="copy-button">copy</button></pre>
<h6><code>writable.cork()</code><span><a class="mark" href="#all_stream_writablecork" id="all_stream_writablecork">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_cork"></a></h6>
<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="#all_stream_writableuncork"><code>stream.uncork()</code></a> or
<a href="#all_stream_writableendchunk-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="#all_stream_writableuncork"><code>writable.uncork()</code></a>, <a href="#all_stream_writable_writevchunks-callback"><code>writable._writev()</code></a>.</p>
<h6><code>writable.destroy([error])</code><span><a class="mark" href="#all_stream_writabledestroyerror" id="all_stream_writabledestroyerror">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_destroy_error"></a></h6>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.0.0</td>
<td><p>Work as a no-op on a stream that has already been destroyed.</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>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.</p>
<pre><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);

<span class="hljs-keyword">const</span> myStream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>();

<span class="hljs-keyword">const</span> fooErr = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'foo error'</span>);
myStream.<span class="hljs-title function_">destroy</span>(fooErr);
myStream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">fooErr</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(fooErr.<span class="hljs-property">message</span>)); <span class="hljs-comment">// foo error</span></code> <button class="copy-button">copy</button></pre>
<pre><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);

<span class="hljs-keyword">const</span> myStream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>();

myStream.<span class="hljs-title function_">destroy</span>();
myStream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-keyword">function</span> <span class="hljs-title function_">wontHappen</span>(<span class="hljs-params"></span>) {});</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);

<span class="hljs-keyword">const</span> myStream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>();
myStream.<span class="hljs-title function_">destroy</span>();

myStream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-function">(<span class="hljs-params">error</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(error.<span class="hljs-property">code</span>));
<span class="hljs-comment">// ERR_STREAM_DESTROYED</span></code> <button class="copy-button">copy</button></pre>
<p>Once <code>destroy()</code> has been called any further calls will be a no-op and no
further errors except from <code>_destroy()</code> may be emitted as <code>'error'</code>.</p>
<p>Implementors should not override this method,
but instead implement <a href="#all_stream_writable_destroyerr-callback"><code>writable._destroy()</code></a>.</p>
<h6><code>writable.closed</code><span><a class="mark" href="#all_stream_writableclosed" id="all_stream_writableclosed">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_closed"></a></h6>
<div class="api_metadata">
<span>Added in: v18.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 <code>'close'</code> has been emitted.</p>
<h6><code>writable.destroyed</code><span><a class="mark" href="#all_stream_writabledestroyed" id="all_stream_writabledestroyed">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_destroyed"></a></h6>
<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="#all_stream_writabledestroyerror"><code>writable.destroy()</code></a> has been called.</p>
<pre><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);

<span class="hljs-keyword">const</span> myStream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>();

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myStream.<span class="hljs-property">destroyed</span>); <span class="hljs-comment">// false</span>
myStream.<span class="hljs-title function_">destroy</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myStream.<span class="hljs-property">destroyed</span>); <span class="hljs-comment">// true</span></code> <button class="copy-button">copy</button></pre>
<h6><code>writable.end([chunk[, encoding]][, callback])</code><span><a class="mark" href="#all_stream_writableendchunk-encoding-callback" id="all_stream_writableendchunk-encoding-callback">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_end_chunk_encoding_callback"></a></h6>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.13.0</td>
<td><p>The <code>chunk</code> argument can now be a <code>TypedArray</code> or <code>DataView</code> instance.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p>The <code>callback</code> is invoked before 'finish' or on error.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>The <code>callback</code> is invoked if 'finish' or 'error' is emitted.</p></td></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="#all_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#Data_types" class="type">&#x3C;any></a> Optional data to write. For
streams not operating in object mode, <code>chunk</code> must be a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a>, <a href="#all_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> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a>. 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> 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="#all_stream_class-streamwritable"><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.</p>
<p>Calling the <a href="#all_stream_writablewritechunk-encoding-callback"><code>stream.write()</code></a> method after calling
<a href="#all_stream_writableendchunk-encoding-callback"><code>stream.end()</code></a> will raise an error.</p>
<pre><code class="language-js"><span class="hljs-comment">// Write 'hello, ' and then end with 'world!'.</span>
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> file = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'example.txt'</span>);
file.<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello, '</span>);
file.<span class="hljs-title function_">end</span>(<span class="hljs-string">'world!'</span>);
<span class="hljs-comment">// Writing more now is not allowed!</span></code> <button class="copy-button">copy</button></pre>
<h6><code>writable.setDefaultEncoding(encoding)</code><span><a class="mark" href="#all_stream_writablesetdefaultencodingencoding" id="all_stream_writablesetdefaultencodingencoding">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_setdefaultencoding_encoding"></a></h6>
<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="#all_stream_class-streamwritable"><code>Writable</code></a> stream.</p>
<h6><code>writable.uncork()</code><span><a class="mark" href="#all_stream_writableuncork" id="all_stream_writableuncork">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_uncork"></a></h6>
<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="#all_stream_writablecork"><code>stream.cork()</code></a> was called.</p>
<p>When using <a href="#all_stream_writablecork"><code>writable.cork()</code></a> and <code>writable.uncork()</code> to manage the buffering
of writes to a stream, defer calls to <code>writable.uncork()</code> 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.<span class="hljs-title function_">cork</span>();
stream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some '</span>);
stream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'data '</span>);
process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> stream.<span class="hljs-title function_">uncork</span>());</code> <button class="copy-button">copy</button></pre>
<p>If the <a href="#all_stream_writablecork"><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.<span class="hljs-title function_">cork</span>();
stream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'some '</span>);
stream.<span class="hljs-title function_">cork</span>();
stream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'data '</span>);
process.<span class="hljs-title function_">nextTick</span>(<span class="hljs-function">() =></span> {
  stream.<span class="hljs-title function_">uncork</span>();
  <span class="hljs-comment">// The data will not be flushed until uncork() is called a second time.</span>
  stream.<span class="hljs-title function_">uncork</span>();
});</code> <button class="copy-button">copy</button></pre>
<p>See also: <a href="#all_stream_writablecork"><code>writable.cork()</code></a>.</p>
<h6><code>writable.writable</code><span><a class="mark" href="#all_stream_writablewritable" id="all_stream_writablewritable">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_writable"></a></h6>
<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="#all_stream_writablewritechunk-encoding-callback"><code>writable.write()</code></a>, which means
the stream has not been destroyed, errored, or ended.</p>
<h6><code>writable.writableAborted</code><span><a class="mark" href="#all_stream_writablewritableaborted" id="all_stream_writablewritableaborted">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_writableaborted"></a></h6>
<div class="api_metadata">
<span>Added in: v18.0.0, v16.17.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_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>Returns whether the stream was destroyed or errored before emitting <code>'finish'</code>.</p>
<h6><code>writable.writableEnded</code><span><a class="mark" href="#all_stream_writablewritableended" id="all_stream_writablewritableended">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_writableended"></a></h6>
<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="#all_stream_writableendchunk-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="#all_stream_writablewritablefinished"><code>writable.writableFinished</code></a> instead.</p>
<h6><code>writable.writableCorked</code><span><a class="mark" href="#all_stream_writablewritablecorked" id="all_stream_writablewritablecorked">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_writablecorked"></a></h6>
<div class="api_metadata">
<span>Added in: v13.2.0, 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="#all_stream_writableuncork"><code>writable.uncork()</code></a> needs to be
called in order to fully uncork the stream.</p>
<h6><code>writable.errored</code><span><a class="mark" href="#all_stream_writableerrored" id="all_stream_writableerrored">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_errored"></a></h6>
<div class="api_metadata">
<span>Added in: v18.0.0</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>Returns error if the stream has been destroyed with an error.</p>
<h6><code>writable.writableFinished</code><span><a class="mark" href="#all_stream_writablewritablefinished" id="all_stream_writablewritablefinished">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_writablefinished"></a></h6>
<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="#all_stream_event-finish"><code>'finish'</code></a> event is emitted.</p>
<h6><code>writable.writableHighWaterMark</code><span><a class="mark" href="#all_stream_writablewritablehighwatermark" id="all_stream_writablewritablehighwatermark">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_writablehighwatermark"></a></h6>
<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 creating this <code>Writable</code>.</p>
<h6><code>writable.writableLength</code><span><a class="mark" href="#all_stream_writablewritablelength" id="all_stream_writablewritablelength">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_writablelength"></a></h6>
<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>
<h6><code>writable.writableNeedDrain</code><span><a class="mark" href="#all_stream_writablewritableneeddrain" id="all_stream_writablewritableneeddrain">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_writableneeddrain"></a></h6>
<div class="api_metadata">
<span>Added in: v15.2.0, v14.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>Is <code>true</code> if the stream's buffer has been full and stream will emit <code>'drain'</code>.</p>
<h6><code>writable.writableObjectMode</code><span><a class="mark" href="#all_stream_writablewritableobjectmode" id="all_stream_writablewritableobjectmode">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_writableobjectmode"></a></h6>
<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>
<h6><code>writable[Symbol.asyncDispose]()</code><span><a class="mark" href="#all_stream_writablesymbolasyncdispose" id="all_stream_writablesymbolasyncdispose">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_symbol_asyncdispose"></a></h6>
<div class="api_metadata">
<span>Added in: v20.16.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Calls <a href="#all_stream_writabledestroyerror"><code>writable.destroy()</code></a> with an <code>AbortError</code> and returns
a promise that fulfills when the stream is finished.</p>
<h6><code>writable.write(chunk[, encoding][, callback])</code><span><a class="mark" href="#all_stream_writablewritechunk-encoding-callback" id="all_stream_writablewritechunk-encoding-callback">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_write_chunk_encoding_callback"></a></h6>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.13.0</td>
<td><p>The <code>chunk</code> argument can now be a <code>TypedArray</code> or <code>DataView</code> instance.</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>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="#all_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#Data_types" class="type">&#x3C;any></a> Optional data to write. For
streams not operating in object mode, <code>chunk</code> must be a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a>, <a href="#all_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> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a>. 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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></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> will be called with the error as its
first argument. The <code>callback</code> is called asynchronously and before <code>'error'</code> is
emitted.</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="#all_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.
Once <code>write()</code> returns false, do not write more chunks
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="#all_stream_class-streamtransform"><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="#all_stream_class-streamreadable"><code>Readable</code></a> and use
<a href="#all_stream_readablepipedestination-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="#all_stream_event-drain"><code>'drain'</code></a> event:</p>
<pre><code class="language-js"><span class="hljs-keyword">function</span> <span class="hljs-title function_">write</span>(<span class="hljs-params">data, cb</span>) {
  <span class="hljs-keyword">if</span> (!stream.<span class="hljs-title function_">write</span>(data)) {
    stream.<span class="hljs-title function_">once</span>(<span class="hljs-string">'drain'</span>, cb);
  } <span class="hljs-keyword">else</span> {
    process.<span class="hljs-title function_">nextTick</span>(cb);
  }
}

<span class="hljs-comment">// Wait for cb to be called before doing any other write.</span>
<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Write completed, do more writes now.'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>A <code>Writable</code> stream in object mode will always ignore the <code>encoding</code> argument.</p>
<h4>Readable streams<span><a class="mark" href="#all_stream_readable-streams" id="all_stream_readable-streams">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_streams"></a></h4>
<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="#all_http_class-httpincomingmessage">HTTP responses, on the client</a></li>
<li><a href="#all_http_class-httpincomingmessage">HTTP requests, on the server</a></li>
<li><a href="#all_fs_class-fsreadstream">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="#all_net_class-netsocket">TCP sockets</a></li>
<li><a href="#all_child_process_subprocessstdout">child process stdout and stderr</a></li>
<li><a href="#all_process_processstdin"><code>process.stdin</code></a></li>
</ul>
<p>All <a href="#all_stream_class-streamreadable"><code>Readable</code></a> streams implement the interface defined by the
<code>stream.Readable</code> class.</p>
<h5>Two reading modes<span><a class="mark" href="#all_stream_two-reading-modes" id="all_stream_two-reading-modes">#</a></span><a aria-hidden="true" class="legacy" id="stream_two_reading_modes"></a></h5>
<p><code>Readable</code> streams effectively operate in one of two modes: flowing and
paused. These modes are separate from <a href="#all_stream_object-mode">object mode</a>.
A <a href="#all_stream_class-streamreadable"><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="#all_events_class-eventemitter"><code>EventEmitter</code></a> interface.</p>
</li>
<li>
<p>In paused mode, the <a href="#all_stream_readablereadsize"><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="#all_stream_class-streamreadable"><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="#all_stream_event-data"><code>'data'</code></a> event handler.</li>
<li>Calling the <a href="#all_stream_readableresume"><code>stream.resume()</code></a> method.</li>
<li>Calling the <a href="#all_stream_readablepipedestination-options"><code>stream.pipe()</code></a> method to send the data to a <a href="#all_stream_class-streamwritable"><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="#all_stream_readablepause"><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="#all_stream_readableunpipedestination"><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="#all_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="#all_stream_readablepause"><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="#all_stream_class-streamreadable"><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="#all_stream_event-readable"><code>'readable'</code></a> event handler automatically makes the stream
stop flowing, and the data has to be consumed via
<a href="#all_stream_readablereadsize"><code>readable.read()</code></a>. If the <a href="#all_stream_event-readable"><code>'readable'</code></a> event handler is
removed, then the stream will start flowing again if there is a
<a href="#all_stream_event-data"><code>'data'</code></a> event handler.</p>
<h5>Three states<span><a class="mark" href="#all_stream_three-states" id="all_stream_three-states">#</a></span><a aria-hidden="true" class="legacy" id="stream_three_states"></a></h5>
<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"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">PassThrough</span>, <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> pass = <span class="hljs-keyword">new</span> <span class="hljs-title class_">PassThrough</span>();
<span class="hljs-keyword">const</span> writable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>();

pass.<span class="hljs-title function_">pipe</span>(writable);
pass.<span class="hljs-title function_">unpipe</span>(writable);
<span class="hljs-comment">// readableFlowing is now false.</span>

pass.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk.<span class="hljs-title function_">toString</span>()); });
<span class="hljs-comment">// readableFlowing is still false.</span>
pass.<span class="hljs-title function_">write</span>(<span class="hljs-string">'ok'</span>);  <span class="hljs-comment">// Will not emit 'data'.</span>
pass.<span class="hljs-title function_">resume</span>();     <span class="hljs-comment">// Must be called to make stream emit 'data'.</span>
<span class="hljs-comment">// readableFlowing is now true.</span></code> <button class="copy-button">copy</button></pre>
<p>While <code>readable.readableFlowing</code> is <code>false</code>, data may be accumulating
within the stream's internal buffer.</p>
<h5>Choose one API style<span><a class="mark" href="#all_stream_choose-one-api-style" id="all_stream_choose-one-api-style">#</a></span><a aria-hidden="true" class="legacy" id="stream_choose_one_api_style"></a></h5>
<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>
<h5>Class: <code>stream.Readable</code><span><a class="mark" href="#all_stream_class-streamreadable" id="all_stream_class-streamreadable">#</a></span><a aria-hidden="true" class="legacy" id="stream_class_stream_readable"></a></h5>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>

<h6>Event: <code>'close'</code><span><a class="mark" href="#all_stream_event-close_1" id="all_stream_event-close_1">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_close_1"></a></h6>
<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="#all_stream_class-streamreadable"><code>Readable</code></a> stream will always emit the <code>'close'</code> event if it is
created with the <code>emitClose</code> option.</p>
<h6>Event: <code>'data'</code><span><a class="mark" href="#all_stream_event-data" id="all_stream_event-data">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_data"></a></h6>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<ul>
<li><code>chunk</code> <a href="#all_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"><span class="hljs-keyword">const</span> readable = <span class="hljs-title function_">getReadableStreamSomehow</span>();
readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Received <span class="hljs-subst">${chunk.length}</span> bytes of data.`</span>);
});</code> <button class="copy-button">copy</button></pre>
<h6>Event: <code>'end'</code><span><a class="mark" href="#all_stream_event-end" id="all_stream_event-end">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_end"></a></h6>
<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="#all_stream_readablereadsize"><code>stream.read()</code></a> repeatedly until all data has been
consumed.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> readable = <span class="hljs-title function_">getReadableStreamSomehow</span>();
readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Received <span class="hljs-subst">${chunk.length}</span> bytes of data.`</span>);
});
readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'There will be no more data.'</span>);
});</code> <button class="copy-button">copy</button></pre>
<h6>Event: <code>'error'</code><span><a class="mark" href="#all_stream_event-error_1" id="all_stream_event-error_1">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_error_1"></a></h6>
<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>
<h6>Event: <code>'pause'</code><span><a class="mark" href="#all_stream_event-pause" id="all_stream_event-pause">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_pause"></a></h6>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<p>The <code>'pause'</code> event is emitted when <a href="#all_stream_readablepause"><code>stream.pause()</code></a> is called
and <code>readableFlowing</code> is not <code>false</code>.</p>
<h6>Event: <code>'readable'</code><span><a class="mark" href="#all_stream_event-readable" id="all_stream_event-readable">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_readable"></a></h6>
<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, up to the configured high water mark (<code>state.highWaterMark</code>). Effectively,
it indicates that the stream has new information within the buffer. If data is available
within this buffer, <a href="#all_stream_readablereadsize"><code>stream.read()</code></a> can be called to retrieve that data.
Additionally, the <code>'readable'</code> event may also be emitted when the end of the stream has been
reached.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> readable = <span class="hljs-title function_">getReadableStreamSomehow</span>();
readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) {
  <span class="hljs-comment">// There is some data to read now.</span>
  <span class="hljs-keyword">let</span> data;

  <span class="hljs-keyword">while</span> ((data = <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">read</span>()) !== <span class="hljs-literal">null</span>) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data);
  }
});</code> <button class="copy-button">copy</button></pre>
<p>If the end of the stream has been reached, calling
<a href="#all_stream_readablereadsize"><code>stream.read()</code></a> will return <code>null</code> and trigger the <code>'end'</code>
event. This is also true if there never was any data to be read. For instance,
in the following example, <code>foo.txt</code> is an empty file:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> rr = fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'foo.txt'</span>);
rr.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`readable: <span class="hljs-subst">${rr.read()}</span>`</span>);
});
rr.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'end'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>The output of running this script is:</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node test.js</span>
readable: null
end</code> <button class="copy-button">copy</button></pre>
<p>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>
<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="#all_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="#all_stream_readablereadsize"><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>
<h6>Event: <code>'resume'</code><span><a class="mark" href="#all_stream_event-resume" id="all_stream_event-resume">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_resume"></a></h6>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<p>The <code>'resume'</code> event is emitted when <a href="#all_stream_readableresume"><code>stream.resume()</code></a> is
called and <code>readableFlowing</code> is not <code>true</code>.</p>
<h6><code>readable.destroy([error])</code><span><a class="mark" href="#all_stream_readabledestroyerror" id="all_stream_readabledestroyerror">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_destroy_error"></a></h6>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.0.0</td>
<td><p>Work as a no-op on a stream that has already been destroyed.</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>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.</p>
<p>Once <code>destroy()</code> has been called any further calls will be a no-op and no
further errors except from <code>_destroy()</code> may be emitted as <code>'error'</code>.</p>
<p>Implementors should not override this method, but instead implement
<a href="#all_stream_readable_destroyerr-callback"><code>readable._destroy()</code></a>.</p>
<h6><code>readable.closed</code><span><a class="mark" href="#all_stream_readableclosed" id="all_stream_readableclosed">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_closed"></a></h6>
<div class="api_metadata">
<span>Added in: v18.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 <code>'close'</code> has been emitted.</p>
<h6><code>readable.destroyed</code><span><a class="mark" href="#all_stream_readabledestroyed" id="all_stream_readabledestroyed">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_destroyed"></a></h6>
<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="#all_stream_readabledestroyerror"><code>readable.destroy()</code></a> has been called.</p>
<h6><code>readable.isPaused()</code><span><a class="mark" href="#all_stream_readableispaused" id="all_stream_readableispaused">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_ispaused"></a></h6>
<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"><span class="hljs-keyword">const</span> readable = <span class="hljs-keyword">new</span> stream.<span class="hljs-title class_">Readable</span>();

readable.<span class="hljs-title function_">isPaused</span>(); <span class="hljs-comment">// === false</span>
readable.<span class="hljs-title function_">pause</span>();
readable.<span class="hljs-title function_">isPaused</span>(); <span class="hljs-comment">// === true</span>
readable.<span class="hljs-title function_">resume</span>();
readable.<span class="hljs-title function_">isPaused</span>(); <span class="hljs-comment">// === false</span></code> <button class="copy-button">copy</button></pre>
<h6><code>readable.pause()</code><span><a class="mark" href="#all_stream_readablepause" id="all_stream_readablepause">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_pause"></a></h6>
<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="#all_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"><span class="hljs-keyword">const</span> readable = <span class="hljs-title function_">getReadableStreamSomehow</span>();
readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Received <span class="hljs-subst">${chunk.length}</span> bytes of data.`</span>);
  readable.<span class="hljs-title function_">pause</span>();
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'There will be no additional data for 1 second.'</span>);
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Now data will start flowing again.'</span>);
    readable.<span class="hljs-title function_">resume</span>();
  }, <span class="hljs-number">1000</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>The <code>readable.pause()</code> method has no effect if there is a <code>'readable'</code>
event listener.</p>
<h6><code>readable.pipe(destination[, options])</code><span><a class="mark" href="#all_stream_readablepipedestination-options" id="all_stream_readablepipedestination-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_pipe_destination_options"></a></h6>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<ul>
<li><code>destination</code> <a href="#all_stream_class-streamwritable" class="type">&#x3C;stream.Writable></a> The destination for writing data</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Pipe options
<ul>
<li><code>end</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> End the writer when the reader ends. <strong>Default:</strong> <code>true</code>.</li>
</ul>
</li>
<li>Returns: <a href="#all_stream_class-streamwritable" class="type">&#x3C;stream.Writable></a> The <em>destination</em>, allowing for a chain of pipes if
it is a <a href="#all_stream_class-streamduplex"><code>Duplex</code></a> or a <a href="#all_stream_class-streamtransform"><code>Transform</code></a> stream</li>
</ul>
<p>The <code>readable.pipe()</code> method attaches a <a href="#all_stream_class-streamwritable"><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="#all_stream_class-streamwritable"><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"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> readable = <span class="hljs-title function_">getReadableStreamSomehow</span>();
<span class="hljs-keyword">const</span> writable = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'file.txt'</span>);
<span class="hljs-comment">// All the data from readable goes into 'file.txt'.</span>
readable.<span class="hljs-title function_">pipe</span>(writable);</code> <button class="copy-button">copy</button></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"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> zlib = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:zlib'</span>);
<span class="hljs-keyword">const</span> r = fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'file.txt'</span>);
<span class="hljs-keyword">const</span> z = zlib.<span class="hljs-title function_">createGzip</span>();
<span class="hljs-keyword">const</span> w = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'file.txt.gz'</span>);
r.<span class="hljs-title function_">pipe</span>(z).<span class="hljs-title function_">pipe</span>(w);</code> <button class="copy-button">copy</button></pre>
<p>By default, <a href="#all_stream_writableendchunk-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="#all_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.<span class="hljs-title function_">pipe</span>(writer, { <span class="hljs-attr">end</span>: <span class="hljs-literal">false</span> });
reader.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> {
  writer.<span class="hljs-title function_">end</span>(<span class="hljs-string">'Goodbye\n'</span>);
});</code> <button class="copy-button">copy</button></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="#all_process_processstderr"><code>process.stderr</code></a> and <a href="#all_process_processstdout"><code>process.stdout</code></a> <code>Writable</code> streams are never
closed until the Node.js process exits, regardless of the specified options.</p>
<h6><code>readable.read([size])</code><span><a class="mark" href="#all_stream_readablereadsize" id="all_stream_readablereadsize">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_read_size"></a></h6>
<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="#all_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 reads data out of the internal buffer and
returns it. If no data is available to be read, <code>null</code> is returned. By default,
the data is 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 GiB.</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"><span class="hljs-keyword">const</span> readable = <span class="hljs-title function_">getReadableStreamSomehow</span>();

<span class="hljs-comment">// 'readable' may be triggered multiple times as data is buffered in</span>
readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-keyword">let</span> chunk;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Stream is readable (new data received in buffer)'</span>);
  <span class="hljs-comment">// Use a loop to make sure we read all currently available data</span>
  <span class="hljs-keyword">while</span> (<span class="hljs-literal">null</span> !== (chunk = readable.<span class="hljs-title function_">read</span>())) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Read <span class="hljs-subst">${chunk.length}</span> bytes of data...`</span>);
  }
});

<span class="hljs-comment">// 'end' will be triggered once when there is no more data available</span>
readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Reached end of stream.'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>Each call to <code>readable.read()</code> returns a chunk of data or <code>null</code>, signifying
that there's no more data to read at that moment. These chunks aren't automatically
concatenated. Because a single <code>read()</code> call does not return all the data, using
a while loop may be necessary to continuously read chunks until all data is retrieved.
When reading a large file, <code>.read()</code> might return <code>null</code> temporarily, indicating
that it has consumed all buffered content but there may be more data yet to be
buffered. In such cases, a new <code>'readable'</code> event is emitted once there's more
data in the buffer, and the <code>'end'</code> event signifies the end of data transmission.</p>
<p>Therefore to read a file's whole contents from a <code>readable</code>, it is necessary
to collect chunks across multiple <code>'readable'</code> events:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> chunks = [];

readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-keyword">let</span> chunk;
  <span class="hljs-keyword">while</span> (<span class="hljs-literal">null</span> !== (chunk = readable.<span class="hljs-title function_">read</span>())) {
    chunks.<span class="hljs-title function_">push</span>(chunk);
  }
});

readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-keyword">const</span> content = chunks.<span class="hljs-title function_">join</span>(<span class="hljs-string">''</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>A <code>Readable</code> stream in object mode will always return a single item from
a call to <a href="#all_stream_readablereadsize"><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="#all_stream_readablereadsize"><code>stream.read([size])</code></a> after the <a href="#all_stream_event-end"><code>'end'</code></a> event has
been emitted will return <code>null</code>. No runtime error will be raised.</p>
<h6><code>readable.readable</code><span><a class="mark" href="#all_stream_readablereadable" id="all_stream_readablereadable">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_readable"></a></h6>
<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="#all_stream_readablereadsize"><code>readable.read()</code></a>, which means
the stream has not been destroyed or emitted <code>'error'</code> or <code>'end'</code>.</p>
<h6><code>readable.readableAborted</code><span><a class="mark" href="#all_stream_readablereadableaborted" id="all_stream_readablereadableaborted">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_readableaborted"></a></h6>
<div class="api_metadata">
<span>Added in: v16.8.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_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>Returns whether the stream was destroyed or errored before emitting <code>'end'</code>.</p>
<h6><code>readable.readableDidRead</code><span><a class="mark" href="#all_stream_readablereadabledidread" id="all_stream_readablereadabledidread">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_readabledidread"></a></h6>
<div class="api_metadata">
<span>Added in: v16.7.0, v14.18.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_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>Returns whether <code>'data'</code> has been emitted.</p>
<h6><code>readable.readableEncoding</code><span><a class="mark" href="#all_stream_readablereadableencoding" id="all_stream_readablereadableencoding">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_readableencoding"></a></h6>
<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="#all_stream_readablesetencodingencoding"><code>readable.setEncoding()</code></a> method.</p>
<h6><code>readable.readableEnded</code><span><a class="mark" href="#all_stream_readablereadableended" id="all_stream_readablereadableended">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_readableended"></a></h6>
<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="#all_stream_event-end"><code>'end'</code></a> event is emitted.</p>
<h6><code>readable.errored</code><span><a class="mark" href="#all_stream_readableerrored" id="all_stream_readableerrored">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_errored"></a></h6>
<div class="api_metadata">
<span>Added in: v18.0.0</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>Returns error if the stream has been destroyed with an error.</p>
<h6><code>readable.readableFlowing</code><span><a class="mark" href="#all_stream_readablereadableflowing" id="all_stream_readablereadableflowing">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_readableflowing"></a></h6>
<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="#all_stream_three-states">Three states</a> section.</p>
<h6><code>readable.readableHighWaterMark</code><span><a class="mark" href="#all_stream_readablereadablehighwatermark" id="all_stream_readablereadablehighwatermark">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_readablehighwatermark"></a></h6>
<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 creating this <code>Readable</code>.</p>
<h6><code>readable.readableLength</code><span><a class="mark" href="#all_stream_readablereadablelength" id="all_stream_readablereadablelength">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_readablelength"></a></h6>
<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>
<h6><code>readable.readableObjectMode</code><span><a class="mark" href="#all_stream_readablereadableobjectmode" id="all_stream_readablereadableobjectmode">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_readableobjectmode"></a></h6>
<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>
<h6><code>readable.resume()</code><span><a class="mark" href="#all_stream_readableresume" id="all_stream_readableresume">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_resume"></a></h6>
<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="#all_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"><span class="hljs-title function_">getReadableStreamSomehow</span>()
  .<span class="hljs-title function_">resume</span>()
  .<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Reached the end, but did not read anything.'</span>);
  });</code> <button class="copy-button">copy</button></pre>
<p>The <code>readable.resume()</code> method has no effect if there is a <code>'readable'</code>
event listener.</p>
<h6><code>readable.setEncoding(encoding)</code><span><a class="mark" href="#all_stream_readablesetencodingencoding" id="all_stream_readablesetencodingencoding">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_setencoding_encoding"></a></h6>
<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"><span class="hljs-keyword">const</span> readable = <span class="hljs-title function_">getReadableStreamSomehow</span>();
readable.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>);
readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> {
  assert.<span class="hljs-title function_">equal</span>(<span class="hljs-keyword">typeof</span> chunk, <span class="hljs-string">'string'</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Got %d characters of string data:'</span>, chunk.<span class="hljs-property">length</span>);
});</code> <button class="copy-button">copy</button></pre>
<h6><code>readable.unpipe([destination])</code><span><a class="mark" href="#all_stream_readableunpipedestination" id="all_stream_readableunpipedestination">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_unpipe_destination"></a></h6>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<ul>
<li><code>destination</code> <a href="#all_stream_class-streamwritable" 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="#all_stream_readablepipedestination-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"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> readable = <span class="hljs-title function_">getReadableStreamSomehow</span>();
<span class="hljs-keyword">const</span> writable = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'file.txt'</span>);
<span class="hljs-comment">// All the data from readable goes into 'file.txt',</span>
<span class="hljs-comment">// but only for the first second.</span>
readable.<span class="hljs-title function_">pipe</span>(writable);
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Stop writing to file.txt.'</span>);
  readable.<span class="hljs-title function_">unpipe</span>(writable);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Manually close the file stream.'</span>);
  writable.<span class="hljs-title function_">end</span>();
}, <span class="hljs-number">1000</span>);</code> <button class="copy-button">copy</button></pre>
<h6><code>readable.unshift(chunk[, encoding])</code><span><a class="mark" href="#all_stream_readableunshiftchunk-encoding" id="all_stream_readableunshiftchunk-encoding">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_unshift_chunk_encoding"></a></h6>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.13.0</td>
<td><p>The <code>chunk</code> argument can now be a <code>TypedArray</code> or <code>DataView</code> instance.</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.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="#all_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#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 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a>, <a href="#all_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> 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="#all_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="#all_stream_class-streamtransform"><code>Transform</code></a> stream instead. See the <a href="#all_stream_api-for-stream-implementers">API for stream implementers</a>
section for more information.</p>
<pre><code class="language-js"><span class="hljs-comment">// Pull off a header delimited by \n\n.</span>
<span class="hljs-comment">// Use unshift() if we get too much.</span>
<span class="hljs-comment">// Call the callback with (error, header, stream).</span>
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">StringDecoder</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:string_decoder'</span>);
<span class="hljs-keyword">function</span> <span class="hljs-title function_">parseHeader</span>(<span class="hljs-params">stream, callback</span>) {
  stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, callback);
  stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, onReadable);
  <span class="hljs-keyword">const</span> decoder = <span class="hljs-keyword">new</span> <span class="hljs-title class_">StringDecoder</span>(<span class="hljs-string">'utf8'</span>);
  <span class="hljs-keyword">let</span> header = <span class="hljs-string">''</span>;
  <span class="hljs-keyword">function</span> <span class="hljs-title function_">onReadable</span>(<span class="hljs-params"></span>) {
    <span class="hljs-keyword">let</span> chunk;
    <span class="hljs-keyword">while</span> (<span class="hljs-literal">null</span> !== (chunk = stream.<span class="hljs-title function_">read</span>())) {
      <span class="hljs-keyword">const</span> str = decoder.<span class="hljs-title function_">write</span>(chunk);
      <span class="hljs-keyword">if</span> (str.<span class="hljs-title function_">includes</span>(<span class="hljs-string">'\n\n'</span>)) {
        <span class="hljs-comment">// Found the header boundary.</span>
        <span class="hljs-keyword">const</span> split = str.<span class="hljs-title function_">split</span>(<span class="hljs-regexp">/\n\n/</span>);
        header += split.<span class="hljs-title function_">shift</span>();
        <span class="hljs-keyword">const</span> remaining = split.<span class="hljs-title function_">join</span>(<span class="hljs-string">'\n\n'</span>);
        <span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(remaining, <span class="hljs-string">'utf8'</span>);
        stream.<span class="hljs-title function_">removeListener</span>(<span class="hljs-string">'error'</span>, callback);
        <span class="hljs-comment">// Remove the 'readable' listener before unshifting.</span>
        stream.<span class="hljs-title function_">removeListener</span>(<span class="hljs-string">'readable'</span>, onReadable);
        <span class="hljs-keyword">if</span> (buf.<span class="hljs-property">length</span>)
          stream.<span class="hljs-title function_">unshift</span>(buf);
        <span class="hljs-comment">// Now the body of the message can be read from the stream.</span>
        <span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, header, stream);
        <span class="hljs-keyword">return</span>;
      }
      <span class="hljs-comment">// Still reading the header.</span>
      header += str;
    }
  }
}</code> <button class="copy-button">copy</button></pre>
<p>Unlike <a href="#all_stream_readablepushchunk-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="#all_stream_readable_readsize"><code>stream._read()</code></a> implementation on a
custom stream). Following the call to <code>readable.unshift()</code> with an immediate
<a href="#all_stream_readablepushchunk-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>
<h6><code>readable.wrap(stream)</code><span><a class="mark" href="#all_stream_readablewrapstream" id="all_stream_readablewrapstream">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_wrap_stream"></a></h6>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>
<ul>
<li><code>stream</code> <a href="#all_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>node:stream</code>
module API as it is currently defined. (See <a href="#all_stream_compatibility-with-older-nodejs-versions">Compatibility</a> for more
information.)</p>
<p>When using an older Node.js library that emits <a href="#all_stream_event-data"><code>'data'</code></a> events and has a
<a href="#all_stream_readablepause"><code>stream.pause()</code></a> method that is advisory only, the
<code>readable.wrap()</code> method can be used to create a <a href="#all_stream_class-streamreadable"><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"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">OldReader</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./old-api-module.js'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Readable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> oreader = <span class="hljs-keyword">new</span> <span class="hljs-title class_">OldReader</span>();
<span class="hljs-keyword">const</span> myReader = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Readable</span>().<span class="hljs-title function_">wrap</span>(oreader);

myReader.<span class="hljs-title function_">on</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> {
  myReader.<span class="hljs-title function_">read</span>(); <span class="hljs-comment">// etc.</span>
});</code> <button class="copy-button">copy</button></pre>
<h6><code>readable[Symbol.asyncIterator]()</code><span><a class="mark" href="#all_stream_readablesymbolasynciterator" id="all_stream_readablesymbolasynciterator">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_symbol_asynciterator"></a></h6>
<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"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">print</span>(<span class="hljs-params">readable</span>) {
  readable.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>);
  <span class="hljs-keyword">let</span> data = <span class="hljs-string">''</span>;
  <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> readable) {
    data += chunk;
  }
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data);
}

<span class="hljs-title function_">print</span>(fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'file'</span>)).<span class="hljs-title function_">catch</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">error</span>);</code> <button class="copy-button">copy</button></pre>
<p>If the loop terminates with a <code>break</code>, <code>return</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 64 KiB of data because no <code>highWaterMark</code> option is provided to
<a href="#all_fs_fscreatereadstreampath-options"><code>fs.createReadStream()</code></a>.</p>
<h6><code>readable[Symbol.asyncDispose]()</code><span><a class="mark" href="#all_stream_readablesymbolasyncdispose" id="all_stream_readablesymbolasyncdispose">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_symbol_asyncdispose"></a></h6>
<div class="api_metadata">
<span>Added in: v20.4.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Calls <a href="#all_stream_readabledestroyerror"><code>readable.destroy()</code></a> with an <code>AbortError</code> and returns
a promise that fulfills when the stream is finished.</p>
<h6><code>readable.compose(stream[, options])</code><span><a class="mark" href="#all_stream_readablecomposestream-options" id="all_stream_readablecomposestream-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_compose_stream_options"></a></h6>
<div class="api_metadata">
<span>Added in: v19.1.0, v18.13.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>stream</code> <a href="#all_stream_stream" class="type">&#x3C;Stream></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol" class="type">&#x3C;Iterable></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type">&#x3C;AsyncIterable></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></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>
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> allows destroying the stream if the signal is
aborted.</li>
</ul>
</li>
<li>Returns: <a href="#all_stream_class-streamduplex" class="type">&#x3C;Duplex></a> a stream composed with the stream <code>stream</code>.</li>
</ul>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>* <span class="hljs-title function_">splitToWords</span>(<span class="hljs-params">source</span>) {
  <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> source) {
    <span class="hljs-keyword">const</span> words = <span class="hljs-title class_">String</span>(chunk).<span class="hljs-title function_">split</span>(<span class="hljs-string">' '</span>);

    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> word <span class="hljs-keyword">of</span> words) {
      <span class="hljs-keyword">yield</span> word;
    }
  }
}

<span class="hljs-keyword">const</span> wordsStream = <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-string">'this is'</span>, <span class="hljs-string">'compose as operator'</span>]).<span class="hljs-title function_">compose</span>(splitToWords);
<span class="hljs-keyword">const</span> words = <span class="hljs-keyword">await</span> wordsStream.<span class="hljs-title function_">toArray</span>();

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(words); <span class="hljs-comment">// prints ['this', 'is', 'compose', 'as', 'operator']</span></code> <button class="copy-button">copy</button></pre>
<p>See <a href="#all_stream_streamcomposestreams"><code>stream.compose</code></a> for more information.</p>
<h6><code>readable.iterator([options])</code><span><a class="mark" href="#all_stream_readableiteratoroptions" id="all_stream_readableiteratoroptions">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_iterator_options"></a></h6>
<div class="api_metadata">
<span>Added in: v16.3.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<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>
<ul>
<li><code>destroyOnReturn</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>, calling <code>return</code> on the
async iterator, or exiting a <code>for await...of</code> iteration using a <code>break</code>,
<code>return</code>, or <code>throw</code> will not destroy the stream. <strong>Default:</strong> <code>true</code>.</li>
</ul>
</li>
<li>Returns: <a href="https://tc39.github.io/ecma262/#sec-asynciterator-interface" class="type">&#x3C;AsyncIterator></a> to consume the stream.</li>
</ul>
<p>The iterator created by this method gives users the option to cancel the
destruction of the stream if the <code>for await...of</code> loop is exited by <code>return</code>,
<code>break</code>, or <code>throw</code>, or if the iterator should destroy the stream if the stream
emitted an error during iteration.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Readable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">printIterator</span>(<span class="hljs-params">readable</span>) {
  <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> readable.<span class="hljs-title function_">iterator</span>({ <span class="hljs-attr">destroyOnReturn</span>: <span class="hljs-literal">false</span> })) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk); <span class="hljs-comment">// 1</span>
    <span class="hljs-keyword">break</span>;
  }

  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(readable.<span class="hljs-property">destroyed</span>); <span class="hljs-comment">// false</span>

  <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> readable.<span class="hljs-title function_">iterator</span>({ <span class="hljs-attr">destroyOnReturn</span>: <span class="hljs-literal">false</span> })) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk); <span class="hljs-comment">// Will print 2 and then 3</span>
  }

  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(readable.<span class="hljs-property">destroyed</span>); <span class="hljs-comment">// True, stream was totally consumed</span>
}

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">printSymbolAsyncIterator</span>(<span class="hljs-params">readable</span>) {
  <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> readable) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk); <span class="hljs-comment">// 1</span>
    <span class="hljs-keyword">break</span>;
  }

  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(readable.<span class="hljs-property">destroyed</span>); <span class="hljs-comment">// true</span>
}

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">showBoth</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">await</span> <span class="hljs-title function_">printIterator</span>(<span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]));
  <span class="hljs-keyword">await</span> <span class="hljs-title function_">printSymbolAsyncIterator</span>(<span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]));
}

<span class="hljs-title function_">showBoth</span>();</code> <button class="copy-button">copy</button></pre>
<h6><code>readable.map(fn[, options])</code><span><a class="mark" href="#all_stream_readablemapfn-options" id="all_stream_readablemapfn-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_map_fn_options"></a></h6>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.7.0</td>
<td><p>added <code>highWaterMark</code> in options.</p></td></tr>
<tr><td>v17.4.0, v16.14.0</td>
<td><p><span>Added in: v17.4.0, v16.14.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<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://tc39.es/ecma262/#sec-async-function-constructor" class="type">&#x3C;AsyncFunction></a> a function to map over every chunk in the
stream.
<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> a chunk of data from the stream.</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>
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> aborted if the stream is destroyed allowing to
abort the <code>fn</code> call early.</li>
</ul>
</li>
</ul>
</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>
<ul>
<li><code>concurrency</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> the maximum concurrent invocation of <code>fn</code> to call
on the stream at once. <strong>Default:</strong> <code>1</code>.</li>
<li><code>highWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> how many items to buffer while waiting for user
consumption of the mapped items. <strong>Default:</strong> <code>concurrency * 2 - 1</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> allows destroying the stream if the signal is
aborted.</li>
</ul>
</li>
<li>Returns: <a href="#all_stream_class-streamreadable" class="type">&#x3C;Readable></a> a stream mapped with the function <code>fn</code>.</li>
</ul>
<p>This method allows mapping over the stream. The <code>fn</code> function will be called
for every chunk in the stream. If the <code>fn</code> function returns a promise - that
promise will be <code>await</code>ed before being passed to the result stream.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Resolver</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dns/promises'</span>;

<span class="hljs-comment">// With a synchronous mapper.</span>
<span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">map</span>(<span class="hljs-function">(<span class="hljs-params">x</span>) =></span> x * <span class="hljs-number">2</span>)) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk); <span class="hljs-comment">// 2, 4, 6, 8</span>
}
<span class="hljs-comment">// With an asynchronous mapper, making at most 2 queries at a time.</span>
<span class="hljs-keyword">const</span> resolver = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Resolver</span>();
<span class="hljs-keyword">const</span> dnsResults = <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([
  <span class="hljs-string">'nodejs.org'</span>,
  <span class="hljs-string">'openjsf.org'</span>,
  <span class="hljs-string">'www.linuxfoundation.org'</span>,
]).<span class="hljs-title function_">map</span>(<span class="hljs-function">(<span class="hljs-params">domain</span>) =></span> resolver.<span class="hljs-title function_">resolve4</span>(domain), { <span class="hljs-attr">concurrency</span>: <span class="hljs-number">2</span> });
<span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> result <span class="hljs-keyword">of</span> dnsResults) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result); <span class="hljs-comment">// Logs the DNS result of resolver.resolve4.</span>
}</code> <button class="copy-button">copy</button></pre>
<h6><code>readable.filter(fn[, options])</code><span><a class="mark" href="#all_stream_readablefilterfn-options" id="all_stream_readablefilterfn-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_filter_fn_options"></a></h6>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.7.0</td>
<td><p>added <code>highWaterMark</code> in options.</p></td></tr>
<tr><td>v17.4.0, v16.14.0</td>
<td><p><span>Added in: v17.4.0, v16.14.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<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://tc39.es/ecma262/#sec-async-function-constructor" class="type">&#x3C;AsyncFunction></a> a function to filter chunks from the stream.
<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> a chunk of data from the stream.</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>
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> aborted if the stream is destroyed allowing to
abort the <code>fn</code> call early.</li>
</ul>
</li>
</ul>
</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>
<ul>
<li><code>concurrency</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> the maximum concurrent invocation of <code>fn</code> to call
on the stream at once. <strong>Default:</strong> <code>1</code>.</li>
<li><code>highWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> how many items to buffer while waiting for user
consumption of the filtered items. <strong>Default:</strong> <code>concurrency * 2 - 1</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> allows destroying the stream if the signal is
aborted.</li>
</ul>
</li>
<li>Returns: <a href="#all_stream_class-streamreadable" class="type">&#x3C;Readable></a> a stream filtered with the predicate <code>fn</code>.</li>
</ul>
<p>This method allows filtering the stream. For each chunk in the stream the <code>fn</code>
function will be called and if it returns a truthy value, the chunk will be
passed to the result stream. If the <code>fn</code> function returns a promise - that
promise will be <code>await</code>ed.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Resolver</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dns/promises'</span>;

<span class="hljs-comment">// With a synchronous predicate.</span>
<span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">filter</span>(<span class="hljs-function">(<span class="hljs-params">x</span>) =></span> x > <span class="hljs-number">2</span>)) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk); <span class="hljs-comment">// 3, 4</span>
}
<span class="hljs-comment">// With an asynchronous predicate, making at most 2 queries at a time.</span>
<span class="hljs-keyword">const</span> resolver = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Resolver</span>();
<span class="hljs-keyword">const</span> dnsResults = <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([
  <span class="hljs-string">'nodejs.org'</span>,
  <span class="hljs-string">'openjsf.org'</span>,
  <span class="hljs-string">'www.linuxfoundation.org'</span>,
]).<span class="hljs-title function_">filter</span>(<span class="hljs-keyword">async</span> (domain) => {
  <span class="hljs-keyword">const</span> { address } = <span class="hljs-keyword">await</span> resolver.<span class="hljs-title function_">resolve4</span>(domain, { <span class="hljs-attr">ttl</span>: <span class="hljs-literal">true</span> });
  <span class="hljs-keyword">return</span> address.<span class="hljs-property">ttl</span> > <span class="hljs-number">60</span>;
}, { <span class="hljs-attr">concurrency</span>: <span class="hljs-number">2</span> });
<span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> result <span class="hljs-keyword">of</span> dnsResults) {
  <span class="hljs-comment">// Logs domains with more than 60 seconds on the resolved dns record.</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result);
}</code> <button class="copy-button">copy</button></pre>
<h6><code>readable.forEach(fn[, options])</code><span><a class="mark" href="#all_stream_readableforeachfn-options" id="all_stream_readableforeachfn-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_foreach_fn_options"></a></h6>
<div class="api_metadata">
<span>Added in: v17.5.0, v16.15.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<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://tc39.es/ecma262/#sec-async-function-constructor" class="type">&#x3C;AsyncFunction></a> a function to call on each chunk of the stream.
<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> a chunk of data from the stream.</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>
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> aborted if the stream is destroyed allowing to
abort the <code>fn</code> call early.</li>
</ul>
</li>
</ul>
</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>
<ul>
<li><code>concurrency</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> the maximum concurrent invocation of <code>fn</code> to call
on the stream at once. <strong>Default:</strong> <code>1</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> allows destroying the stream if the signal is
aborted.</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> a promise for when the stream has finished.</li>
</ul>
<p>This method allows iterating a stream. For each chunk in the stream the
<code>fn</code> function will be called. If the <code>fn</code> function returns a promise - that
promise will be <code>await</code>ed.</p>
<p>This method is different from <code>for await...of</code> loops in that it can optionally
process chunks concurrently. In addition, a <code>forEach</code> iteration can only be
stopped by having passed a <code>signal</code> option and aborting the related
<code>AbortController</code> while <code>for await...of</code> can be stopped with <code>break</code> or
<code>return</code>. In either case the stream will be destroyed.</p>
<p>This method is different from listening to the <a href="#all_stream_event-data"><code>'data'</code></a> event in that it
uses the <a href="#all_stream_class-streamreadable"><code>readable</code></a> event in the underlying machinary and can limit the
number of concurrent <code>fn</code> calls.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Resolver</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dns/promises'</span>;

<span class="hljs-comment">// With a synchronous predicate.</span>
<span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">filter</span>(<span class="hljs-function">(<span class="hljs-params">x</span>) =></span> x > <span class="hljs-number">2</span>)) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk); <span class="hljs-comment">// 3, 4</span>
}
<span class="hljs-comment">// With an asynchronous predicate, making at most 2 queries at a time.</span>
<span class="hljs-keyword">const</span> resolver = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Resolver</span>();
<span class="hljs-keyword">const</span> dnsResults = <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([
  <span class="hljs-string">'nodejs.org'</span>,
  <span class="hljs-string">'openjsf.org'</span>,
  <span class="hljs-string">'www.linuxfoundation.org'</span>,
]).<span class="hljs-title function_">map</span>(<span class="hljs-keyword">async</span> (domain) => {
  <span class="hljs-keyword">const</span> { address } = <span class="hljs-keyword">await</span> resolver.<span class="hljs-title function_">resolve4</span>(domain, { <span class="hljs-attr">ttl</span>: <span class="hljs-literal">true</span> });
  <span class="hljs-keyword">return</span> address;
}, { <span class="hljs-attr">concurrency</span>: <span class="hljs-number">2</span> });
<span class="hljs-keyword">await</span> dnsResults.<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">result</span>) =></span> {
  <span class="hljs-comment">// Logs result, similar to `for await (const result of dnsResults)`</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result);
});
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'done'</span>); <span class="hljs-comment">// Stream has finished</span></code> <button class="copy-button">copy</button></pre>
<h6><code>readable.toArray([options])</code><span><a class="mark" href="#all_stream_readabletoarrayoptions" id="all_stream_readabletoarrayoptions">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_toarray_options"></a></h6>
<div class="api_metadata">
<span>Added in: v17.5.0, v16.15.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<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>
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> allows cancelling the toArray operation if the
signal is aborted.</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> a promise containing an array with the contents of the
stream.</li>
</ul>
<p>This method allows easily obtaining the contents of a stream.</p>
<p>As this method reads the entire stream into memory, it negates the benefits of
streams. It's intended for interoperability and convenience, not as the primary
way to consume streams.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Resolver</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dns/promises'</span>;

<span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">toArray</span>(); <span class="hljs-comment">// [1, 2, 3, 4]</span>

<span class="hljs-comment">// Make dns queries concurrently using .map and collect</span>
<span class="hljs-comment">// the results into an array using toArray</span>
<span class="hljs-keyword">const</span> dnsResults = <span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([
  <span class="hljs-string">'nodejs.org'</span>,
  <span class="hljs-string">'openjsf.org'</span>,
  <span class="hljs-string">'www.linuxfoundation.org'</span>,
]).<span class="hljs-title function_">map</span>(<span class="hljs-keyword">async</span> (domain) => {
  <span class="hljs-keyword">const</span> { address } = <span class="hljs-keyword">await</span> resolver.<span class="hljs-title function_">resolve4</span>(domain, { <span class="hljs-attr">ttl</span>: <span class="hljs-literal">true</span> });
  <span class="hljs-keyword">return</span> address;
}, { <span class="hljs-attr">concurrency</span>: <span class="hljs-number">2</span> }).<span class="hljs-title function_">toArray</span>();</code> <button class="copy-button">copy</button></pre>
<h6><code>readable.some(fn[, options])</code><span><a class="mark" href="#all_stream_readablesomefn-options" id="all_stream_readablesomefn-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_some_fn_options"></a></h6>
<div class="api_metadata">
<span>Added in: v17.5.0, v16.15.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<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://tc39.es/ecma262/#sec-async-function-constructor" class="type">&#x3C;AsyncFunction></a> a function to call on each chunk of the stream.
<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> a chunk of data from the stream.</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>
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> aborted if the stream is destroyed allowing to
abort the <code>fn</code> call early.</li>
</ul>
</li>
</ul>
</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>
<ul>
<li><code>concurrency</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> the maximum concurrent invocation of <code>fn</code> to call
on the stream at once. <strong>Default:</strong> <code>1</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> allows destroying the stream if the signal is
aborted.</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> a promise evaluating to <code>true</code> if <code>fn</code> returned a truthy
value for at least one of the chunks.</li>
</ul>
<p>This method is similar to <code>Array.prototype.some</code> and calls <code>fn</code> on each chunk
in the stream until the awaited return value is <code>true</code> (or any truthy value).
Once an <code>fn</code> call on a chunk awaited return value is truthy, the stream is
destroyed and the promise is fulfilled with <code>true</code>. If none of the <code>fn</code>
calls on the chunks return a truthy value, the promise is fulfilled with
<code>false</code>.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;
<span class="hljs-keyword">import</span> { stat } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;

<span class="hljs-comment">// With a synchronous predicate.</span>
<span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">some</span>(<span class="hljs-function">(<span class="hljs-params">x</span>) =></span> x > <span class="hljs-number">2</span>); <span class="hljs-comment">// true</span>
<span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">some</span>(<span class="hljs-function">(<span class="hljs-params">x</span>) =></span> x &#x3C; <span class="hljs-number">0</span>); <span class="hljs-comment">// false</span>

<span class="hljs-comment">// With an asynchronous predicate, making at most 2 file checks at a time.</span>
<span class="hljs-keyword">const</span> anyBigFile = <span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([
  <span class="hljs-string">'file1'</span>,
  <span class="hljs-string">'file2'</span>,
  <span class="hljs-string">'file3'</span>,
]).<span class="hljs-title function_">some</span>(<span class="hljs-keyword">async</span> (fileName) => {
  <span class="hljs-keyword">const</span> stats = <span class="hljs-keyword">await</span> <span class="hljs-title function_">stat</span>(fileName);
  <span class="hljs-keyword">return</span> stats.<span class="hljs-property">size</span> > <span class="hljs-number">1024</span> * <span class="hljs-number">1024</span>;
}, { <span class="hljs-attr">concurrency</span>: <span class="hljs-number">2</span> });
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(anyBigFile); <span class="hljs-comment">// `true` if any file in the list is bigger than 1MB</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'done'</span>); <span class="hljs-comment">// Stream has finished</span></code> <button class="copy-button">copy</button></pre>
<h6><code>readable.find(fn[, options])</code><span><a class="mark" href="#all_stream_readablefindfn-options" id="all_stream_readablefindfn-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_find_fn_options"></a></h6>
<div class="api_metadata">
<span>Added in: v17.5.0, v16.17.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<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://tc39.es/ecma262/#sec-async-function-constructor" class="type">&#x3C;AsyncFunction></a> a function to call on each chunk of the stream.
<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> a chunk of data from the stream.</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>
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> aborted if the stream is destroyed allowing to
abort the <code>fn</code> call early.</li>
</ul>
</li>
</ul>
</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>
<ul>
<li><code>concurrency</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> the maximum concurrent invocation of <code>fn</code> to call
on the stream at once. <strong>Default:</strong> <code>1</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> allows destroying the stream if the signal is
aborted.</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> a promise evaluating to the first chunk for which <code>fn</code>
evaluated with a truthy value, or <code>undefined</code> if no element was found.</li>
</ul>
<p>This method is similar to <code>Array.prototype.find</code> and calls <code>fn</code> on each chunk
in the stream to find a chunk with a truthy value for <code>fn</code>. Once an <code>fn</code> call's
awaited return value is truthy, the stream is destroyed and the promise is
fulfilled with value for which <code>fn</code> returned a truthy value. If all of the
<code>fn</code> calls on the chunks return a falsy value, the promise is fulfilled with
<code>undefined</code>.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;
<span class="hljs-keyword">import</span> { stat } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;

<span class="hljs-comment">// With a synchronous predicate.</span>
<span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">find</span>(<span class="hljs-function">(<span class="hljs-params">x</span>) =></span> x > <span class="hljs-number">2</span>); <span class="hljs-comment">// 3</span>
<span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">find</span>(<span class="hljs-function">(<span class="hljs-params">x</span>) =></span> x > <span class="hljs-number">0</span>); <span class="hljs-comment">// 1</span>
<span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">find</span>(<span class="hljs-function">(<span class="hljs-params">x</span>) =></span> x > <span class="hljs-number">10</span>); <span class="hljs-comment">// undefined</span>

<span class="hljs-comment">// With an asynchronous predicate, making at most 2 file checks at a time.</span>
<span class="hljs-keyword">const</span> foundBigFile = <span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([
  <span class="hljs-string">'file1'</span>,
  <span class="hljs-string">'file2'</span>,
  <span class="hljs-string">'file3'</span>,
]).<span class="hljs-title function_">find</span>(<span class="hljs-keyword">async</span> (fileName) => {
  <span class="hljs-keyword">const</span> stats = <span class="hljs-keyword">await</span> <span class="hljs-title function_">stat</span>(fileName);
  <span class="hljs-keyword">return</span> stats.<span class="hljs-property">size</span> > <span class="hljs-number">1024</span> * <span class="hljs-number">1024</span>;
}, { <span class="hljs-attr">concurrency</span>: <span class="hljs-number">2</span> });
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(foundBigFile); <span class="hljs-comment">// File name of large file, if any file in the list is bigger than 1MB</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'done'</span>); <span class="hljs-comment">// Stream has finished</span></code> <button class="copy-button">copy</button></pre>
<h6><code>readable.every(fn[, options])</code><span><a class="mark" href="#all_stream_readableeveryfn-options" id="all_stream_readableeveryfn-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_every_fn_options"></a></h6>
<div class="api_metadata">
<span>Added in: v17.5.0, v16.15.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<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://tc39.es/ecma262/#sec-async-function-constructor" class="type">&#x3C;AsyncFunction></a> a function to call on each chunk of the stream.
<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> a chunk of data from the stream.</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>
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> aborted if the stream is destroyed allowing to
abort the <code>fn</code> call early.</li>
</ul>
</li>
</ul>
</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>
<ul>
<li><code>concurrency</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> the maximum concurrent invocation of <code>fn</code> to call
on the stream at once. <strong>Default:</strong> <code>1</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> allows destroying the stream if the signal is
aborted.</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> a promise evaluating to <code>true</code> if <code>fn</code> returned a truthy
value for all of the chunks.</li>
</ul>
<p>This method is similar to <code>Array.prototype.every</code> and calls <code>fn</code> on each chunk
in the stream to check if all awaited return values are truthy value for <code>fn</code>.
Once an <code>fn</code> call on a chunk awaited return value is falsy, the stream is
destroyed and the promise is fulfilled with <code>false</code>. If all of the <code>fn</code> calls
on the chunks return a truthy value, the promise is fulfilled with <code>true</code>.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;
<span class="hljs-keyword">import</span> { stat } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;

<span class="hljs-comment">// With a synchronous predicate.</span>
<span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">every</span>(<span class="hljs-function">(<span class="hljs-params">x</span>) =></span> x > <span class="hljs-number">2</span>); <span class="hljs-comment">// false</span>
<span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">every</span>(<span class="hljs-function">(<span class="hljs-params">x</span>) =></span> x > <span class="hljs-number">0</span>); <span class="hljs-comment">// true</span>

<span class="hljs-comment">// With an asynchronous predicate, making at most 2 file checks at a time.</span>
<span class="hljs-keyword">const</span> allBigFiles = <span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([
  <span class="hljs-string">'file1'</span>,
  <span class="hljs-string">'file2'</span>,
  <span class="hljs-string">'file3'</span>,
]).<span class="hljs-title function_">every</span>(<span class="hljs-keyword">async</span> (fileName) => {
  <span class="hljs-keyword">const</span> stats = <span class="hljs-keyword">await</span> <span class="hljs-title function_">stat</span>(fileName);
  <span class="hljs-keyword">return</span> stats.<span class="hljs-property">size</span> > <span class="hljs-number">1024</span> * <span class="hljs-number">1024</span>;
}, { <span class="hljs-attr">concurrency</span>: <span class="hljs-number">2</span> });
<span class="hljs-comment">// `true` if all files in the list are bigger than 1MiB</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(allBigFiles);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'done'</span>); <span class="hljs-comment">// Stream has finished</span></code> <button class="copy-button">copy</button></pre>
<h6><code>readable.flatMap(fn[, options])</code><span><a class="mark" href="#all_stream_readableflatmapfn-options" id="all_stream_readableflatmapfn-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_flatmap_fn_options"></a></h6>
<div class="api_metadata">
<span>Added in: v17.5.0, v16.15.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<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://tc39.es/proposal-async-iteration/#sec-asyncgeneratorfunction-constructor" class="type">&#x3C;AsyncGeneratorFunction></a> | <a href="https://tc39.es/ecma262/#sec-async-function-constructor" class="type">&#x3C;AsyncFunction></a> a function to map over
every chunk in the stream.
<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> a chunk of data from the stream.</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>
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> aborted if the stream is destroyed allowing to
abort the <code>fn</code> call early.</li>
</ul>
</li>
</ul>
</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>
<ul>
<li><code>concurrency</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> the maximum concurrent invocation of <code>fn</code> to call
on the stream at once. <strong>Default:</strong> <code>1</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> allows destroying the stream if the signal is
aborted.</li>
</ul>
</li>
<li>Returns: <a href="#all_stream_class-streamreadable" class="type">&#x3C;Readable></a> a stream flat-mapped with the function <code>fn</code>.</li>
</ul>
<p>This method returns a new stream by applying the given callback to each
chunk of the stream and then flattening the result.</p>
<p>It is possible to return a stream or another iterable or async iterable from
<code>fn</code> and the result streams will be merged (flattened) into the returned
stream.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;
<span class="hljs-keyword">import</span> { createReadStream } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-comment">// With a synchronous mapper.</span>
<span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">flatMap</span>(<span class="hljs-function">(<span class="hljs-params">x</span>) =></span> [x, x])) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk); <span class="hljs-comment">// 1, 1, 2, 2, 3, 3, 4, 4</span>
}
<span class="hljs-comment">// With an asynchronous mapper, combine the contents of 4 files</span>
<span class="hljs-keyword">const</span> concatResult = <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([
  <span class="hljs-string">'./1.mjs'</span>,
  <span class="hljs-string">'./2.mjs'</span>,
  <span class="hljs-string">'./3.mjs'</span>,
  <span class="hljs-string">'./4.mjs'</span>,
]).<span class="hljs-title function_">flatMap</span>(<span class="hljs-function">(<span class="hljs-params">fileName</span>) =></span> <span class="hljs-title function_">createReadStream</span>(fileName));
<span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> result <span class="hljs-keyword">of</span> concatResult) {
  <span class="hljs-comment">// This will contain the contents (all chunks) of all 4 files</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result);
}</code> <button class="copy-button">copy</button></pre>
<h6><code>readable.drop(limit[, options])</code><span><a class="mark" href="#all_stream_readabledroplimit-options" id="all_stream_readabledroplimit-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_drop_limit_options"></a></h6>
<div class="api_metadata">
<span>Added in: v17.5.0, v16.15.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>limit</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> the number of chunks to drop from the readable.</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>
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> allows destroying the stream if the signal is
aborted.</li>
</ul>
</li>
<li>Returns: <a href="#all_stream_class-streamreadable" class="type">&#x3C;Readable></a> a stream with <code>limit</code> chunks dropped.</li>
</ul>
<p>This method returns a new stream with the first <code>limit</code> chunks dropped.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;

<span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">drop</span>(<span class="hljs-number">2</span>).<span class="hljs-title function_">toArray</span>(); <span class="hljs-comment">// [3, 4]</span></code> <button class="copy-button">copy</button></pre>
<h6><code>readable.take(limit[, options])</code><span><a class="mark" href="#all_stream_readabletakelimit-options" id="all_stream_readabletakelimit-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_take_limit_options"></a></h6>
<div class="api_metadata">
<span>Added in: v17.5.0, v16.15.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>limit</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> the number of chunks to take from the readable.</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>
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> allows destroying the stream if the signal is
aborted.</li>
</ul>
</li>
<li>Returns: <a href="#all_stream_class-streamreadable" class="type">&#x3C;Readable></a> a stream with <code>limit</code> chunks taken.</li>
</ul>
<p>This method returns a new stream with the first <code>limit</code> chunks.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;

<span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]).<span class="hljs-title function_">take</span>(<span class="hljs-number">2</span>).<span class="hljs-title function_">toArray</span>(); <span class="hljs-comment">// [1, 2]</span></code> <button class="copy-button">copy</button></pre>
<h6><code>readable.asIndexedPairs([options])</code><span><a class="mark" href="#all_stream_readableasindexedpairsoptions" id="all_stream_readableasindexedpairsoptions">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_asindexedpairs_options"></a></h6>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.3.0</td>
<td><p>Using the <code>asIndexedPairs</code> method emits a runtime warning that it will be removed in a future version.</p></td></tr>
<tr><td>v17.5.0, v16.15.0</td>
<td><p><span>Added in: v17.5.0, v16.15.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<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>
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> allows destroying the stream if the signal is
aborted.</li>
</ul>
</li>
<li>Returns: <a href="#all_stream_class-streamreadable" class="type">&#x3C;Readable></a> a stream of indexed pairs.</li>
</ul>
<p>This method returns a new stream with chunks of the underlying stream paired
with a counter in the form <code>[index, chunk]</code>. The first index value is 0 and it
increases by 1 for each chunk produced.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;

<span class="hljs-keyword">const</span> pairs = <span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>]).<span class="hljs-title function_">asIndexedPairs</span>().<span class="hljs-title function_">toArray</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(pairs); <span class="hljs-comment">// [[0, 'a'], [1, 'b'], [2, 'c']]</span></code> <button class="copy-button">copy</button></pre>
<h6><code>readable.reduce(fn[, initial[, options]])</code><span><a class="mark" href="#all_stream_readablereducefn-initial-options" id="all_stream_readablereducefn-initial-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_reduce_fn_initial_options"></a></h6>
<div class="api_metadata">
<span>Added in: v17.5.0, v16.15.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<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://tc39.es/ecma262/#sec-async-function-constructor" class="type">&#x3C;AsyncFunction></a> a reducer function to call over every chunk
in the stream.
<ul>
<li><code>previous</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> the value obtained from the last call to <code>fn</code> or the
<code>initial</code> value if specified or the first chunk of the stream otherwise.</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> a chunk of data from the stream.</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>
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> aborted if the stream is destroyed allowing to
abort the <code>fn</code> call early.</li>
</ul>
</li>
</ul>
</li>
<li><code>initial</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> the initial value to use in the reduction.</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>
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> allows destroying the stream if the signal is
aborted.</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> a promise for the final value of the reduction.</li>
</ul>
<p>This method calls <code>fn</code> on each chunk of the stream in order, passing it the
result from the calculation on the previous element. It returns a promise for
the final value of the reduction.</p>
<p>If no <code>initial</code> value is supplied the first chunk of the stream is used as the
initial value. If the stream is empty, the promise is rejected with a
<code>TypeError</code> with the <code>ERR_INVALID_ARGS</code> code property.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;
<span class="hljs-keyword">import</span> { readdir, stat } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
<span class="hljs-keyword">import</span> { join } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:path'</span>;

<span class="hljs-keyword">const</span> directoryPath = <span class="hljs-string">'./src'</span>;
<span class="hljs-keyword">const</span> filesInDir = <span class="hljs-keyword">await</span> <span class="hljs-title function_">readdir</span>(directoryPath);

<span class="hljs-keyword">const</span> folderSize = <span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>(filesInDir)
  .<span class="hljs-title function_">reduce</span>(<span class="hljs-keyword">async</span> (totalSize, file) => {
    <span class="hljs-keyword">const</span> { size } = <span class="hljs-keyword">await</span> <span class="hljs-title function_">stat</span>(<span class="hljs-title function_">join</span>(directoryPath, file));
    <span class="hljs-keyword">return</span> totalSize + size;
  }, <span class="hljs-number">0</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(folderSize);</code> <button class="copy-button">copy</button></pre>
<p>The reducer function iterates the stream element-by-element which means that
there is no <code>concurrency</code> parameter or parallelism. To perform a <code>reduce</code>
concurrently, you can extract the async function to <a href="#all_stream_readablemapfn-options"><code>readable.map</code></a> method.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;
<span class="hljs-keyword">import</span> { readdir, stat } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
<span class="hljs-keyword">import</span> { join } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:path'</span>;

<span class="hljs-keyword">const</span> directoryPath = <span class="hljs-string">'./src'</span>;
<span class="hljs-keyword">const</span> filesInDir = <span class="hljs-keyword">await</span> <span class="hljs-title function_">readdir</span>(directoryPath);

<span class="hljs-keyword">const</span> folderSize = <span class="hljs-keyword">await</span> <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>(filesInDir)
  .<span class="hljs-title function_">map</span>(<span class="hljs-function">(<span class="hljs-params">file</span>) =></span> <span class="hljs-title function_">stat</span>(<span class="hljs-title function_">join</span>(directoryPath, file)), { <span class="hljs-attr">concurrency</span>: <span class="hljs-number">2</span> })
  .<span class="hljs-title function_">reduce</span>(<span class="hljs-function">(<span class="hljs-params">totalSize, { size }</span>) =></span> totalSize + size, <span class="hljs-number">0</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(folderSize);</code> <button class="copy-button">copy</button></pre>
<h4>Duplex and transform streams<span><a class="mark" href="#all_stream_duplex-and-transform-streams" id="all_stream_duplex-and-transform-streams">#</a></span><a aria-hidden="true" class="legacy" id="stream_duplex_and_transform_streams"></a></h4>
<h5>Class: <code>stream.Duplex</code><span><a class="mark" href="#all_stream_class-streamduplex" id="all_stream_class-streamduplex">#</a></span><a aria-hidden="true" class="legacy" id="stream_class_stream_duplex"></a></h5>
<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="#all_stream_class-streamreadable"><code>Readable</code></a> and
<a href="#all_stream_class-streamwritable"><code>Writable</code></a> interfaces.</p>
<p>Examples of <code>Duplex</code> streams include:</p>
<ul>
<li><a href="#all_net_class-netsocket">TCP sockets</a></li>
<li><a href="zlib.html">zlib streams</a></li>
<li><a href="crypto.html">crypto streams</a></li>
</ul>
<h6><code>duplex.allowHalfOpen</code><span><a class="mark" href="#all_stream_duplexallowhalfopen" id="all_stream_duplexallowhalfopen">#</a></span><a aria-hidden="true" class="legacy" id="stream_duplex_allowhalfopen"></a></h6>
<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/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>If <code>false</code> then the stream will automatically end the writable side when the
readable side ends. Set initially by the <code>allowHalfOpen</code> constructor option,
which defaults to <code>true</code>.</p>
<p>This can be changed manually to change the half-open behavior of an existing
<code>Duplex</code> stream instance, but must be changed before the <code>'end'</code> event is
emitted.</p>
<h5>Class: <code>stream.Transform</code><span><a class="mark" href="#all_stream_class-streamtransform" id="all_stream_class-streamtransform">#</a></span><a aria-hidden="true" class="legacy" id="stream_class_stream_transform"></a></h5>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div>

<p>Transform streams are <a href="#all_stream_class-streamduplex"><code>Duplex</code></a> streams where the output is in some way
related to the input. Like all <a href="#all_stream_class-streamduplex"><code>Duplex</code></a> streams, <code>Transform</code> streams
implement both the <a href="#all_stream_class-streamreadable"><code>Readable</code></a> and <a href="#all_stream_class-streamwritable"><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>
<h6><code>transform.destroy([error])</code><span><a class="mark" href="#all_stream_transformdestroyerror" id="all_stream_transformdestroyerror">#</a></span><a aria-hidden="true" class="legacy" id="stream_transform_destroy_error"></a></h6>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.0.0</td>
<td><p>Work as a no-op on a stream that has already been destroyed.</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>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="#all_stream_readable_destroyerr-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>
<p>Once <code>destroy()</code> has been called, any further calls will be a no-op and no
further errors except from <code>_destroy()</code> may be emitted as <code>'error'</code>.</p>
<h5><code>stream.duplexPair([options])</code><span><a class="mark" href="#all_stream_streamduplexpairoptions" id="all_stream_streamduplexpairoptions">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_duplexpair_options"></a></h5>
<div class="api_metadata">
<span>Added in: v20.17.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 value to pass to both <a href="#all_stream_class-streamduplex"><code>Duplex</code></a> constructors,
to set options such as buffering.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type">&#x3C;Array></a> of two <a href="#all_stream_class-streamduplex"><code>Duplex</code></a> instances.</li>
</ul>
<p>The utility function <code>duplexPair</code> returns an Array with two items,
each being a <code>Duplex</code> stream connected to the other side:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> [ sideA, sideB ] = <span class="hljs-title function_">duplexPair</span>();</code> <button class="copy-button">copy</button></pre>
<p>Whatever is written to one stream is made readable on the other. It provides
behavior analogous to a network connection, where the data written by the client
becomes readable by the server, and vice-versa.</p>
<p>The Duplex streams are symmetrical; one or the other may be used without any
difference in behavior.</p>
<h4><code>stream.finished(stream[, options], callback)</code><span><a class="mark" href="#all_stream_streamfinishedstream-options-callback" id="all_stream_streamfinishedstream-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_finished_stream_options_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.5.0</td>
<td><p>Added support for <code>ReadableStream</code> and <code>WritableStream</code>.</p></td></tr>
<tr><td>v15.11.0</td>
<td><p>The <code>signal</code> option was added.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>The <code>finished(stream, cb)</code> will wait for the <code>'close'</code> event before invoking the callback. The implementation tries to detect legacy streams and only apply this behavior to streams which are expected to emit <code>'close'</code>.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>Emitting <code>'close'</code> before <code>'end'</code> on a <code>Readable</code> stream will cause an <code>ERR_STREAM_PREMATURE_CLOSE</code> error.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>Callback will be invoked on streams which have already finished before the call to <code>finished(stream, cb)</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>stream</code> <a href="#all_stream_stream" class="type">&#x3C;Stream></a> | <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a> | <a href="#all_webstreams_class-writablestream" class="type">&#x3C;WritableStream></a> A readable and/or writable
stream/webstream.</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>
<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>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> allows aborting the wait for the stream finish. The
underlying stream will <em>not</em> be aborted if the signal is aborted. The
callback will get called with an <code>AbortError</code>. All registered
listeners added by this function will also be removed.</li>
<li><code>cleanup</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> remove all registered stream listeners.
<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> 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"><span class="hljs-keyword">const</span> { finished } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);

<span class="hljs-keyword">const</span> rs = fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'archive.tar'</span>);

<span class="hljs-title function_">finished</span>(rs, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'Stream failed.'</span>, err);
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Stream is done reading.'</span>);
  }
});

rs.<span class="hljs-title function_">resume</span>(); <span class="hljs-comment">// Drain the stream.</span></code> <button class="copy-button">copy</button></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 provides <a href="#all_stream_streamfinishedstream-options">promise version</a>.</p>
<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"><span class="hljs-keyword">const</span> cleanup = <span class="hljs-title function_">finished</span>(rs, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-title function_">cleanup</span>();
  <span class="hljs-comment">// ...</span>
});</code> <button class="copy-button">copy</button></pre>
<h4><code>stream.pipeline(source[, ...transforms], destination, callback)</code><span><a class="mark" href="#all_stream_streampipelinesource-transforms-destination-callback" id="all_stream_streampipelinesource-transforms-destination-callback">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_pipeline_source_transforms_destination_callback"></a></h4>
<h4><code>stream.pipeline(streams, callback)</code><span><a class="mark" href="#all_stream_streampipelinestreams-callback" id="all_stream_streampipelinestreams-callback">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_pipeline_streams_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.7.0</td>
<td><p>Added support for webstreams.</p></td></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>The <code>pipeline(..., cb)</code> will wait for the <code>'close'</code> event before invoking the callback. The implementation tries to detect legacy streams and only apply this behavior to streams which are expected to emit <code>'close'</code>.</p></td></tr>
<tr><td>v13.10.0</td>
<td><p>Add support for async generators.</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>streams</code> <a href="#all_stream_stream" class="type">&#x3C;Stream[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol" class="type">&#x3C;Iterable[]></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type">&#x3C;AsyncIterable[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function[]></a> | <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream[]></a> | <a href="#all_webstreams_class-writablestream" class="type">&#x3C;WritableStream[]></a> | <a href="#all_webstreams_class-transformstream" class="type">&#x3C;TransformStream[]></a></li>
<li><code>source</code> <a href="#all_stream_stream" class="type">&#x3C;Stream></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol" class="type">&#x3C;Iterable></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type">&#x3C;AsyncIterable></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> | <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a>
<ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol" class="type">&#x3C;Iterable></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type">&#x3C;AsyncIterable></a></li>
</ul>
</li>
<li><code>...transforms</code> <a href="#all_stream_stream" class="type">&#x3C;Stream></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> | <a href="#all_webstreams_class-transformstream" class="type">&#x3C;TransformStream></a>
<ul>
<li><code>source</code> <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type">&#x3C;AsyncIterable></a></li>
<li>Returns: <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type">&#x3C;AsyncIterable></a></li>
</ul>
</li>
<li><code>destination</code> <a href="#all_stream_stream" class="type">&#x3C;Stream></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> | <a href="#all_webstreams_class-writablestream" class="type">&#x3C;WritableStream></a>
<ul>
<li><code>source</code> <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type">&#x3C;AsyncIterable></a></li>
<li>Returns: <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type">&#x3C;AsyncIterable></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></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> Called when the pipeline is fully done.
<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>val</code> Resolved value of <code>Promise</code> returned by <code>destination</code>.</li>
</ul>
</li>
<li>Returns: <a href="#all_stream_stream" class="type">&#x3C;Stream></a></li>
</ul>
<p>A module method to pipe between streams and generators forwarding errors and
properly cleaning up and provide a callback when the pipeline is complete.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { pipeline } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> zlib = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:zlib'</span>);

<span class="hljs-comment">// Use the pipeline API to easily pipe a series of streams</span>
<span class="hljs-comment">// together and get notified when the pipeline is fully done.</span>

<span class="hljs-comment">// A pipeline to gzip a potentially huge tar file efficiently:</span>

<span class="hljs-title function_">pipeline</span>(
  fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'archive.tar'</span>),
  zlib.<span class="hljs-title function_">createGzip</span>(),
  fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'archive.tar.gz'</span>),
  <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
    <span class="hljs-keyword">if</span> (err) {
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'Pipeline failed.'</span>, err);
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Pipeline succeeded.'</span>);
    }
  },
);</code> <button class="copy-button">copy</button></pre>
<p>The <code>pipeline</code> API provides a <a href="#all_stream_streampipelinesource-transforms-destination-options">promise version</a>.</p>
<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. If the last
stream is readable, dangling event listeners will be removed so that the last
stream can be consumed later.</p>
<p><code>stream.pipeline()</code> closes all the streams when an error is raised.
The <code>IncomingRequest</code> usage with <code>pipeline</code> could lead to an unexpected behavior
once it would destroy the socket without sending the expected response.
See the example below:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);
<span class="hljs-keyword">const</span> { pipeline } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);

<span class="hljs-keyword">const</span> server = http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
  <span class="hljs-keyword">const</span> fileStream = fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'./fileNotExist.txt'</span>);
  <span class="hljs-title function_">pipeline</span>(fileStream, res, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
    <span class="hljs-keyword">if</span> (err) {
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(err); <span class="hljs-comment">// No such file</span>
      <span class="hljs-comment">// this message can't be sent once `pipeline` already destroyed the socket</span>
      <span class="hljs-keyword">return</span> res.<span class="hljs-title function_">end</span>(<span class="hljs-string">'error!!!'</span>);
    }
  });
});</code> <button class="copy-button">copy</button></pre>
<h4><code>stream.compose(...streams)</code><span><a class="mark" href="#all_stream_streamcomposestreams" id="all_stream_streamcomposestreams">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_compose_streams"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.10.0</td>
<td><p>Added support for stream class.</p></td></tr>
<tr><td>v19.8.0, v18.16.0</td>
<td><p>Added support for webstreams.</p></td></tr>
<tr><td>v16.9.0</td>
<td><p><span>Added in: v16.9.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - <code>stream.compose</code> is experimental.</div><p></p>
<ul>
<li><code>streams</code> <a href="#all_stream_stream" class="type">&#x3C;Stream[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol" class="type">&#x3C;Iterable[]></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type">&#x3C;AsyncIterable[]></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function[]></a> | <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream[]></a> | <a href="#all_webstreams_class-writablestream" class="type">&#x3C;WritableStream[]></a> | <a href="#all_webstreams_class-transformstream" class="type">&#x3C;TransformStream[]></a> | <a href="#all_stream_class-streamduplex" class="type">&#x3C;Duplex[]></a> | <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="#all_stream_class-streamduplex" class="type">&#x3C;stream.Duplex></a></li>
</ul>
<p>Combines two or more streams into a <code>Duplex</code> stream that writes to the
first stream and reads from the last. Each provided stream is piped into
the next, using <code>stream.pipeline</code>. If any of the streams error then all
are destroyed, including the outer <code>Duplex</code> stream.</p>
<p>Because <code>stream.compose</code> returns a new stream that in turn can (and
should) be piped into other streams, it enables composition. In contrast,
when passing streams to <code>stream.pipeline</code>, typically the first stream is
a readable stream and the last a writable stream, forming a closed
circuit.</p>
<p>If passed a <code>Function</code> it must be a factory method taking a <code>source</code>
<code>Iterable</code>.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { compose, <span class="hljs-title class_">Transform</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;

<span class="hljs-keyword">const</span> removeSpaces = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Transform</span>({
  <span class="hljs-title function_">transform</span>(<span class="hljs-params">chunk, encoding, callback</span>) {
    <span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-title class_">String</span>(chunk).<span class="hljs-title function_">replace</span>(<span class="hljs-string">' '</span>, <span class="hljs-string">''</span>));
  },
});

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>* <span class="hljs-title function_">toUpper</span>(<span class="hljs-params">source</span>) {
  <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> source) {
    <span class="hljs-keyword">yield</span> <span class="hljs-title class_">String</span>(chunk).<span class="hljs-title function_">toUpperCase</span>();
  }
}

<span class="hljs-keyword">let</span> res = <span class="hljs-string">''</span>;
<span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> buf <span class="hljs-keyword">of</span> <span class="hljs-title function_">compose</span>(removeSpaces, toUpper).<span class="hljs-title function_">end</span>(<span class="hljs-string">'hello world'</span>)) {
  res += buf;
}

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(res); <span class="hljs-comment">// prints 'HELLOWORLD'</span></code> <button class="copy-button">copy</button></pre>
<p><code>stream.compose</code> can be used to convert async iterables, generators and
functions into streams.</p>
<ul>
<li><code>AsyncIterable</code> converts into a readable <code>Duplex</code>. Cannot yield
<code>null</code>.</li>
<li><code>AsyncGeneratorFunction</code> converts into a readable/writable transform <code>Duplex</code>.
Must take a source <code>AsyncIterable</code> as first parameter. Cannot yield
<code>null</code>.</li>
<li><code>AsyncFunction</code> converts into a writable <code>Duplex</code>. Must return
either <code>null</code> or <code>undefined</code>.</li>
</ul>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { compose } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;
<span class="hljs-keyword">import</span> { finished } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/promises'</span>;

<span class="hljs-comment">// Convert AsyncIterable into readable Duplex.</span>
<span class="hljs-keyword">const</span> s1 = <span class="hljs-title function_">compose</span>(<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>*() {
  <span class="hljs-keyword">yield</span> <span class="hljs-string">'Hello'</span>;
  <span class="hljs-keyword">yield</span> <span class="hljs-string">'World'</span>;
}());

<span class="hljs-comment">// Convert AsyncGenerator into transform Duplex.</span>
<span class="hljs-keyword">const</span> s2 = <span class="hljs-title function_">compose</span>(<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>*(source) {
  <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> source) {
    <span class="hljs-keyword">yield</span> <span class="hljs-title class_">String</span>(chunk).<span class="hljs-title function_">toUpperCase</span>();
  }
});

<span class="hljs-keyword">let</span> res = <span class="hljs-string">''</span>;

<span class="hljs-comment">// Convert AsyncFunction into writable Duplex.</span>
<span class="hljs-keyword">const</span> s3 = <span class="hljs-title function_">compose</span>(<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>(<span class="hljs-params">source</span>) {
  <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> source) {
    res += chunk;
  }
});

<span class="hljs-keyword">await</span> <span class="hljs-title function_">finished</span>(<span class="hljs-title function_">compose</span>(s1, s2, s3));

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(res); <span class="hljs-comment">// prints 'HELLOWORLD'</span></code> <button class="copy-button">copy</button></pre>
<p>See <a href="#all_stream_readablecomposestream-options"><code>readable.compose(stream)</code></a> for <code>stream.compose</code> as operator.</p>
<h4><code>stream.Readable.from(iterable[, options])</code><span><a class="mark" href="#all_stream_streamreadablefromiterable-options" id="all_stream_streamreadablefromiterable-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_readable_from_iterable_options"></a></h4>
<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="#all_stream_class-streamreadable" 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"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Readable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> * <span class="hljs-title function_">generate</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">yield</span> <span class="hljs-string">'hello'</span>;
  <span class="hljs-keyword">yield</span> <span class="hljs-string">'streams'</span>;
}

<span class="hljs-keyword">const</span> readable = <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>(<span class="hljs-title function_">generate</span>());

readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk);
});</code> <button class="copy-button">copy</button></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>
<p>If an <code>Iterable</code> object containing promises is passed as an argument,
it might result in unhandled rejection.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Readable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);

<span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>([
  <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =></span> <span class="hljs-built_in">setTimeout</span>(<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'1'</span>), <span class="hljs-number">1500</span>)),
  <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">_, reject</span>) =></span> <span class="hljs-built_in">setTimeout</span>(<span class="hljs-title function_">reject</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'2'</span>)), <span class="hljs-number">1000</span>)), <span class="hljs-comment">// Unhandled rejection</span>
]);</code> <button class="copy-button">copy</button></pre>
<h4><code>stream.Readable.fromWeb(readableStream[, options])</code><span><a class="mark" href="#all_stream_streamreadablefromwebreadablestream-options" id="all_stream_streamreadablefromwebreadablestream-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_readable_fromweb_readablestream_options"></a></h4>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>readableStream</code> <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></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>
<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><code>highWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></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></li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a></li>
</ul>
</li>
<li>Returns: <a href="#all_stream_class-streamreadable" class="type">&#x3C;stream.Readable></a></li>
</ul>
<h4><code>stream.Readable.isDisturbed(stream)</code><span><a class="mark" href="#all_stream_streamreadableisdisturbedstream" id="all_stream_streamreadableisdisturbedstream">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_readable_isdisturbed_stream"></a></h4>
<div class="api_metadata">
<span>Added in: v16.8.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>stream</code> <a href="#all_stream_class-streamreadable" class="type">&#x3C;stream.Readable></a> | <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a></li>
<li>Returns: <code>boolean</code></li>
</ul>
<p>Returns whether the stream has been read from or cancelled.</p>
<h4><code>stream.isErrored(stream)</code><span><a class="mark" href="#all_stream_streamiserroredstream" id="all_stream_streamiserroredstream">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_iserrored_stream"></a></h4>
<div class="api_metadata">
<span>Added in: v17.3.0, v16.14.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>stream</code> <a href="#all_stream_class-streamreadable" class="type">&#x3C;Readable></a> | <a href="#all_stream_class-streamwritable" class="type">&#x3C;Writable></a> | <a href="#all_stream_class-streamduplex" class="type">&#x3C;Duplex></a> | <a href="#all_webstreams_class-writablestream" class="type">&#x3C;WritableStream></a> | <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></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 whether the stream has encountered an error.</p>
<h4><code>stream.isReadable(stream)</code><span><a class="mark" href="#all_stream_streamisreadablestream" id="all_stream_streamisreadablestream">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_isreadable_stream"></a></h4>
<div class="api_metadata">
<span>Added in: v17.4.0, v16.14.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>stream</code> <a href="#all_stream_class-streamreadable" class="type">&#x3C;Readable></a> | <a href="#all_stream_class-streamduplex" class="type">&#x3C;Duplex></a> | <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></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 whether the stream is readable.</p>
<h4><code>stream.Readable.toWeb(streamReadable[, options])</code><span><a class="mark" href="#all_stream_streamreadabletowebstreamreadable-options" id="all_stream_streamreadabletowebstreamreadable-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_readable_toweb_streamreadable_options"></a></h4>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>streamReadable</code> <a href="#all_stream_class-streamreadable" class="type">&#x3C;stream.Readable></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>
<ul>
<li><code>strategy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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 internal queue size (of the created
<code>ReadableStream</code>) before backpressure is applied in reading from the given
<code>stream.Readable</code>. If no value is provided, it will be taken from the
given <code>stream.Readable</code>.</li>
<li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> A function that size of the given chunk of data.
If no value is provided, the size will be <code>1</code> for all the chunks.
<ul>
<li><code>chunk</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#Number_type" class="type">&#x3C;number></a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li>Returns: <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a></li>
</ul>
<h4><code>stream.Writable.fromWeb(writableStream[, options])</code><span><a class="mark" href="#all_stream_streamwritablefromwebwritablestream-options" id="all_stream_streamwritablefromwebwritablestream-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_writable_fromweb_writablestream_options"></a></h4>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>writableStream</code> <a href="#all_webstreams_class-writablestream" class="type">&#x3C;WritableStream></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>
<ul>
<li><code>decodeStrings</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
<li><code>highWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></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></li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a></li>
</ul>
</li>
<li>Returns: <a href="#all_stream_class-streamwritable" class="type">&#x3C;stream.Writable></a></li>
</ul>
<h4><code>stream.Writable.toWeb(streamWritable)</code><span><a class="mark" href="#all_stream_streamwritabletowebstreamwritable" id="all_stream_streamwritabletowebstreamwritable">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_writable_toweb_streamwritable"></a></h4>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>streamWritable</code> <a href="#all_stream_class-streamwritable" class="type">&#x3C;stream.Writable></a></li>
<li>Returns: <a href="#all_webstreams_class-writablestream" class="type">&#x3C;WritableStream></a></li>
</ul>
<h4><code>stream.Duplex.from(src)</code><span><a class="mark" href="#all_stream_streamduplexfromsrc" id="all_stream_streamduplexfromsrc">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_duplex_from_src"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.5.0</td>
<td><p>The <code>src</code> argument can now be a <code>ReadableStream</code> or <code>WritableStream</code>.</p></td></tr>
<tr><td>v16.8.0</td>
<td><p><span>Added in: v16.8.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>src</code> <a href="#all_stream_stream" class="type">&#x3C;Stream></a> | <a href="#all_buffer_class-blob" class="type">&#x3C;Blob></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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol" class="type">&#x3C;Iterable></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterable-interface" class="type">&#x3C;AsyncIterable></a> | <a href="https://tc39.es/proposal-async-iteration/#sec-asyncgeneratorfunction-constructor" class="type">&#x3C;AsyncGeneratorFunction></a> | <a href="https://tc39.es/ecma262/#sec-async-function-constructor" class="type">&#x3C;AsyncFunction></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> | <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a> | <a href="#all_webstreams_class-writablestream" class="type">&#x3C;WritableStream></a></li>
</ul>
<p>A utility method for creating duplex streams.</p>
<ul>
<li><code>Stream</code> converts writable stream into writable <code>Duplex</code> and readable stream
to <code>Duplex</code>.</li>
<li><code>Blob</code> converts into readable <code>Duplex</code>.</li>
<li><code>string</code> converts into readable <code>Duplex</code>.</li>
<li><code>ArrayBuffer</code> converts into readable <code>Duplex</code>.</li>
<li><code>AsyncIterable</code> converts into a readable <code>Duplex</code>. Cannot yield
<code>null</code>.</li>
<li><code>AsyncGeneratorFunction</code> converts into a readable/writable transform
<code>Duplex</code>. Must take a source <code>AsyncIterable</code> as first parameter. Cannot yield
<code>null</code>.</li>
<li><code>AsyncFunction</code> converts into a writable <code>Duplex</code>. Must return
either <code>null</code> or <code>undefined</code></li>
<li><code>Object ({ writable, readable })</code> converts <code>readable</code> and
<code>writable</code> into <code>Stream</code> and then combines them into <code>Duplex</code> where the
<code>Duplex</code> will write to the <code>writable</code> and read from the <code>readable</code>.</li>
<li><code>Promise</code> converts into readable <code>Duplex</code>. Value <code>null</code> is ignored.</li>
<li><code>ReadableStream</code> converts into readable <code>Duplex</code>.</li>
<li><code>WritableStream</code> converts into writable <code>Duplex</code>.</li>
<li>Returns: <a href="#all_stream_class-streamduplex" class="type">&#x3C;stream.Duplex></a></li>
</ul>
<p>If an <code>Iterable</code> object containing promises is passed as an argument,
it might result in unhandled rejection.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Duplex</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);

<span class="hljs-title class_">Duplex</span>.<span class="hljs-title function_">from</span>([
  <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =></span> <span class="hljs-built_in">setTimeout</span>(<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'1'</span>), <span class="hljs-number">1500</span>)),
  <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">_, reject</span>) =></span> <span class="hljs-built_in">setTimeout</span>(<span class="hljs-title function_">reject</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'2'</span>)), <span class="hljs-number">1000</span>)), <span class="hljs-comment">// Unhandled rejection</span>
]);</code> <button class="copy-button">copy</button></pre>
<h4><code>stream.Duplex.fromWeb(pair[, options])</code><span><a class="mark" href="#all_stream_streamduplexfromwebpair-options" id="all_stream_streamduplexfromwebpair-options">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_duplex_fromweb_pair_options"></a></h4>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>pair</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>readable</code> <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a></li>
<li><code>writable</code> <a href="#all_webstreams_class-writablestream" class="type">&#x3C;WritableStream></a></li>
</ul>
</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>
<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></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></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>highWaterMark</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></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></li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a></li>
</ul>
</li>
<li>Returns: <a href="#all_stream_class-streamduplex" class="type">&#x3C;stream.Duplex></a></li>
</ul>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Duplex</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;
<span class="hljs-keyword">import</span> {
  <span class="hljs-title class_">ReadableStream</span>,
  <span class="hljs-title class_">WritableStream</span>,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/web'</span>;

<span class="hljs-keyword">const</span> readable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ReadableStream</span>({
  <span class="hljs-title function_">start</span>(<span class="hljs-params">controller</span>) {
    controller.<span class="hljs-title function_">enqueue</span>(<span class="hljs-string">'world'</span>);
  },
});

<span class="hljs-keyword">const</span> writable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WritableStream</span>({
  <span class="hljs-title function_">write</span>(<span class="hljs-params">chunk</span>) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'writable'</span>, chunk);
  },
});

<span class="hljs-keyword">const</span> pair = {
  readable,
  writable,
};
<span class="hljs-keyword">const</span> duplex = <span class="hljs-title class_">Duplex</span>.<span class="hljs-title function_">fromWeb</span>(pair, { <span class="hljs-attr">encoding</span>: <span class="hljs-string">'utf8'</span>, <span class="hljs-attr">objectMode</span>: <span class="hljs-literal">true</span> });

duplex.<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello'</span>);

<span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> duplex) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'readable'</span>, chunk);
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Duplex</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> {
  <span class="hljs-title class_">ReadableStream</span>,
  <span class="hljs-title class_">WritableStream</span>,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/web'</span>);

<span class="hljs-keyword">const</span> readable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ReadableStream</span>({
  <span class="hljs-title function_">start</span>(<span class="hljs-params">controller</span>) {
    controller.<span class="hljs-title function_">enqueue</span>(<span class="hljs-string">'world'</span>);
  },
});

<span class="hljs-keyword">const</span> writable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WritableStream</span>({
  <span class="hljs-title function_">write</span>(<span class="hljs-params">chunk</span>) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'writable'</span>, chunk);
  },
});

<span class="hljs-keyword">const</span> pair = {
  readable,
  writable,
};
<span class="hljs-keyword">const</span> duplex = <span class="hljs-title class_">Duplex</span>.<span class="hljs-title function_">fromWeb</span>(pair, { <span class="hljs-attr">encoding</span>: <span class="hljs-string">'utf8'</span>, <span class="hljs-attr">objectMode</span>: <span class="hljs-literal">true</span> });

duplex.<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello'</span>);
duplex.<span class="hljs-title function_">once</span>(<span class="hljs-string">'readable'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'readable'</span>, duplex.<span class="hljs-title function_">read</span>()));</code><button class="copy-button">copy</button></pre>
<h4><code>stream.Duplex.toWeb(streamDuplex)</code><span><a class="mark" href="#all_stream_streamduplextowebstreamduplex" id="all_stream_streamduplextowebstreamduplex">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_duplex_toweb_streamduplex"></a></h4>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>streamDuplex</code> <a href="#all_stream_class-streamduplex" class="type">&#x3C;stream.Duplex></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>readable</code> <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a></li>
<li><code>writable</code> <a href="#all_webstreams_class-writablestream" class="type">&#x3C;WritableStream></a></li>
</ul>
</li>
</ul>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Duplex</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;

<span class="hljs-keyword">const</span> duplex = <span class="hljs-title class_">Duplex</span>({
  <span class="hljs-attr">objectMode</span>: <span class="hljs-literal">true</span>,
  <span class="hljs-title function_">read</span>(<span class="hljs-params"></span>) {
    <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(<span class="hljs-string">'world'</span>);
    <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(<span class="hljs-literal">null</span>);
  },
  <span class="hljs-title function_">write</span>(<span class="hljs-params">chunk, encoding, callback</span>) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'writable'</span>, chunk);
    <span class="hljs-title function_">callback</span>();
  },
});

<span class="hljs-keyword">const</span> { readable, writable } = <span class="hljs-title class_">Duplex</span>.<span class="hljs-title function_">toWeb</span>(duplex);
writable.<span class="hljs-title function_">getWriter</span>().<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello'</span>);

<span class="hljs-keyword">const</span> { value } = <span class="hljs-keyword">await</span> readable.<span class="hljs-title function_">getReader</span>().<span class="hljs-title function_">read</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'readable'</span>, value);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Duplex</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);

<span class="hljs-keyword">const</span> duplex = <span class="hljs-title class_">Duplex</span>({
  <span class="hljs-attr">objectMode</span>: <span class="hljs-literal">true</span>,
  <span class="hljs-title function_">read</span>(<span class="hljs-params"></span>) {
    <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(<span class="hljs-string">'world'</span>);
    <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(<span class="hljs-literal">null</span>);
  },
  <span class="hljs-title function_">write</span>(<span class="hljs-params">chunk, encoding, callback</span>) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'writable'</span>, chunk);
    <span class="hljs-title function_">callback</span>();
  },
});

<span class="hljs-keyword">const</span> { readable, writable } = <span class="hljs-title class_">Duplex</span>.<span class="hljs-title function_">toWeb</span>(duplex);
writable.<span class="hljs-title function_">getWriter</span>().<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello'</span>);

readable.<span class="hljs-title function_">getReader</span>().<span class="hljs-title function_">read</span>().<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">result</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'readable'</span>, result.<span class="hljs-property">value</span>);
});</code><button class="copy-button">copy</button></pre>
<h4><code>stream.addAbortSignal(signal, stream)</code><span><a class="mark" href="#all_stream_streamaddabortsignalsignal-stream" id="all_stream_streamaddabortsignalsignal-stream">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_addabortsignal_signal_stream"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.7.0</td>
<td><p>Added support for <code>ReadableStream</code> and <code>WritableStream</code>.</p></td></tr>
<tr><td>v15.4.0</td>
<td><p><span>Added in: v15.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> A signal representing possible cancellation</li>
<li><code>stream</code> <a href="#all_stream_stream" class="type">&#x3C;Stream></a> | <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a> | <a href="#all_webstreams_class-writablestream" class="type">&#x3C;WritableStream></a> A stream to attach a signal
to.</li>
</ul>
<p>Attaches an AbortSignal to a readable or writeable stream. This lets code
control stream destruction using an <code>AbortController</code>.</p>
<p>Calling <code>abort</code> on the <code>AbortController</code> corresponding to the passed
<code>AbortSignal</code> will behave the same way as calling <code>.destroy(new AbortError())</code>
on the stream, and <code>controller.error(new AbortError())</code> for webstreams.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);

<span class="hljs-keyword">const</span> controller = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
<span class="hljs-keyword">const</span> read = <span class="hljs-title function_">addAbortSignal</span>(
  controller.<span class="hljs-property">signal</span>,
  fs.<span class="hljs-title function_">createReadStream</span>((<span class="hljs-string">'object.json'</span>)),
);
<span class="hljs-comment">// Later, abort the operation closing the stream</span>
controller.<span class="hljs-title function_">abort</span>();</code> <button class="copy-button">copy</button></pre>
<p>Or using an <code>AbortSignal</code> with a readable stream as an async iterable:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> controller = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> controller.<span class="hljs-title function_">abort</span>(), <span class="hljs-number">10_000</span>); <span class="hljs-comment">// set a timeout</span>
<span class="hljs-keyword">const</span> stream = <span class="hljs-title function_">addAbortSignal</span>(
  controller.<span class="hljs-property">signal</span>,
  fs.<span class="hljs-title function_">createReadStream</span>((<span class="hljs-string">'object.json'</span>)),
);
(<span class="hljs-keyword">async</span> () => {
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> stream) {
      <span class="hljs-keyword">await</span> <span class="hljs-title function_">process</span>(chunk);
    }
  } <span class="hljs-keyword">catch</span> (e) {
    <span class="hljs-keyword">if</span> (e.<span class="hljs-property">name</span> === <span class="hljs-string">'AbortError'</span>) {
      <span class="hljs-comment">// The operation was cancelled</span>
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-keyword">throw</span> e;
    }
  }
})();</code> <button class="copy-button">copy</button></pre>
<p>Or using an <code>AbortSignal</code> with a ReadableStream:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> controller = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
<span class="hljs-keyword">const</span> rs = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ReadableStream</span>({
  <span class="hljs-title function_">start</span>(<span class="hljs-params">controller</span>) {
    controller.<span class="hljs-title function_">enqueue</span>(<span class="hljs-string">'hello'</span>);
    controller.<span class="hljs-title function_">enqueue</span>(<span class="hljs-string">'world'</span>);
    controller.<span class="hljs-title function_">close</span>();
  },
});

<span class="hljs-title function_">addAbortSignal</span>(controller.<span class="hljs-property">signal</span>, rs);

<span class="hljs-title function_">finished</span>(rs, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) {
    <span class="hljs-keyword">if</span> (err.<span class="hljs-property">name</span> === <span class="hljs-string">'AbortError'</span>) {
      <span class="hljs-comment">// The operation was cancelled</span>
    }
  }
});

<span class="hljs-keyword">const</span> reader = rs.<span class="hljs-title function_">getReader</span>();

reader.<span class="hljs-title function_">read</span>().<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">{ value, done }</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(value); <span class="hljs-comment">// hello</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(done); <span class="hljs-comment">// false</span>
  controller.<span class="hljs-title function_">abort</span>();
});</code> <button class="copy-button">copy</button></pre>
<h4><code>stream.getDefaultHighWaterMark(objectMode)</code><span><a class="mark" href="#all_stream_streamgetdefaulthighwatermarkobjectmode" id="all_stream_streamgetdefaulthighwatermarkobjectmode">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_getdefaulthighwatermark_objectmode"></a></h4>
<div class="api_metadata">
<span>Added in: v19.9.0</span>
</div>
<ul>
<li><code>objectMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></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>Returns the default highWaterMark used by streams.
Defaults to <code>65536</code> (64 KiB), or <code>16</code> for <code>objectMode</code>.</p>
<h4><code>stream.setDefaultHighWaterMark(objectMode, value)</code><span><a class="mark" href="#all_stream_streamsetdefaulthighwatermarkobjectmode-value" id="all_stream_streamsetdefaulthighwatermarkobjectmode-value">#</a></span><a aria-hidden="true" class="legacy" id="stream_stream_setdefaulthighwatermark_objectmode_value"></a></h4>
<div class="api_metadata">
<span>Added in: v19.9.0</span>
</div>
<ul>
<li><code>objectMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> highWaterMark value</li>
</ul>
<p>Sets the default highWaterMark used by streams.</p>
</section><section><h3>API for stream implementers<span><a class="mark" href="#all_stream_api-for-stream-implementers" id="all_stream_api-for-stream-implementers">#</a></span><a aria-hidden="true" class="legacy" id="stream_api_for_stream_implementers"></a></h3>

<p>The <code>node: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"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);

<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyWritable</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">Writable</span> {
  <span class="hljs-title function_">constructor</span>(<span class="hljs-params">{ highWaterMark, ...options }</span>) {
    <span class="hljs-variable language_">super</span>({ highWaterMark });
    <span class="hljs-comment">// ...</span>
  }
}</code> <button class="copy-button">copy</button></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="#all_stream_class-streamreadable"><code>Readable</code></a></td><td><a href="#all_stream_readable_readsize"><code>_read()</code></a></td></tr><tr><td>Writing only</td><td><a href="#all_stream_class-streamwritable"><code>Writable</code></a></td><td><a href="#all_stream_writable_writechunk-encoding-callback"><code>_write()</code></a>, <a href="#all_stream_writable_writevchunks-callback"><code>_writev()</code></a>, <a href="#all_stream_writable_finalcallback"><code>_final()</code></a></td></tr><tr><td>Reading and writing</td><td><a href="#all_stream_class-streamduplex"><code>Duplex</code></a></td><td><a href="#all_stream_readable_readsize"><code>_read()</code></a>, <a href="#all_stream_writable_writechunk-encoding-callback"><code>_write()</code></a>, <a href="#all_stream_writable_writevchunks-callback"><code>_writev()</code></a>, <a href="#all_stream_writable_finalcallback"><code>_final()</code></a></td></tr><tr><td>Operate on written data, then read the result</td><td><a href="#all_stream_class-streamtransform"><code>Transform</code></a></td><td><a href="#all_stream_transform_transformchunk-encoding-callback"><code>_transform()</code></a>, <a href="#all_stream_transform_flushcallback"><code>_flush()</code></a>, <a href="#all_stream_writable_finalcallback"><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="#all_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>
<h4>Simplified construction<span><a class="mark" href="#all_stream_simplified-construction" id="all_stream_simplified-construction">#</a></span><a aria-hidden="true" class="legacy" id="stream_simplified_construction"></a></h4>
<div class="api_metadata">
<span>Added in: v1.2.0</span>
</div>
<p>For many simple cases, it is possible to create 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"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);

<span class="hljs-keyword">const</span> myWritable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>({
  <span class="hljs-title function_">construct</span>(<span class="hljs-params">callback</span>) {
    <span class="hljs-comment">// Initialize state and load resources...</span>
  },
  <span class="hljs-title function_">write</span>(<span class="hljs-params">chunk, encoding, callback</span>) {
    <span class="hljs-comment">// ...</span>
  },
  <span class="hljs-title function_">destroy</span>(<span class="hljs-params"></span>) {
    <span class="hljs-comment">// Free resources...</span>
  },
});</code> <button class="copy-button">copy</button></pre>
<h4>Implementing a writable stream<span><a class="mark" href="#all_stream_implementing-a-writable-stream" id="all_stream_implementing-a-writable-stream">#</a></span><a aria-hidden="true" class="legacy" id="stream_implementing_a_writable_stream"></a></h4>
<p>The <code>stream.Writable</code> class is extended to implement a <a href="#all_stream_class-streamwritable"><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>
<h5><code>new stream.Writable([options])</code><span><a class="mark" href="#all_stream_new-streamwritableoptions" id="all_stream_new-streamwritableoptions">#</a></span><a aria-hidden="true" class="legacy" id="stream_new_stream_writable_options"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.5.0</td>
<td><p>support passing in an AbortSignal.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>Change <code>autoDestroy</code> option default to <code>true</code>.</p></td></tr>
<tr><td>v11.2.0, v10.16.0</td>
<td><p>Add <code>autoDestroy</code> option to automatically <code>destroy()</code> the stream when it emits <code>'finish'</code> or errors.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>Add <code>emitClose</code> option to specify if <code>'close'</code> is emitted on destroy.</p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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="#all_stream_writablewritechunk-encoding-callback"><code>stream.write()</code></a> starts returning <code>false</code>. <strong>Default:</strong>
<code>16384</code> (16 KiB), 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="#all_stream_writablewritechunk-encoding-callback"><code>stream.write()</code></a> to <code>Buffer</code>s (with the encoding
specified in the <a href="#all_stream_writablewritechunk-encoding-callback"><code>stream.write()</code></a> call) before passing
them to <a href="#all_stream_writable_writechunk-encoding-callback"><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="#all_stream_writablewritechunk-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="#all_stream_writablewritechunk-encoding-callback"><code>stream.write(anyObj)</code></a> is a valid operation. When set,
it becomes possible to write JavaScript values other than string, <a href="#all_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> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> 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="#all_stream_writable_writechunk-encoding-callback"><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="#all_stream_writable_writevchunks-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="#all_stream_writable_destroyerr-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="#all_stream_writable_finalcallback"><code>stream._final()</code></a> method.</li>
<li><code>construct</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="#all_stream_writable_constructcallback"><code>stream._construct()</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>true</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> A signal representing possible cancellation.</li>
</ul>
</li>
</ul>
<!-- eslint-disable no-useless-constructor -->
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);

<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyWritable</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">Writable</span> {
  <span class="hljs-title function_">constructor</span>(<span class="hljs-params">options</span>) {
    <span class="hljs-comment">// Calls the stream.Writable() constructor.</span>
    <span class="hljs-variable language_">super</span>(options);
    <span class="hljs-comment">// ...</span>
  }
}</code> <button class="copy-button">copy</button></pre>
<p>Or, when using pre-ES6 style constructors:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

<span class="hljs-keyword">function</span> <span class="hljs-title function_">MyWritable</span>(<span class="hljs-params">options</span>) {
  <span class="hljs-keyword">if</span> (!(<span class="hljs-variable language_">this</span> <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">MyWritable</span>))
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyWritable</span>(options);
  <span class="hljs-title class_">Writable</span>.<span class="hljs-title function_">call</span>(<span class="hljs-variable language_">this</span>, options);
}
util.<span class="hljs-title function_">inherits</span>(<span class="hljs-title class_">MyWritable</span>, <span class="hljs-title class_">Writable</span>);</code> <button class="copy-button">copy</button></pre>
<p>Or, using the simplified constructor approach:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);

<span class="hljs-keyword">const</span> myWritable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>({
  <span class="hljs-title function_">write</span>(<span class="hljs-params">chunk, encoding, callback</span>) {
    <span class="hljs-comment">// ...</span>
  },
  <span class="hljs-title function_">writev</span>(<span class="hljs-params">chunks, callback</span>) {
    <span class="hljs-comment">// ...</span>
  },
});</code> <button class="copy-button">copy</button></pre>
<p>Calling <code>abort</code> on the <code>AbortController</code> corresponding to the passed
<code>AbortSignal</code> will behave the same way as calling <code>.destroy(new AbortError())</code>
on the writeable stream.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);

<span class="hljs-keyword">const</span> controller = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
<span class="hljs-keyword">const</span> myWritable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>({
  <span class="hljs-title function_">write</span>(<span class="hljs-params">chunk, encoding, callback</span>) {
    <span class="hljs-comment">// ...</span>
  },
  <span class="hljs-title function_">writev</span>(<span class="hljs-params">chunks, callback</span>) {
    <span class="hljs-comment">// ...</span>
  },
  <span class="hljs-attr">signal</span>: controller.<span class="hljs-property">signal</span>,
});
<span class="hljs-comment">// Later, abort the operation closing the stream</span>
controller.<span class="hljs-title function_">abort</span>();</code> <button class="copy-button">copy</button></pre>
<h5><code>writable._construct(callback)</code><span><a class="mark" href="#all_stream_writable_constructcallback" id="all_stream_writable_constructcallback">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_construct_callback"></a></h5>
<div class="api_metadata">
<span>Added in: v15.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 the stream has finished initializing.</li>
</ul>
<p>The <code>_construct()</code> method MUST NOT 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 in a tick after the stream constructor
has returned, delaying any <code>_write()</code>, <code>_final()</code> and <code>_destroy()</code> calls until
<code>callback</code> is called. This is useful to initialize state or asynchronously
initialize resources before the stream can be used.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);

<span class="hljs-keyword">class</span> <span class="hljs-title class_">WriteStream</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">Writable</span> {
  <span class="hljs-title function_">constructor</span>(<span class="hljs-params">filename</span>) {
    <span class="hljs-variable language_">super</span>();
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">filename</span> = filename;
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">fd</span> = <span class="hljs-literal">null</span>;
  }
  <span class="hljs-title function_">_construct</span>(<span class="hljs-params">callback</span>) {
    fs.<span class="hljs-title function_">open</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">filename</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
      <span class="hljs-keyword">if</span> (err) {
        <span class="hljs-title function_">callback</span>(err);
      } <span class="hljs-keyword">else</span> {
        <span class="hljs-variable language_">this</span>.<span class="hljs-property">fd</span> = fd;
        <span class="hljs-title function_">callback</span>();
      }
    });
  }
  <span class="hljs-title function_">_write</span>(<span class="hljs-params">chunk, encoding, callback</span>) {
    fs.<span class="hljs-title function_">write</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">fd</span>, chunk, callback);
  }
  <span class="hljs-title function_">_destroy</span>(<span class="hljs-params">err, callback</span>) {
    <span class="hljs-keyword">if</span> (<span class="hljs-variable language_">this</span>.<span class="hljs-property">fd</span>) {
      fs.<span class="hljs-title function_">close</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">fd</span>, <span class="hljs-function">(<span class="hljs-params">er</span>) =></span> <span class="hljs-title function_">callback</span>(er || err));
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-title function_">callback</span>(err);
    }
  }
}</code> <button class="copy-button">copy</button></pre>
<h5><code>writable._write(chunk, encoding, callback)</code><span><a class="mark" href="#all_stream_writable_writechunk-encoding-callback" id="all_stream_writable_writechunk-encoding-callback">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_write_chunk_encoding_callback_1"></a></h5>
<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="#all_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="#all_stream_writablewritechunk-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="#all_stream_writablewritechunk-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="#all_stream_writable_writechunk-encoding-callback"><code>writable._write()</code></a> and/or
<a href="#all_stream_writable_writevchunks-callback"><code>writable._writev()</code></a> method to send data to the underlying
resource.</p>
<p><a href="#all_stream_class-streamtransform"><code>Transform</code></a> streams provide their own implementation of the
<a href="#all_stream_writable_writechunk-encoding-callback"><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> function must be called synchronously inside of
<code>writable._write()</code> or asynchronously (i.e. different tick) 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="#all_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>
<h5><code>writable._writev(chunks, callback)</code><span><a class="mark" href="#all_stream_writable_writevchunks-callback" id="all_stream_writable_writevchunks-callback">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_writev_chunks_callback"></a></h5>
<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 data to be written. The value is an array of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
that each represent a discrete chunk of data to write. The properties of
these objects are:
<ul>
<li><code>chunk</code> <a href="#all_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 buffer instance or string containing the data to
be written. The <code>chunk</code> will be a string if the <code>Writable</code> was created with
the <code>decodeStrings</code> option set to <code>false</code> and a string was passed to <code>write()</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 the <code>chunk</code>. If <code>chunk</code> is
a <code>Buffer</code>, the <code>encoding</code> will be <code>'buffer'</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 (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>
<h5><code>writable._destroy(err, callback)</code><span><a class="mark" href="#all_stream_writable_destroyerr-callback" id="all_stream_writable_destroyerr-callback">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_destroy_err_callback"></a></h5>
<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="#all_stream_writabledestroyerror"><code>writable.destroy()</code></a>.
It can be overridden by child classes but it <strong>must not</strong> be called directly.
Furthermore, the <code>callback</code> should not be mixed with async/await
once it is executed when a promise is resolved.</p>
<h5><code>writable._final(callback)</code><span><a class="mark" href="#all_stream_writable_finalcallback" id="all_stream_writable_finalcallback">#</a></span><a aria-hidden="true" class="legacy" id="stream_writable_final_callback"></a></h5>
<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>
<h5>Errors while writing<span><a class="mark" href="#all_stream_errors-while-writing" id="all_stream_errors-while-writing">#</a></span><a aria-hidden="true" class="legacy" id="stream_errors_while_writing"></a></h5>
<p>Errors occurring during the processing of the <a href="#all_stream_writable_writechunk-encoding-callback"><code>writable._write()</code></a>,
<a href="#all_stream_writable_writevchunks-callback"><code>writable._writev()</code></a> and <a href="#all_stream_writable_finalcallback"><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"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);

<span class="hljs-keyword">const</span> myWritable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Writable</span>({
  <span class="hljs-title function_">write</span>(<span class="hljs-params">chunk, encoding, callback</span>) {
    <span class="hljs-keyword">if</span> (chunk.<span class="hljs-title function_">toString</span>().<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">'a'</span>) >= <span class="hljs-number">0</span>) {
      <span class="hljs-title function_">callback</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'chunk is invalid'</span>));
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-title function_">callback</span>();
    }
  },
});</code> <button class="copy-button">copy</button></pre>
<h5>An example writable stream<span><a class="mark" href="#all_stream_an-example-writable-stream" id="all_stream_an-example-writable-stream">#</a></span><a aria-hidden="true" class="legacy" id="stream_an_example_writable_stream"></a></h5>
<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="#all_stream_class-streamwritable"><code>Writable</code></a> stream instance:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);

<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyWritable</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">Writable</span> {
  <span class="hljs-title function_">_write</span>(<span class="hljs-params">chunk, encoding, callback</span>) {
    <span class="hljs-keyword">if</span> (chunk.<span class="hljs-title function_">toString</span>().<span class="hljs-title function_">indexOf</span>(<span class="hljs-string">'a'</span>) >= <span class="hljs-number">0</span>) {
      <span class="hljs-title function_">callback</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'chunk is invalid'</span>));
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-title function_">callback</span>();
    }
  }
}</code> <button class="copy-button">copy</button></pre>
<h5>Decoding buffers in a writable stream<span><a class="mark" href="#all_stream_decoding-buffers-in-a-writable-stream" id="all_stream_decoding-buffers-in-a-writable-stream">#</a></span><a aria-hidden="true" class="legacy" id="stream_decoding_buffers_in_a_writable_stream"></a></h5>
<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="#all_stream_class-streamwritable"><code>Writable</code></a>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Writable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">StringDecoder</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:string_decoder'</span>);

<span class="hljs-keyword">class</span> <span class="hljs-title class_">StringWritable</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">Writable</span> {
  <span class="hljs-title function_">constructor</span>(<span class="hljs-params">options</span>) {
    <span class="hljs-variable language_">super</span>(options);
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">_decoder</span> = <span class="hljs-keyword">new</span> <span class="hljs-title class_">StringDecoder</span>(options &#x26;&#x26; options.<span class="hljs-property">defaultEncoding</span>);
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">data</span> = <span class="hljs-string">''</span>;
  }
  <span class="hljs-title function_">_write</span>(<span class="hljs-params">chunk, encoding, callback</span>) {
    <span class="hljs-keyword">if</span> (encoding === <span class="hljs-string">'buffer'</span>) {
      chunk = <span class="hljs-variable language_">this</span>.<span class="hljs-property">_decoder</span>.<span class="hljs-title function_">write</span>(chunk);
    }
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">data</span> += chunk;
    <span class="hljs-title function_">callback</span>();
  }
  <span class="hljs-title function_">_final</span>(<span class="hljs-params">callback</span>) {
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">data</span> += <span class="hljs-variable language_">this</span>.<span class="hljs-property">_decoder</span>.<span class="hljs-title function_">end</span>();
    <span class="hljs-title function_">callback</span>();
  }
}

<span class="hljs-keyword">const</span> euro = [[<span class="hljs-number">0xE2</span>, <span class="hljs-number">0x82</span>], [<span class="hljs-number">0xAC</span>]].<span class="hljs-title function_">map</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-property">from</span>);
<span class="hljs-keyword">const</span> w = <span class="hljs-keyword">new</span> <span class="hljs-title class_">StringWritable</span>();

w.<span class="hljs-title function_">write</span>(<span class="hljs-string">'currency: '</span>);
w.<span class="hljs-title function_">write</span>(euro[<span class="hljs-number">0</span>]);
w.<span class="hljs-title function_">end</span>(euro[<span class="hljs-number">1</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(w.<span class="hljs-property">data</span>); <span class="hljs-comment">// currency: €</span></code> <button class="copy-button">copy</button></pre>
<h4>Implementing a readable stream<span><a class="mark" href="#all_stream_implementing-a-readable-stream" id="all_stream_implementing-a-readable-stream">#</a></span><a aria-hidden="true" class="legacy" id="stream_implementing_a_readable_stream"></a></h4>
<p>The <code>stream.Readable</code> class is extended to implement a <a href="#all_stream_class-streamreadable"><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="#all_stream_readable_readsize"><code>readable._read()</code></a> method.</p>
<h5><code>new stream.Readable([options])</code><span><a class="mark" href="#all_stream_new-streamreadableoptions" id="all_stream_new-streamreadableoptions">#</a></span><a aria-hidden="true" class="legacy" id="stream_new_stream_readable_options"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.5.0</td>
<td><p>support passing in an AbortSignal.</p></td></tr>
<tr><td>v14.0.0</td>
<td><p>Change <code>autoDestroy</code> option default to <code>true</code>.</p></td></tr>
<tr><td>v11.2.0, v10.16.0</td>
<td><p>Add <code>autoDestroy</code> option to automatically <code>destroy()</code> the stream when it emits <code>'end'</code> or errors.</p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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="#all_stream_highwatermark-discrepancy-after-calling-readablesetencoding">number of bytes</a> to store
in the internal buffer before ceasing to read from the underlying resource.
<strong>Default:</strong> <code>16384</code> (16 KiB), 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="#all_stream_readablereadsize"><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="#all_stream_readable_readsize"><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="#all_stream_readable_destroyerr-callback"><code>stream._destroy()</code></a> method.</li>
<li><code>construct</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="#all_stream_readable_constructcallback"><code>stream._construct()</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>true</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> A signal representing possible cancellation.</li>
</ul>
</li>
</ul>
<!-- eslint-disable no-useless-constructor -->
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Readable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);

<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyReadable</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">Readable</span> {
  <span class="hljs-title function_">constructor</span>(<span class="hljs-params">options</span>) {
    <span class="hljs-comment">// Calls the stream.Readable(options) constructor.</span>
    <span class="hljs-variable language_">super</span>(options);
    <span class="hljs-comment">// ...</span>
  }
}</code> <button class="copy-button">copy</button></pre>
<p>Or, when using pre-ES6 style constructors:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Readable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

<span class="hljs-keyword">function</span> <span class="hljs-title function_">MyReadable</span>(<span class="hljs-params">options</span>) {
  <span class="hljs-keyword">if</span> (!(<span class="hljs-variable language_">this</span> <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">MyReadable</span>))
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyReadable</span>(options);
  <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">call</span>(<span class="hljs-variable language_">this</span>, options);
}
util.<span class="hljs-title function_">inherits</span>(<span class="hljs-title class_">MyReadable</span>, <span class="hljs-title class_">Readable</span>);</code> <button class="copy-button">copy</button></pre>
<p>Or, using the simplified constructor approach:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Readable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);

<span class="hljs-keyword">const</span> myReadable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Readable</span>({
  <span class="hljs-title function_">read</span>(<span class="hljs-params">size</span>) {
    <span class="hljs-comment">// ...</span>
  },
});</code> <button class="copy-button">copy</button></pre>
<p>Calling <code>abort</code> on the <code>AbortController</code> corresponding to the passed
<code>AbortSignal</code> will behave the same way as calling <code>.destroy(new AbortError())</code>
on the readable created.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Readable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> controller = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
<span class="hljs-keyword">const</span> read = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Readable</span>({
  <span class="hljs-title function_">read</span>(<span class="hljs-params">size</span>) {
    <span class="hljs-comment">// ...</span>
  },
  <span class="hljs-attr">signal</span>: controller.<span class="hljs-property">signal</span>,
});
<span class="hljs-comment">// Later, abort the operation closing the stream</span>
controller.<span class="hljs-title function_">abort</span>();</code> <button class="copy-button">copy</button></pre>
<h5><code>readable._construct(callback)</code><span><a class="mark" href="#all_stream_readable_constructcallback" id="all_stream_readable_constructcallback">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_construct_callback"></a></h5>
<div class="api_metadata">
<span>Added in: v15.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 the stream has finished initializing.</li>
</ul>
<p>The <code>_construct()</code> method MUST NOT be called directly. It may be implemented
by child classes, and if so, will be called by the internal <code>Readable</code>
class methods only.</p>
<p>This optional function will be scheduled in the next tick by the stream
constructor, delaying any <code>_read()</code> and <code>_destroy()</code> calls until <code>callback</code> is
called. This is useful to initialize state or asynchronously initialize
resources before the stream can be used.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Readable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);

<span class="hljs-keyword">class</span> <span class="hljs-title class_">ReadStream</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">Readable</span> {
  <span class="hljs-title function_">constructor</span>(<span class="hljs-params">filename</span>) {
    <span class="hljs-variable language_">super</span>();
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">filename</span> = filename;
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">fd</span> = <span class="hljs-literal">null</span>;
  }
  <span class="hljs-title function_">_construct</span>(<span class="hljs-params">callback</span>) {
    fs.<span class="hljs-title function_">open</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">filename</span>, <span class="hljs-function">(<span class="hljs-params">err, fd</span>) =></span> {
      <span class="hljs-keyword">if</span> (err) {
        <span class="hljs-title function_">callback</span>(err);
      } <span class="hljs-keyword">else</span> {
        <span class="hljs-variable language_">this</span>.<span class="hljs-property">fd</span> = fd;
        <span class="hljs-title function_">callback</span>();
      }
    });
  }
  <span class="hljs-title function_">_read</span>(<span class="hljs-params">n</span>) {
    <span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(n);
    fs.<span class="hljs-title function_">read</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">fd</span>, buf, <span class="hljs-number">0</span>, n, <span class="hljs-literal">null</span>, <span class="hljs-function">(<span class="hljs-params">err, bytesRead</span>) =></span> {
      <span class="hljs-keyword">if</span> (err) {
        <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">destroy</span>(err);
      } <span class="hljs-keyword">else</span> {
        <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(bytesRead > <span class="hljs-number">0</span> ? buf.<span class="hljs-title function_">slice</span>(<span class="hljs-number">0</span>, bytesRead) : <span class="hljs-literal">null</span>);
      }
    });
  }
  <span class="hljs-title function_">_destroy</span>(<span class="hljs-params">err, callback</span>) {
    <span class="hljs-keyword">if</span> (<span class="hljs-variable language_">this</span>.<span class="hljs-property">fd</span>) {
      fs.<span class="hljs-title function_">close</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">fd</span>, <span class="hljs-function">(<span class="hljs-params">er</span>) =></span> <span class="hljs-title function_">callback</span>(er || err));
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-title function_">callback</span>(err);
    }
  }
}</code> <button class="copy-button">copy</button></pre>
<h5><code>readable._read(size)</code><span><a class="mark" href="#all_stream_readable_readsize" id="all_stream_readable_readsize">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_read_size_1"></a></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> 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="#all_stream_readable_readsize"><code>readable._read()</code></a> method to fetch data from the underlying resource.</p>
<p>When <a href="#all_stream_readable_readsize"><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="#all_stream_readablepushchunk-encoding"><code>this.push(dataChunk)</code></a> method. <code>_read()</code> will be called again
after each call to <a href="#all_stream_readablepushchunk-encoding"><code>this.push(dataChunk)</code></a> once the stream is
ready to accept more data. <code>_read()</code> may 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 into
the queue.</p>
<p>Once the <a href="#all_stream_readable_readsize"><code>readable._read()</code></a> method has been called, it will not be called
again until more data is pushed through the <a href="#all_stream_readablepushchunk-encoding"><code>readable.push()</code></a>
method. Empty data such as empty buffers and strings will not cause
<a href="#all_stream_readable_readsize"><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="#all_stream_readablepushchunk-encoding"><code>stream.push(chunk)</code></a>.</p>
<p>The <a href="#all_stream_readable_readsize"><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>
<h5><code>readable._destroy(err, callback)</code><span><a class="mark" href="#all_stream_readable_destroyerr-callback" id="all_stream_readable_destroyerr-callback">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_destroy_err_callback"></a></h5>
<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="#all_stream_readabledestroyerror"><code>readable.destroy()</code></a>.
It can be overridden by child classes but it <strong>must not</strong> be called directly.</p>
<h5><code>readable.push(chunk[, encoding])</code><span><a class="mark" href="#all_stream_readablepushchunk-encoding" id="all_stream_readablepushchunk-encoding">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_push_chunk_encoding"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.13.0</td>
<td><p>The <code>chunk</code> argument can now be a <code>TypedArray</code> or <code>DataView</code> instance.</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>
</tbody></table>
</details>
</div>
<ul>
<li><code>chunk</code> <a href="#all_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#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 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a>, <a href="#all_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> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a>. 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 <a href="#all_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> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a>, 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="#all_stream_readablereadsize"><code>readable.read()</code></a> method when the <a href="#all_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"><span class="hljs-comment">// `_source` is an object with readStop() and readStart() methods,</span>
<span class="hljs-comment">// and an `ondata` member that gets called when it has data, and</span>
<span class="hljs-comment">// an `onend` member that gets called when the data is over.</span>

<span class="hljs-keyword">class</span> <span class="hljs-title class_">SourceWrapper</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">Readable</span> {
  <span class="hljs-title function_">constructor</span>(<span class="hljs-params">options</span>) {
    <span class="hljs-variable language_">super</span>(options);

    <span class="hljs-variable language_">this</span>.<span class="hljs-property">_source</span> = <span class="hljs-title function_">getLowLevelSourceObject</span>();

    <span class="hljs-comment">// Every time there's data, push it into the internal buffer.</span>
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">_source</span>.<span class="hljs-property">ondata</span> = <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> {
      <span class="hljs-comment">// If push() returns false, then stop reading from source.</span>
      <span class="hljs-keyword">if</span> (!<span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(chunk))
        <span class="hljs-variable language_">this</span>.<span class="hljs-property">_source</span>.<span class="hljs-title function_">readStop</span>();
    };

    <span class="hljs-comment">// When the source ends, push the EOF-signaling `null` chunk.</span>
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">_source</span>.<span class="hljs-property">onend</span> = <span class="hljs-function">() =></span> {
      <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(<span class="hljs-literal">null</span>);
    };
  }
  <span class="hljs-comment">// _read() will be called when the stream wants to pull more data in.</span>
  <span class="hljs-comment">// The advisory size argument is ignored in this case.</span>
  <span class="hljs-title function_">_read</span>(<span class="hljs-params">size</span>) {
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">_source</span>.<span class="hljs-title function_">readStart</span>();
  }
}</code> <button class="copy-button">copy</button></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="#all_stream_readable_readsize"><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="#all_stream_readablepush"><code>readable.push('')</code></a> for more information.</p>
<h5>Errors while reading<span><a class="mark" href="#all_stream_errors-while-reading" id="all_stream_errors-while-reading">#</a></span><a aria-hidden="true" class="legacy" id="stream_errors_while_reading"></a></h5>
<p>Errors occurring during processing of the <a href="#all_stream_readable_readsize"><code>readable._read()</code></a> must be
propagated through the <a href="#all_stream_readable_destroyerr-callback"><code>readable.destroy(err)</code></a> method.
Throwing an <code>Error</code> from within <a href="#all_stream_readable_readsize"><code>readable._read()</code></a> or manually emitting an
<code>'error'</code> event results in undefined behavior.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Readable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);

<span class="hljs-keyword">const</span> myReadable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Readable</span>({
  <span class="hljs-title function_">read</span>(<span class="hljs-params">size</span>) {
    <span class="hljs-keyword">const</span> err = <span class="hljs-title function_">checkSomeErrorCondition</span>();
    <span class="hljs-keyword">if</span> (err) {
      <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">destroy</span>(err);
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-comment">// Do some work.</span>
    }
  },
});</code> <button class="copy-button">copy</button></pre>
<h5>An example counting stream<span><a class="mark" href="#all_stream_an-example-counting-stream" id="all_stream_an-example-counting-stream">#</a></span><a aria-hidden="true" class="legacy" id="stream_an_example_counting_stream"></a></h5>

<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"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Readable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);

<span class="hljs-keyword">class</span> <span class="hljs-title class_">Counter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">Readable</span> {
  <span class="hljs-title function_">constructor</span>(<span class="hljs-params">opt</span>) {
    <span class="hljs-variable language_">super</span>(opt);
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">_max</span> = <span class="hljs-number">1000000</span>;
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">_index</span> = <span class="hljs-number">1</span>;
  }

  <span class="hljs-title function_">_read</span>(<span class="hljs-params"></span>) {
    <span class="hljs-keyword">const</span> i = <span class="hljs-variable language_">this</span>.<span class="hljs-property">_index</span>++;
    <span class="hljs-keyword">if</span> (i > <span class="hljs-variable language_">this</span>.<span class="hljs-property">_max</span>)
      <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(<span class="hljs-literal">null</span>);
    <span class="hljs-keyword">else</span> {
      <span class="hljs-keyword">const</span> str = <span class="hljs-title class_">String</span>(i);
      <span class="hljs-keyword">const</span> buf = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(str, <span class="hljs-string">'ascii'</span>);
      <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(buf);
    }
  }
}</code> <button class="copy-button">copy</button></pre>
<h4>Implementing a duplex stream<span><a class="mark" href="#all_stream_implementing-a-duplex-stream" id="all_stream_implementing-a-duplex-stream">#</a></span><a aria-hidden="true" class="legacy" id="stream_implementing_a_duplex_stream"></a></h4>
<p>A <a href="#all_stream_class-streamduplex"><code>Duplex</code></a> stream is one that implements both <a href="#all_stream_class-streamreadable"><code>Readable</code></a> and
<a href="#all_stream_class-streamwritable"><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="#all_stream_class-streamduplex"><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="#all_stream_readable_readsize"><code>readable._read()</code></a> and
<code>writable._write()</code> methods.</p>
<h5><code>new stream.Duplex(options)</code><span><a class="mark" href="#all_stream_new-streamduplexoptions" id="all_stream_new-streamduplexoptions">#</a></span><a aria-hidden="true" class="legacy" id="stream_new_stream_duplex_options"></a></h5>
<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><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:
<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>readable</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Sets whether the <code>Duplex</code> should 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> Sets whether the <code>Duplex</code> should be writable.
<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"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Duplex</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);

<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyDuplex</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">Duplex</span> {
  <span class="hljs-title function_">constructor</span>(<span class="hljs-params">options</span>) {
    <span class="hljs-variable language_">super</span>(options);
    <span class="hljs-comment">// ...</span>
  }
}</code> <button class="copy-button">copy</button></pre>
<p>Or, when using pre-ES6 style constructors:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Duplex</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

<span class="hljs-keyword">function</span> <span class="hljs-title function_">MyDuplex</span>(<span class="hljs-params">options</span>) {
  <span class="hljs-keyword">if</span> (!(<span class="hljs-variable language_">this</span> <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">MyDuplex</span>))
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyDuplex</span>(options);
  <span class="hljs-title class_">Duplex</span>.<span class="hljs-title function_">call</span>(<span class="hljs-variable language_">this</span>, options);
}
util.<span class="hljs-title function_">inherits</span>(<span class="hljs-title class_">MyDuplex</span>, <span class="hljs-title class_">Duplex</span>);</code> <button class="copy-button">copy</button></pre>
<p>Or, using the simplified constructor approach:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Duplex</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);

<span class="hljs-keyword">const</span> myDuplex = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Duplex</span>({
  <span class="hljs-title function_">read</span>(<span class="hljs-params">size</span>) {
    <span class="hljs-comment">// ...</span>
  },
  <span class="hljs-title function_">write</span>(<span class="hljs-params">chunk, encoding, callback</span>) {
    <span class="hljs-comment">// ...</span>
  },
});</code> <button class="copy-button">copy</button></pre>
<p>When using pipeline:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Transform</span>, pipeline } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);

<span class="hljs-title function_">pipeline</span>(
  fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'object.json'</span>)
    .<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>),
  <span class="hljs-keyword">new</span> <span class="hljs-title class_">Transform</span>({
    <span class="hljs-attr">decodeStrings</span>: <span class="hljs-literal">false</span>, <span class="hljs-comment">// Accept string input rather than Buffers</span>
    <span class="hljs-title function_">construct</span>(<span class="hljs-params">callback</span>) {
      <span class="hljs-variable language_">this</span>.<span class="hljs-property">data</span> = <span class="hljs-string">''</span>;
      <span class="hljs-title function_">callback</span>();
    },
    <span class="hljs-title function_">transform</span>(<span class="hljs-params">chunk, encoding, callback</span>) {
      <span class="hljs-variable language_">this</span>.<span class="hljs-property">data</span> += chunk;
      <span class="hljs-title function_">callback</span>();
    },
    <span class="hljs-title function_">flush</span>(<span class="hljs-params">callback</span>) {
      <span class="hljs-keyword">try</span> {
        <span class="hljs-comment">// Make sure is valid json.</span>
        <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">data</span>);
        <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">data</span>);
        <span class="hljs-title function_">callback</span>();
      } <span class="hljs-keyword">catch</span> (err) {
        <span class="hljs-title function_">callback</span>(err);
      }
    },
  }),
  fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'valid-object.json'</span>),
  <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
    <span class="hljs-keyword">if</span> (err) {
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'failed'</span>, err);
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'completed'</span>);
    }
  },
);</code> <button class="copy-button">copy</button></pre>
<h5>An example duplex stream<span><a class="mark" href="#all_stream_an-example-duplex-stream" id="all_stream_an-example-duplex-stream">#</a></span><a aria-hidden="true" class="legacy" id="stream_an_example_duplex_stream"></a></h5>
<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="#all_stream_class-streamwritable"><code>Writable</code></a> interface that is read back out
via the <a href="#all_stream_class-streamreadable"><code>Readable</code></a> interface.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Duplex</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> kSource = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'source'</span>);

<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyDuplex</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">Duplex</span> {
  <span class="hljs-title function_">constructor</span>(<span class="hljs-params">source, options</span>) {
    <span class="hljs-variable language_">super</span>(options);
    <span class="hljs-variable language_">this</span>[kSource] = source;
  }

  <span class="hljs-title function_">_write</span>(<span class="hljs-params">chunk, encoding, callback</span>) {
    <span class="hljs-comment">// The underlying source only deals with strings.</span>
    <span class="hljs-keyword">if</span> (<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">isBuffer</span>(chunk))
      chunk = chunk.<span class="hljs-title function_">toString</span>();
    <span class="hljs-variable language_">this</span>[kSource].<span class="hljs-title function_">writeSomeData</span>(chunk);
    <span class="hljs-title function_">callback</span>();
  }

  <span class="hljs-title function_">_read</span>(<span class="hljs-params">size</span>) {
    <span class="hljs-variable language_">this</span>[kSource].<span class="hljs-title function_">fetchSomeData</span>(size, <span class="hljs-function">(<span class="hljs-params">data, encoding</span>) =></span> {
      <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(data, encoding));
    });
  }
}</code> <button class="copy-button">copy</button></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>
<h5>Object mode duplex streams<span><a class="mark" href="#all_stream_object-mode-duplex-streams" id="all_stream_object-mode-duplex-streams">#</a></span><a aria-hidden="true" class="legacy" id="stream_object_mode_duplex_streams"></a></h5>
<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="#all_stream_class-streamduplex"><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"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Transform</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);

<span class="hljs-comment">// All Transform streams are also Duplex Streams.</span>
<span class="hljs-keyword">const</span> myTransform = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Transform</span>({
  <span class="hljs-attr">writableObjectMode</span>: <span class="hljs-literal">true</span>,

  <span class="hljs-title function_">transform</span>(<span class="hljs-params">chunk, encoding, callback</span>) {
    <span class="hljs-comment">// Coerce the chunk to a number if necessary.</span>
    chunk |= <span class="hljs-number">0</span>;

    <span class="hljs-comment">// Transform the chunk into something else.</span>
    <span class="hljs-keyword">const</span> data = chunk.<span class="hljs-title function_">toString</span>(<span class="hljs-number">16</span>);

    <span class="hljs-comment">// Push the data onto the readable queue.</span>
    <span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-string">'0'</span>.<span class="hljs-title function_">repeat</span>(data.<span class="hljs-property">length</span> % <span class="hljs-number">2</span>) + data);
  },
});

myTransform.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'ascii'</span>);
myTransform.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk));

myTransform.<span class="hljs-title function_">write</span>(<span class="hljs-number">1</span>);
<span class="hljs-comment">// Prints: 01</span>
myTransform.<span class="hljs-title function_">write</span>(<span class="hljs-number">10</span>);
<span class="hljs-comment">// Prints: 0a</span>
myTransform.<span class="hljs-title function_">write</span>(<span class="hljs-number">100</span>);
<span class="hljs-comment">// Prints: 64</span></code> <button class="copy-button">copy</button></pre>
<h4>Implementing a transform stream<span><a class="mark" href="#all_stream_implementing-a-transform-stream" id="all_stream_implementing-a-transform-stream">#</a></span><a aria-hidden="true" class="legacy" id="stream_implementing_a_transform_stream"></a></h4>
<p>A <a href="#all_stream_class-streamtransform"><code>Transform</code></a> stream is a <a href="#all_stream_class-streamduplex"><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="#all_stream_class-streamtransform"><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="#all_stream_readable_readsize"><code>readable._read()</code></a> methods. Custom <code>Transform</code> implementations <em>must</em>
implement the <a href="#all_stream_transform_transformchunk-encoding-callback"><code>transform._transform()</code></a> method and <em>may</em>
also implement the <a href="#all_stream_transform_flushcallback"><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>
<h5><code>new stream.Transform([options])</code><span><a class="mark" href="#all_stream_new-streamtransformoptions" id="all_stream_new-streamtransformoptions">#</a></span><a aria-hidden="true" class="legacy" id="stream_new_stream_transform_options"></a></h5>
<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> Passed to both <code>Writable</code> and <code>Readable</code>
constructors. Also has the following fields:
<ul>
<li><code>transform</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Implementation for the
<a href="#all_stream_transform_transformchunk-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="#all_stream_transform_flushcallback"><code>stream._flush()</code></a>
method.</li>
</ul>
</li>
</ul>
<!-- eslint-disable no-useless-constructor -->
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Transform</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);

<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyTransform</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">Transform</span> {
  <span class="hljs-title function_">constructor</span>(<span class="hljs-params">options</span>) {
    <span class="hljs-variable language_">super</span>(options);
    <span class="hljs-comment">// ...</span>
  }
}</code> <button class="copy-button">copy</button></pre>
<p>Or, when using pre-ES6 style constructors:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Transform</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

<span class="hljs-keyword">function</span> <span class="hljs-title function_">MyTransform</span>(<span class="hljs-params">options</span>) {
  <span class="hljs-keyword">if</span> (!(<span class="hljs-variable language_">this</span> <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">MyTransform</span>))
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyTransform</span>(options);
  <span class="hljs-title class_">Transform</span>.<span class="hljs-title function_">call</span>(<span class="hljs-variable language_">this</span>, options);
}
util.<span class="hljs-title function_">inherits</span>(<span class="hljs-title class_">MyTransform</span>, <span class="hljs-title class_">Transform</span>);</code> <button class="copy-button">copy</button></pre>
<p>Or, using the simplified constructor approach:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Transform</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);

<span class="hljs-keyword">const</span> myTransform = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Transform</span>({
  <span class="hljs-title function_">transform</span>(<span class="hljs-params">chunk, encoding, callback</span>) {
    <span class="hljs-comment">// ...</span>
  },
});</code> <button class="copy-button">copy</button></pre>
<h5>Event: <code>'end'</code><span><a class="mark" href="#all_stream_event-end_1" id="all_stream_event-end_1">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_end_1"></a></h5>
<p>The <a href="#all_stream_event-end"><code>'end'</code></a> event is from the <code>stream.Readable</code> class. The <code>'end'</code> event is
emitted after all data has been output, which occurs after the callback in
<a href="#all_stream_transform_flushcallback"><code>transform._flush()</code></a> has been called. In the case of an error,
<code>'end'</code> should not be emitted.</p>
<h5>Event: <code>'finish'</code><span><a class="mark" href="#all_stream_event-finish_1" id="all_stream_event-finish_1">#</a></span><a aria-hidden="true" class="legacy" id="stream_event_finish_1"></a></h5>
<p>The <a href="#all_stream_event-finish"><code>'finish'</code></a> event is from the <code>stream.Writable</code> class. The <code>'finish'</code>
event is emitted after <a href="#all_stream_writableendchunk-encoding-callback"><code>stream.end()</code></a> is called and all chunks
have been processed by <a href="#all_stream_transform_transformchunk-encoding-callback"><code>stream._transform()</code></a>. In the case
of an error, <code>'finish'</code> should not be emitted.</p>
<h5><code>transform._flush(callback)</code><span><a class="mark" href="#all_stream_transform_flushcallback" id="all_stream_transform_flushcallback">#</a></span><a aria-hidden="true" class="legacy" id="stream_transform_flush_callback"></a></h5>
<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="#all_stream_class-streamtransform"><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="#all_stream_event-end"><code>'end'</code></a> event is emitted signaling the end of the
<a href="#all_stream_class-streamreadable"><code>Readable</code></a> stream.</p>
<p>Within the <code>transform._flush()</code> implementation, the <code>transform.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>
<h5><code>transform._transform(chunk, encoding, callback)</code><span><a class="mark" href="#all_stream_transform_transformchunk-encoding-callback" id="all_stream_transform_transformchunk-encoding-callback">#</a></span><a aria-hidden="true" class="legacy" id="stream_transform_transform_chunk_encoding_callback"></a></h5>
<ul>
<li><code>chunk</code> <a href="#all_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="#all_stream_writablewritechunk-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="#all_stream_writablewritechunk-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>transform.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>transform.push()</code> method, but only if the first argument is falsy. In other
words, the following are equivalent:</p>
<pre><code class="language-js">transform.<span class="hljs-property"><span class="hljs-keyword">prototype</span></span>.<span class="hljs-property">_transform</span> = <span class="hljs-keyword">function</span>(<span class="hljs-params">data, encoding, callback</span>) {
  <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">push</span>(data);
  <span class="hljs-title function_">callback</span>();
};

transform.<span class="hljs-property"><span class="hljs-keyword">prototype</span></span>.<span class="hljs-property">_transform</span> = <span class="hljs-keyword">function</span>(<span class="hljs-params">data, encoding, callback</span>) {
  <span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, data);
};</code> <button class="copy-button">copy</button></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>
<h5>Class: <code>stream.PassThrough</code><span><a class="mark" href="#all_stream_class-streampassthrough" id="all_stream_class-streampassthrough">#</a></span><a aria-hidden="true" class="legacy" id="stream_class_stream_passthrough"></a></h5>
<p>The <code>stream.PassThrough</code> class is a trivial implementation of a <a href="#all_stream_class-streamtransform"><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>
</section><section><h3>Additional notes<span><a class="mark" href="#all_stream_additional-notes" id="all_stream_additional-notes">#</a></span><a aria-hidden="true" class="legacy" id="stream_additional_notes"></a></h3>

<h4>Streams compatibility with async generators and async iterators<span><a class="mark" href="#all_stream_streams-compatibility-with-async-generators-and-async-iterators" id="all_stream_streams-compatibility-with-async-generators-and-async-iterators">#</a></span><a aria-hidden="true" class="legacy" id="stream_streams_compatibility_with_async_generators_and_async_iterators"></a></h4>
<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>
<h5>Consuming readable streams with async iterators<span><a class="mark" href="#all_stream_consuming-readable-streams-with-async-iterators" id="all_stream_consuming-readable-streams-with-async-iterators">#</a></span><a aria-hidden="true" class="legacy" id="stream_consuming_readable_streams_with_async_iterators"></a></h5>
<pre><code class="language-js">(<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> readable) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk);
  }
})();</code> <button class="copy-button">copy</button></pre>
<p>Async iterators register a permanent error handler on the stream to prevent any
unhandled post-destroy errors.</p>
<h5>Creating readable streams with async generators<span><a class="mark" href="#all_stream_creating-readable-streams-with-async-generators" id="all_stream_creating-readable-streams-with-async-generators">#</a></span><a aria-hidden="true" class="legacy" id="stream_creating_readable_streams_with_async_generators"></a></h5>
<p>A Node.js readable stream can be created from an asynchronous generator using
the <code>Readable.from()</code> utility method:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Readable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);

<span class="hljs-keyword">const</span> ac = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
<span class="hljs-keyword">const</span> signal = ac.<span class="hljs-property">signal</span>;

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> * <span class="hljs-title function_">generate</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">yield</span> <span class="hljs-string">'a'</span>;
  <span class="hljs-keyword">await</span> <span class="hljs-title function_">someLongRunningFn</span>({ signal });
  <span class="hljs-keyword">yield</span> <span class="hljs-string">'b'</span>;
  <span class="hljs-keyword">yield</span> <span class="hljs-string">'c'</span>;
}

<span class="hljs-keyword">const</span> readable = <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>(<span class="hljs-title function_">generate</span>());
readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">() =></span> {
  ac.<span class="hljs-title function_">abort</span>();
});

readable.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk);
});</code> <button class="copy-button">copy</button></pre>
<h5>Piping to writable streams from async iterators<span><a class="mark" href="#all_stream_piping-to-writable-streams-from-async-iterators" id="all_stream_piping-to-writable-streams-from-async-iterators">#</a></span><a aria-hidden="true" class="legacy" id="stream_piping_to_writable_streams_from_async_iterators"></a></h5>
<p>When writing to a writable stream from an async iterator, ensure correct
handling of backpressure and errors. <a href="#all_stream_streampipelinesource-transforms-destination-callback"><code>stream.pipeline()</code></a> abstracts away
the handling of backpressure and backpressure-related errors:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> { pipeline } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-attr">pipeline</span>: pipelinePromise } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/promises'</span>);

<span class="hljs-keyword">const</span> writable = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'./file'</span>);

<span class="hljs-keyword">const</span> ac = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
<span class="hljs-keyword">const</span> signal = ac.<span class="hljs-property">signal</span>;

<span class="hljs-keyword">const</span> iterator = <span class="hljs-title function_">createIterator</span>({ signal });

<span class="hljs-comment">// Callback Pattern</span>
<span class="hljs-title function_">pipeline</span>(iterator, writable, <span class="hljs-function">(<span class="hljs-params">err, value</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err);
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(value, <span class="hljs-string">'value returned'</span>);
  }
}).<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">() =></span> {
  ac.<span class="hljs-title function_">abort</span>();
});

<span class="hljs-comment">// Promise Pattern</span>
<span class="hljs-title function_">pipelinePromise</span>(iterator, writable)
  .<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">value</span>) =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(value, <span class="hljs-string">'value returned'</span>);
  })
  .<span class="hljs-title function_">catch</span>(<span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(err);
    ac.<span class="hljs-title function_">abort</span>();
  });</code> <button class="copy-button">copy</button></pre>

<h4>Compatibility with older Node.js versions<span><a class="mark" href="#all_stream_compatibility-with-older-nodejs-versions" id="all_stream_compatibility-with-older-nodejs-versions">#</a></span><a aria-hidden="true" class="legacy" id="stream_compatibility_with_older_node_js_versions"></a></h4>

<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="#all_stream_readablereadsize"><code>stream.read()</code></a> method,
<a href="#all_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="#all_stream_readablepause"><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="#all_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="#all_stream_class-streamreadable"><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="#all_stream_event-data"><code>'data'</code></a> event handler is added, or when the
<a href="#all_stream_readableresume"><code>stream.resume()</code></a> method is called. The effect is that, even
when not using the new <a href="#all_stream_readablereadsize"><code>stream.read()</code></a> method and
<a href="#all_stream_event-readable"><code>'readable'</code></a> event, it is no longer necessary to worry about losing
<a href="#all_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="#all_stream_event-data"><code>'data'</code></a> event listener is added.</li>
<li>The <a href="#all_stream_readableresume"><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"><span class="hljs-comment">// WARNING!  BROKEN!</span>
net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">socket</span>) =></span> {

  <span class="hljs-comment">// We add an 'end' listener, but never consume the data.</span>
  socket.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> {
    <span class="hljs-comment">// It will never get here.</span>
    socket.<span class="hljs-title function_">end</span>(<span class="hljs-string">'The message was received but was not processed.\n'</span>);
  });

}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">1337</span>);</code> <button class="copy-button">copy</button></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="#all_stream_readableresume"><code>stream.resume()</code></a> method to begin the flow of data:</p>
<pre><code class="language-js"><span class="hljs-comment">// Workaround.</span>
net.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">socket</span>) =></span> {
  socket.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> {
    socket.<span class="hljs-title function_">end</span>(<span class="hljs-string">'The message was received but was not processed.\n'</span>);
  });

  <span class="hljs-comment">// Start the flow of data, discarding it.</span>
  socket.<span class="hljs-title function_">resume</span>();
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">1337</span>);</code> <button class="copy-button">copy</button></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="#all_stream_readablewrapstream"><code>readable.wrap()</code></a> method.</p>
<h4><code>readable.read(0)</code><span><a class="mark" href="#all_stream_readableread0" id="all_stream_readableread0">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_read_0"></a></h4>
<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="#all_stream_readable_readsize"><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>
<h4><code>readable.push('')</code><span><a class="mark" href="#all_stream_readablepush" id="all_stream_readablepush">#</a></span><a aria-hidden="true" class="legacy" id="stream_readable_push"></a></h4>
<p>Use of <code>readable.push('')</code> is not recommended.</p>
<p>Pushing a zero-byte <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a>, <a href="#all_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> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> to a stream
that is not in object mode has an interesting side effect.
Because it <em>is</em> a call to
<a href="#all_stream_readablepushchunk-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>
<h4><code>highWaterMark</code> discrepancy after calling <code>readable.setEncoding()</code><span><a class="mark" href="#all_stream_highwatermark-discrepancy-after-calling-readablesetencoding" id="all_stream_highwatermark-discrepancy-after-calling-readablesetencoding">#</a></span><a aria-hidden="true" class="legacy" id="stream_highwatermark_discrepancy_after_calling_readable_setencoding"></a></h4>
<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></section>
        </section>
<section><h2>String decoder<span><a class="mark" href="#all_string_decoder_string-decoder" id="all_string_decoder_string-decoder">#</a></span><a aria-hidden="true" class="legacy" id="string_decoder_string_decoder"></a></h2>

<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/string_decoder.js">lib/string_decoder.js</a></p>
<p>The <code>node: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"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">StringDecoder</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:string_decoder'</span>);</code> <button class="copy-button">copy</button></pre>
<p>The following example shows the basic use of the <code>StringDecoder</code> class.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">StringDecoder</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:string_decoder'</span>);
<span class="hljs-keyword">const</span> decoder = <span class="hljs-keyword">new</span> <span class="hljs-title class_">StringDecoder</span>(<span class="hljs-string">'utf8'</span>);

<span class="hljs-keyword">const</span> cent = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0xC2</span>, <span class="hljs-number">0xA2</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(decoder.<span class="hljs-title function_">write</span>(cent)); <span class="hljs-comment">// Prints: ¢</span>

<span class="hljs-keyword">const</span> euro = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0xE2</span>, <span class="hljs-number">0x82</span>, <span class="hljs-number">0xAC</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(decoder.<span class="hljs-title function_">write</span>(euro)); <span class="hljs-comment">// Prints: €</span></code> <button class="copy-button">copy</button></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"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">StringDecoder</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:string_decoder'</span>);
<span class="hljs-keyword">const</span> decoder = <span class="hljs-keyword">new</span> <span class="hljs-title class_">StringDecoder</span>(<span class="hljs-string">'utf8'</span>);

decoder.<span class="hljs-title function_">write</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0xE2</span>]));
decoder.<span class="hljs-title function_">write</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0x82</span>]));
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(decoder.<span class="hljs-title function_">end</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>([<span class="hljs-number">0xAC</span>]))); <span class="hljs-comment">// Prints: €</span></code> <button class="copy-button">copy</button></pre>
<section><h3>Class: <code>StringDecoder</code><span><a class="mark" href="#all_string_decoder_class-stringdecoder" id="all_string_decoder_class-stringdecoder">#</a></span><a aria-hidden="true" class="legacy" id="string_decoder_class_stringdecoder"></a></h3>
<h4><code>new StringDecoder([encoding])</code><span><a class="mark" href="#all_string_decoder_new-stringdecoderencoding" id="all_string_decoder_new-stringdecoderencoding">#</a></span><a aria-hidden="true" class="legacy" id="string_decoder_new_stringdecoder_encoding"></a></h4>
<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="#all_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>
<h4><code>stringDecoder.end([buffer])</code><span><a class="mark" href="#all_string_decoder_stringdecoderendbuffer" id="all_string_decoder_stringdecoderendbuffer">#</a></span><a aria-hidden="true" class="legacy" id="string_decoder_stringdecoder_end_buffer"></a></h4>
<div class="api_metadata">
<span>Added in: v0.9.3</span>
</div>
<ul>
<li><code>buffer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#all_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 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.
After <code>end()</code> is called, the <code>stringDecoder</code> object can be reused for new input.</p>
<h4><code>stringDecoder.write(buffer)</code><span><a class="mark" href="#all_string_decoder_stringdecoderwritebuffer" id="all_string_decoder_stringdecoderwritebuffer">#</a></span><a aria-hidden="true" class="legacy" id="string_decoder_stringdecoder_write_buffer"></a></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>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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> | <a href="#all_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 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></section>
        </section>
<section><h2>Test runner<span><a class="mark" href="#all_test_test-runner" id="all_test_test-runner">#</a></span><a aria-hidden="true" class="legacy" id="test_test_runner"></a></h2>

<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>The test runner is now stable.</p></td></tr>
<tr><td>v18.0.0, v16.17.0</td>
<td><p><span>Added in: v18.0.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/test.js">lib/test.js</a></p>
<p>The <code>node:test</code> module facilitates the creation of JavaScript tests.
To access it:</p>

<pre class="with-34-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> test <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> test = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);</code><button class="copy-button">copy</button></pre>
<p>This module is only available under the <code>node:</code> scheme. The following will not
work:</p>

<pre class="with-29-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> test <span class="hljs-keyword">from</span> <span class="hljs-string">'test'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> test = <span class="hljs-built_in">require</span>(<span class="hljs-string">'test'</span>);</code><button class="copy-button">copy</button></pre>
<p>Tests created via the <code>test</code> module consist of a single function that is
processed in one of three ways:</p>
<ol>
<li>A synchronous function that is considered failing if it throws an exception,
and is considered passing otherwise.</li>
<li>A function that returns a <code>Promise</code> that is considered failing if the
<code>Promise</code> rejects, and is considered passing if the <code>Promise</code> fulfills.</li>
<li>A function that receives a callback function. If the callback receives any
truthy value as its first argument, the test is considered failing. If a
falsy value is passed as the first argument to the callback, the test is
considered passing. If the test function receives a callback function and
also returns a <code>Promise</code>, the test will fail.</li>
</ol>
<p>The following example illustrates how tests are written using the
<code>test</code> module.</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'synchronous passing test'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
  <span class="hljs-comment">// This test passes because it does not throw an exception.</span>
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>);
});

<span class="hljs-title function_">test</span>(<span class="hljs-string">'synchronous failing test'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
  <span class="hljs-comment">// This test fails because it throws an exception.</span>
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);
});

<span class="hljs-title function_">test</span>(<span class="hljs-string">'asynchronous passing test'</span>, <span class="hljs-keyword">async</span> (t) => {
  <span class="hljs-comment">// This test passes because the Promise returned by the async</span>
  <span class="hljs-comment">// function is settled and not rejected.</span>
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>);
});

<span class="hljs-title function_">test</span>(<span class="hljs-string">'asynchronous failing test'</span>, <span class="hljs-keyword">async</span> (t) => {
  <span class="hljs-comment">// This test fails because the Promise returned by the async</span>
  <span class="hljs-comment">// function is rejected.</span>
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);
});

<span class="hljs-title function_">test</span>(<span class="hljs-string">'failing test using Promises'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
  <span class="hljs-comment">// Promises can be used directly as well.</span>
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =></span> {
    <span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></span> {
      <span class="hljs-title function_">reject</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'this will cause the test to fail'</span>));
    });
  });
});

<span class="hljs-title function_">test</span>(<span class="hljs-string">'callback passing test'</span>, <span class="hljs-function">(<span class="hljs-params">t, done</span>) =></span> {
  <span class="hljs-comment">// done() is the callback function. When the setImmediate() runs, it invokes</span>
  <span class="hljs-comment">// done() with no arguments.</span>
  <span class="hljs-title function_">setImmediate</span>(done);
});

<span class="hljs-title function_">test</span>(<span class="hljs-string">'callback failing test'</span>, <span class="hljs-function">(<span class="hljs-params">t, done</span>) =></span> {
  <span class="hljs-comment">// When the setImmediate() runs, done() is invoked with an Error object and</span>
  <span class="hljs-comment">// the test fails.</span>
  <span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></span> {
    <span class="hljs-title function_">done</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'callback failure'</span>));
  });
});</code> <button class="copy-button">copy</button></pre>
<p>If any tests fail, the process exit code is set to <code>1</code>.</p>
<section><h3>Subtests<span><a class="mark" href="#all_test_subtests" id="all_test_subtests">#</a></span><a aria-hidden="true" class="legacy" id="test_subtests"></a></h3>
<p>The test context's <code>test()</code> method allows subtests to be created.
It allows you to structure your tests in a hierarchical manner,
where you can create nested tests within a larger test.
This method behaves identically to the top level <code>test()</code> function.
The following example demonstrates the creation of a
top level test with two subtests.</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'top level test'</span>, <span class="hljs-keyword">async</span> (t) => {
  <span class="hljs-keyword">await</span> t.<span class="hljs-title function_">test</span>(<span class="hljs-string">'subtest 1'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
    assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>);
  });

  <span class="hljs-keyword">await</span> t.<span class="hljs-title function_">test</span>(<span class="hljs-string">'subtest 2'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
    assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-number">2</span>, <span class="hljs-number">2</span>);
  });
});</code> <button class="copy-button">copy</button></pre>
<blockquote>
<p><strong>Note:</strong> <code>beforeEach</code> and <code>afterEach</code> hooks are triggered
between each subtest execution.</p>
</blockquote>
<p>In this example, <code>await</code> is used to ensure that both subtests have completed.
This is necessary because tests do not wait for their subtests to
complete, unlike tests created within suites.
Any subtests that are still outstanding when their parent finishes
are cancelled and treated as failures. Any subtest failures cause the parent
test to fail.</p>
</section><section><h3>Skipping tests<span><a class="mark" href="#all_test_skipping-tests" id="all_test_skipping-tests">#</a></span><a aria-hidden="true" class="legacy" id="test_skipping_tests"></a></h3>
<p>Individual tests can be skipped by passing the <code>skip</code> option to the test, or by
calling the test context's <code>skip()</code> method as shown in the
following example.</p>
<pre><code class="language-js"><span class="hljs-comment">// The skip option is used, but no message is provided.</span>
<span class="hljs-title function_">test</span>(<span class="hljs-string">'skip option'</span>, { <span class="hljs-attr">skip</span>: <span class="hljs-literal">true</span> }, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
  <span class="hljs-comment">// This code is never executed.</span>
});

<span class="hljs-comment">// The skip option is used, and a message is provided.</span>
<span class="hljs-title function_">test</span>(<span class="hljs-string">'skip option with message'</span>, { <span class="hljs-attr">skip</span>: <span class="hljs-string">'this is skipped'</span> }, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
  <span class="hljs-comment">// This code is never executed.</span>
});

<span class="hljs-title function_">test</span>(<span class="hljs-string">'skip() method'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
  <span class="hljs-comment">// Make sure to return here as well if the test contains additional logic.</span>
  t.<span class="hljs-title function_">skip</span>();
});

<span class="hljs-title function_">test</span>(<span class="hljs-string">'skip() method with message'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
  <span class="hljs-comment">// Make sure to return here as well if the test contains additional logic.</span>
  t.<span class="hljs-title function_">skip</span>(<span class="hljs-string">'this is skipped'</span>);
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3>TODO tests<span><a class="mark" href="#all_test_todo-tests" id="all_test_todo-tests">#</a></span><a aria-hidden="true" class="legacy" id="test_todo_tests"></a></h3>
<p>Individual tests can be marked as flaky or incomplete by passing the <code>todo</code>
option to the test, or by calling the test context's <code>todo()</code> method, as shown
in the following example. These tests represent a pending implementation or bug
that needs to be fixed. TODO tests are executed, but are not treated as test
failures, and therefore do not affect the process exit code. If a test is marked
as both TODO and skipped, the TODO option is ignored.</p>
<pre><code class="language-js"><span class="hljs-comment">// The todo option is used, but no message is provided.</span>
<span class="hljs-title function_">test</span>(<span class="hljs-string">'todo option'</span>, { <span class="hljs-attr">todo</span>: <span class="hljs-literal">true</span> }, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
  <span class="hljs-comment">// This code is executed, but not treated as a failure.</span>
  <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'this does not fail the test'</span>);
});

<span class="hljs-comment">// The todo option is used, and a message is provided.</span>
<span class="hljs-title function_">test</span>(<span class="hljs-string">'todo option with message'</span>, { <span class="hljs-attr">todo</span>: <span class="hljs-string">'this is a todo test'</span> }, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
  <span class="hljs-comment">// This code is executed.</span>
});

<span class="hljs-title function_">test</span>(<span class="hljs-string">'todo() method'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
  t.<span class="hljs-title function_">todo</span>();
});

<span class="hljs-title function_">test</span>(<span class="hljs-string">'todo() method with message'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
  t.<span class="hljs-title function_">todo</span>(<span class="hljs-string">'this is a todo test and is not treated as a failure'</span>);
  <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'this does not fail the test'</span>);
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>describe()</code> and <code>it()</code> aliases<span><a class="mark" href="#all_test_describe-and-it-aliases" id="all_test_describe-and-it-aliases">#</a></span><a aria-hidden="true" class="legacy" id="test_describe_and_it_aliases"></a></h3>
<p>Suites and tests can also be written using the <code>describe()</code> and <code>it()</code>
functions. <a href="#all_test_describename-options-fn"><code>describe()</code></a> is an alias for <a href="#all_test_suitename-options-fn"><code>suite()</code></a>, and <a href="#all_test_itname-options-fn"><code>it()</code></a> is an
alias for <a href="#all_test_testname-options-fn"><code>test()</code></a>.</p>
<pre><code class="language-js"><span class="hljs-title function_">describe</span>(<span class="hljs-string">'A thing'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-title function_">it</span>(<span class="hljs-string">'should work'</span>, <span class="hljs-function">() =></span> {
    assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>);
  });

  <span class="hljs-title function_">it</span>(<span class="hljs-string">'should be ok'</span>, <span class="hljs-function">() =></span> {
    assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-number">2</span>, <span class="hljs-number">2</span>);
  });

  <span class="hljs-title function_">describe</span>(<span class="hljs-string">'a nested thing'</span>, <span class="hljs-function">() =></span> {
    <span class="hljs-title function_">it</span>(<span class="hljs-string">'should work'</span>, <span class="hljs-function">() =></span> {
      assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-number">3</span>, <span class="hljs-number">3</span>);
    });
  });
});</code> <button class="copy-button">copy</button></pre>
<p><code>describe()</code> and <code>it()</code> are imported from the <code>node:test</code> module.</p>

<pre class="with-46-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { describe, it } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { describe, it } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>only</code> tests<span><a class="mark" href="#all_test_only-tests" id="all_test_only-tests">#</a></span><a aria-hidden="true" class="legacy" id="test_only_tests"></a></h3>
<p>If Node.js is started with the <a href="#all_cli_--test-only"><code>--test-only</code></a> command-line option, it is
possible to skip all top level tests except for a selected subset by passing
the <code>only</code> option to the tests that should be run. When a test with the <code>only</code>
option set is run, all subtests are also run. The test context's <code>runOnly()</code>
method can be used to implement the same behavior at the subtest level.</p>
<pre><code class="language-js"><span class="hljs-comment">// Assume Node.js is run with the --test-only command-line option.</span>
<span class="hljs-comment">// The 'only' option is set, so this test is run.</span>
<span class="hljs-title function_">test</span>(<span class="hljs-string">'this test is run'</span>, { <span class="hljs-attr">only</span>: <span class="hljs-literal">true</span> }, <span class="hljs-keyword">async</span> (t) => {
  <span class="hljs-comment">// Within this test, all subtests are run by default.</span>
  <span class="hljs-keyword">await</span> t.<span class="hljs-title function_">test</span>(<span class="hljs-string">'running subtest'</span>);

  <span class="hljs-comment">// The test context can be updated to run subtests with the 'only' option.</span>
  t.<span class="hljs-title function_">runOnly</span>(<span class="hljs-literal">true</span>);
  <span class="hljs-keyword">await</span> t.<span class="hljs-title function_">test</span>(<span class="hljs-string">'this subtest is now skipped'</span>);
  <span class="hljs-keyword">await</span> t.<span class="hljs-title function_">test</span>(<span class="hljs-string">'this subtest is run'</span>, { <span class="hljs-attr">only</span>: <span class="hljs-literal">true</span> });

  <span class="hljs-comment">// Switch the context back to execute all tests.</span>
  t.<span class="hljs-title function_">runOnly</span>(<span class="hljs-literal">false</span>);
  <span class="hljs-keyword">await</span> t.<span class="hljs-title function_">test</span>(<span class="hljs-string">'this subtest is now run'</span>);

  <span class="hljs-comment">// Explicitly do not run these tests.</span>
  <span class="hljs-keyword">await</span> t.<span class="hljs-title function_">test</span>(<span class="hljs-string">'skipped subtest 3'</span>, { <span class="hljs-attr">only</span>: <span class="hljs-literal">false</span> });
  <span class="hljs-keyword">await</span> t.<span class="hljs-title function_">test</span>(<span class="hljs-string">'skipped subtest 4'</span>, { <span class="hljs-attr">skip</span>: <span class="hljs-literal">true</span> });
});

<span class="hljs-comment">// The 'only' option is not set, so this test is skipped.</span>
<span class="hljs-title function_">test</span>(<span class="hljs-string">'this test is not run'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-comment">// This code is not run.</span>
  <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'fail'</span>);
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Filtering tests by name<span><a class="mark" href="#all_test_filtering-tests-by-name" id="all_test_filtering-tests-by-name">#</a></span><a aria-hidden="true" class="legacy" id="test_filtering_tests_by_name"></a></h3>
<p>The <a href="#all_cli_--test-name-pattern"><code>--test-name-pattern</code></a> command-line option can be used to only run tests
whose name matches the provided pattern. Test name patterns are interpreted as
JavaScript regular expressions. The <code>--test-name-pattern</code> option can be
specified multiple times in order to run nested tests. For each test that is
executed, any corresponding test hooks, such as <code>beforeEach()</code>, are also
run.</p>
<p>Given the following test file, starting Node.js with the
<code>--test-name-pattern="test [1-3]"</code> option would cause the test runner to execute
<code>test 1</code>, <code>test 2</code>, and <code>test 3</code>. If <code>test 1</code> did not match the test name
pattern, then its subtests would not execute, despite matching the pattern. The
same set of tests could also be executed by passing <code>--test-name-pattern</code>
multiple times (e.g. <code>--test-name-pattern="test 1"</code>,
<code>--test-name-pattern="test 2"</code>, etc.).</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'test 1'</span>, <span class="hljs-keyword">async</span> (t) => {
  <span class="hljs-keyword">await</span> t.<span class="hljs-title function_">test</span>(<span class="hljs-string">'test 2'</span>);
  <span class="hljs-keyword">await</span> t.<span class="hljs-title function_">test</span>(<span class="hljs-string">'test 3'</span>);
});

<span class="hljs-title function_">test</span>(<span class="hljs-string">'Test 4'</span>, <span class="hljs-keyword">async</span> (t) => {
  <span class="hljs-keyword">await</span> t.<span class="hljs-title function_">test</span>(<span class="hljs-string">'Test 5'</span>);
  <span class="hljs-keyword">await</span> t.<span class="hljs-title function_">test</span>(<span class="hljs-string">'test 6'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>Test name patterns can also be specified using regular expression literals. This
allows regular expression flags to be used. In the previous example, starting
Node.js with <code>--test-name-pattern="/test [4-5]/i"</code> would match <code>Test 4</code> and
<code>Test 5</code> because the pattern is case-insensitive.</p>
<p>Test name patterns do not change the set of files that the test runner executes.</p>
</section><section><h3>Extraneous asynchronous activity<span><a class="mark" href="#all_test_extraneous-asynchronous-activity" id="all_test_extraneous-asynchronous-activity">#</a></span><a aria-hidden="true" class="legacy" id="test_extraneous_asynchronous_activity"></a></h3>
<p>Once a test function finishes executing, the results are reported as quickly
as possible while maintaining the order of the tests. However, it is possible
for the test function to generate asynchronous activity that outlives the test
itself. The test runner handles this type of activity, but does not delay the
reporting of test results in order to accommodate it.</p>
<p>In the following example, a test completes with two <code>setImmediate()</code>
operations still outstanding. The first <code>setImmediate()</code> attempts to create a
new subtest. Because the parent test has already finished and output its
results, the new subtest is immediately marked as failed, and reported later
to the <a href="#all_test_class-testsstream" class="type">&#x3C;TestsStream></a>.</p>
<p>The second <code>setImmediate()</code> creates an <code>uncaughtException</code> event.
<code>uncaughtException</code> and <code>unhandledRejection</code> events originating from a completed
test are marked as failed by the <code>test</code> module and reported as diagnostic
warnings at the top level by the <a href="#all_test_class-testsstream" class="type">&#x3C;TestsStream></a>.</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'a test that creates asynchronous activity'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
  <span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></span> {
    t.<span class="hljs-title function_">test</span>(<span class="hljs-string">'subtest that is created too late'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'error1'</span>);
    });
  });

  <span class="hljs-title function_">setImmediate</span>(<span class="hljs-function">() =></span> {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'error2'</span>);
  });

  <span class="hljs-comment">// The test finishes after this line.</span>
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Watch mode<span><a class="mark" href="#all_test_watch-mode" id="all_test_watch-mode">#</a></span><a aria-hidden="true" class="legacy" id="test_watch_mode"></a></h3>
<div class="api_metadata">
<span>Added in: v19.2.0, v18.13.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>The Node.js test runner supports running in watch mode by passing the <code>--watch</code> flag:</p>
<pre><code class="language-bash">node --<span class="hljs-built_in">test</span> --watch</code> <button class="copy-button">copy</button></pre>
<p>In watch mode, the test runner will watch for changes to test files and
their dependencies. When a change is detected, the test runner will
rerun the tests affected by the change.
The test runner will continue to run until the process is terminated.</p>
</section><section><h3>Running tests from the command line<span><a class="mark" href="#all_test_running-tests-from-the-command-line" id="all_test_running-tests-from-the-command-line">#</a></span><a aria-hidden="true" class="legacy" id="test_running_tests_from_the_command_line"></a></h3>
<p>The Node.js test runner can be invoked from the command line by passing the
<a href="#all_cli_--test"><code>--test</code></a> flag:</p>
<pre><code class="language-bash">node --<span class="hljs-built_in">test</span></code> <button class="copy-button">copy</button></pre>
<p>By default, Node.js will recursively search the current directory for
JavaScript source files matching a specific naming convention. Matching files
are executed as test files. More information on the expected test file naming
convention and behavior can be found in the <a href="#all_test_test-runner-execution-model">test runner execution model</a>
section.</p>
<p>Alternatively, one or more paths can be provided as the final argument(s) to
the Node.js command, as shown below.</p>
<pre><code class="language-bash">node --<span class="hljs-built_in">test</span> test1.js test2.mjs custom_test_dir/</code> <button class="copy-button">copy</button></pre>
<p>In this example, the test runner will execute the files <code>test1.js</code> and
<code>test2.mjs</code>. The test runner will also recursively search the
<code>custom_test_dir/</code> directory for test files to execute.</p>
<h4>Test runner execution model<span><a class="mark" href="#all_test_test-runner-execution-model" id="all_test_test-runner-execution-model">#</a></span><a aria-hidden="true" class="legacy" id="test_test_runner_execution_model"></a></h4>
<p>When searching for test files to execute, the test runner behaves as follows:</p>
<ul>
<li>Any files explicitly provided by the user are executed.</li>
<li>If the user did not explicitly specify any paths, the current working
directory is recursively searched for files as specified in the following
steps.</li>
<li><code>node_modules</code> directories are skipped unless explicitly provided by the
user.</li>
<li>If a directory named <code>test</code> is encountered, the test runner will search it
recursively for all all <code>.js</code>, <code>.cjs</code>, and <code>.mjs</code> files. All of these files
are treated as test files, and do not need to match the specific naming
convention detailed below. This is to accommodate projects that place all of
their tests in a single <code>test</code> directory.</li>
<li>In all other directories, <code>.js</code>, <code>.cjs</code>, and <code>.mjs</code> files matching the
following patterns are treated as test files:
<ul>
<li><code>^test$</code> - Files whose basename is the string <code>'test'</code>. Examples:
<code>test.js</code>, <code>test.cjs</code>, <code>test.mjs</code>.</li>
<li><code>^test-.+</code> - Files whose basename starts with the string <code>'test-'</code>
followed by one or more characters. Examples: <code>test-example.js</code>,
<code>test-another-example.mjs</code>.</li>
<li><code>.+[\.\-\_]test$</code> - Files whose basename ends with <code>.test</code>, <code>-test</code>, or
<code>_test</code>, preceded by one or more characters. Examples: <code>example.test.js</code>,
<code>example-test.cjs</code>, <code>example_test.mjs</code>.</li>
<li>Other file types understood by Node.js such as <code>.node</code> and <code>.json</code> are not
automatically executed by the test runner, but are supported if explicitly
provided on the command line.</li>
</ul>
</li>
</ul>
<p>Each matching test file is executed in a separate child process. The maximum
number of child processes running at any time is controlled by the
<a href="#all_cli_--test-concurrency"><code>--test-concurrency</code></a> flag. If the child process finishes with an exit code
of 0, the test is considered passing. Otherwise, the test is considered to be a
failure. Test files must be executable by Node.js, but are not required to use
the <code>node:test</code> module internally.</p>
<p>Each test file is executed as if it was a regular script. That is, if the test
file itself uses <code>node:test</code> to define tests, all of those tests will be
executed within a single application thread, regardless of the value of the
<code>concurrency</code> option of <a href="#all_test_testname-options-fn"><code>test()</code></a>.</p>
</section><section><h3>Collecting code coverage<span><a class="mark" href="#all_test_collecting-code-coverage" id="all_test_collecting-code-coverage">#</a></span><a aria-hidden="true" class="legacy" id="test_collecting_code_coverage"></a></h3>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>When Node.js is started with the <a href="#all_cli_--experimental-test-coverage"><code>--experimental-test-coverage</code></a>
command-line flag, code coverage is collected and statistics are reported once
all tests have completed. If the <a href="#all_cli_node_v8_coveragedir"><code>NODE_V8_COVERAGE</code></a> environment variable is
used to specify a code coverage directory, the generated V8 coverage files are
written to that directory. Node.js core modules and files within
<code>node_modules/</code> directories are, by default, not included in the coverage report.
However, they can be explicity included via the <a href="#all_cli_--test-coverage-include"><code>--test-coverage-include</code></a> flag. If
coverage is enabled, the coverage report is sent to any <a href="#all_test_test-reporters">test reporters</a> via
the <code>'test:coverage'</code> event.</p>
<p>Coverage can be disabled on a series of lines using the following
comment syntax:</p>
<pre><code class="language-js"><span class="hljs-comment">/* node:coverage disable */</span>
<span class="hljs-keyword">if</span> (anAlwaysFalseCondition) {
  <span class="hljs-comment">// Code in this branch will never be executed, but the lines are ignored for</span>
  <span class="hljs-comment">// coverage purposes. All lines following the 'disable' comment are ignored</span>
  <span class="hljs-comment">// until a corresponding 'enable' comment is encountered.</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'this is never executed'</span>);
}
<span class="hljs-comment">/* node:coverage enable */</span></code> <button class="copy-button">copy</button></pre>
<p>Coverage can also be disabled for a specified number of lines. After the
specified number of lines, coverage will be automatically reenabled. If the
number of lines is not explicitly provided, a single line is ignored.</p>
<pre><code class="language-js"><span class="hljs-comment">/* node:coverage ignore next */</span>
<span class="hljs-keyword">if</span> (anAlwaysFalseCondition) { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'this is never executed'</span>); }

<span class="hljs-comment">/* node:coverage ignore next 3 */</span>
<span class="hljs-keyword">if</span> (anAlwaysFalseCondition) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'this is never executed'</span>);
}</code> <button class="copy-button">copy</button></pre>
<h4>Coverage reporters<span><a class="mark" href="#all_test_coverage-reporters" id="all_test_coverage-reporters">#</a></span><a aria-hidden="true" class="legacy" id="test_coverage_reporters"></a></h4>
<p>The tap and spec reporters will print a summary of the coverage statistics.
There is also an lcov reporter that will generate an lcov file which can be
used as an in depth coverage report.</p>
<pre><code class="language-bash">node --<span class="hljs-built_in">test</span> --experimental-test-coverage --test-reporter=lcov --test-reporter-destination=lcov.info</code> <button class="copy-button">copy</button></pre>
<ul>
<li>No test results are reported by this reporter.</li>
<li>This reporter should ideally be used alongside another reporter.</li>
</ul>
<h4>Limitations<span><a class="mark" href="#all_test_limitations" id="all_test_limitations">#</a></span><a aria-hidden="true" class="legacy" id="test_limitations"></a></h4>
<p>The test runner's code coverage functionality does not support excluding
specific files or directories from the coverage report.</p>
</section><section><h3>Mocking<span><a class="mark" href="#all_test_mocking" id="all_test_mocking">#</a></span><a aria-hidden="true" class="legacy" id="test_mocking"></a></h3>
<p>The <code>node:test</code> module supports mocking during testing via a top-level <code>mock</code>
object. The following example creates a spy on a function that adds two numbers
together. The spy is then used to assert that the function was called as
expected.</p>

<pre class="with-39-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> { mock, test } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;

<span class="hljs-title function_">test</span>(<span class="hljs-string">'spies on a function'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-keyword">const</span> sum = mock.<span class="hljs-title function_">fn</span>(<span class="hljs-function">(<span class="hljs-params">a, b</span>) =></span> {
    <span class="hljs-keyword">return</span> a + b;
  });

  assert.<span class="hljs-title function_">strictEqual</span>(sum.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">0</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title function_">sum</span>(<span class="hljs-number">3</span>, <span class="hljs-number">4</span>), <span class="hljs-number">7</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(sum.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);

  <span class="hljs-keyword">const</span> call = sum.<span class="hljs-property">mock</span>.<span class="hljs-property">calls</span>[<span class="hljs-number">0</span>];
  assert.<span class="hljs-title function_">deepStrictEqual</span>(call.<span class="hljs-property">arguments</span>, [<span class="hljs-number">3</span>, <span class="hljs-number">4</span>]);
  assert.<span class="hljs-title function_">strictEqual</span>(call.<span class="hljs-property">result</span>, <span class="hljs-number">7</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(call.<span class="hljs-property">error</span>, <span class="hljs-literal">undefined</span>);

  <span class="hljs-comment">// Reset the globally tracked mocks.</span>
  mock.<span class="hljs-title function_">reset</span>();
});</code><code class="language-js cjs"><span class="hljs-meta">'use strict'</span>;
<span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { mock, test } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);

<span class="hljs-title function_">test</span>(<span class="hljs-string">'spies on a function'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-keyword">const</span> sum = mock.<span class="hljs-title function_">fn</span>(<span class="hljs-function">(<span class="hljs-params">a, b</span>) =></span> {
    <span class="hljs-keyword">return</span> a + b;
  });

  assert.<span class="hljs-title function_">strictEqual</span>(sum.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">0</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title function_">sum</span>(<span class="hljs-number">3</span>, <span class="hljs-number">4</span>), <span class="hljs-number">7</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(sum.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);

  <span class="hljs-keyword">const</span> call = sum.<span class="hljs-property">mock</span>.<span class="hljs-property">calls</span>[<span class="hljs-number">0</span>];
  assert.<span class="hljs-title function_">deepStrictEqual</span>(call.<span class="hljs-property">arguments</span>, [<span class="hljs-number">3</span>, <span class="hljs-number">4</span>]);
  assert.<span class="hljs-title function_">strictEqual</span>(call.<span class="hljs-property">result</span>, <span class="hljs-number">7</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(call.<span class="hljs-property">error</span>, <span class="hljs-literal">undefined</span>);

  <span class="hljs-comment">// Reset the globally tracked mocks.</span>
  mock.<span class="hljs-title function_">reset</span>();
});</code><button class="copy-button">copy</button></pre>
<p>The same mocking functionality is also exposed on the <a href="#all_test_class-testcontext"><code>TestContext</code></a> object
of each test. The following example creates a spy on an object method using the
API exposed on the <code>TestContext</code>. The benefit of mocking via the test context is
that the test runner will automatically restore all mocked functionality once
the test finishes.</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'spies on an object method'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
  <span class="hljs-keyword">const</span> number = {
    <span class="hljs-attr">value</span>: <span class="hljs-number">5</span>,
    <span class="hljs-title function_">add</span>(<span class="hljs-params">a</span>) {
      <span class="hljs-keyword">return</span> <span class="hljs-variable language_">this</span>.<span class="hljs-property">value</span> + a;
    },
  };

  t.<span class="hljs-property">mock</span>.<span class="hljs-title function_">method</span>(number, <span class="hljs-string">'add'</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(number.<span class="hljs-property">add</span>.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">0</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(number.<span class="hljs-title function_">add</span>(<span class="hljs-number">3</span>), <span class="hljs-number">8</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(number.<span class="hljs-property">add</span>.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);

  <span class="hljs-keyword">const</span> call = number.<span class="hljs-property">add</span>.<span class="hljs-property">mock</span>.<span class="hljs-property">calls</span>[<span class="hljs-number">0</span>];

  assert.<span class="hljs-title function_">deepStrictEqual</span>(call.<span class="hljs-property">arguments</span>, [<span class="hljs-number">3</span>]);
  assert.<span class="hljs-title function_">strictEqual</span>(call.<span class="hljs-property">result</span>, <span class="hljs-number">8</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(call.<span class="hljs-property">target</span>, <span class="hljs-literal">undefined</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(call.<span class="hljs-property">this</span>, number);
});</code> <button class="copy-button">copy</button></pre>
<h4>Timers<span><a class="mark" href="#all_test_timers" id="all_test_timers">#</a></span><a aria-hidden="true" class="legacy" id="test_timers"></a></h4>
<p>Mocking timers is a technique commonly used in software testing to simulate and
control the behavior of timers, such as <code>setInterval</code> and <code>setTimeout</code>,
without actually waiting for the specified time intervals.</p>
<p>Refer to the <a href="#all_test_class-mocktimers"><code>MockTimers</code></a> class for a full list of methods and features.</p>
<p>This allows developers to write more reliable and
predictable tests for time-dependent functionality.</p>
<p>The example below shows how to mock <code>setTimeout</code>.
Using <code>.enable({ apis: ['setTimeout'] });</code>
it will mock the <code>setTimeout</code> functions in the <a href="./timers.html">node:timers</a> and
<a href="./timers.html#timers-promises-api">node:timers/promises</a> modules,
as well as from the Node.js global context.</p>
<p><strong>Note:</strong> Destructuring functions such as
<code>import { setTimeout } from 'node:timers'</code>
is currently not supported by this API.</p>

<pre class="with-44-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> { mock, test } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;

<span class="hljs-title function_">test</span>(<span class="hljs-string">'mocks setTimeout to be executed synchronously without having to actually wait for it'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-keyword">const</span> fn = mock.<span class="hljs-title function_">fn</span>();

  <span class="hljs-comment">// Optionally choose what to mock</span>
  mock.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>] });
  <span class="hljs-built_in">setTimeout</span>(fn, <span class="hljs-number">9999</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">0</span>);

  <span class="hljs-comment">// Advance in time</span>
  mock.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(<span class="hljs-number">9999</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);

  <span class="hljs-comment">// Reset the globally tracked mocks.</span>
  mock.<span class="hljs-property">timers</span>.<span class="hljs-title function_">reset</span>();

  <span class="hljs-comment">// If you call reset mock instance, it will also reset timers instance</span>
  mock.<span class="hljs-title function_">reset</span>();
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { mock, test } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);

<span class="hljs-title function_">test</span>(<span class="hljs-string">'mocks setTimeout to be executed synchronously without having to actually wait for it'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-keyword">const</span> fn = mock.<span class="hljs-title function_">fn</span>();

  <span class="hljs-comment">// Optionally choose what to mock</span>
  mock.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>] });
  <span class="hljs-built_in">setTimeout</span>(fn, <span class="hljs-number">9999</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">0</span>);

  <span class="hljs-comment">// Advance in time</span>
  mock.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(<span class="hljs-number">9999</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);

  <span class="hljs-comment">// Reset the globally tracked mocks.</span>
  mock.<span class="hljs-property">timers</span>.<span class="hljs-title function_">reset</span>();

  <span class="hljs-comment">// If you call reset mock instance, it will also reset timers instance</span>
  mock.<span class="hljs-title function_">reset</span>();
});</code><button class="copy-button">copy</button></pre>
<p>The same mocking functionality is also exposed in the mock property on the <a href="#all_test_class-testcontext"><code>TestContext</code></a> object
of each test. The benefit of mocking via the test context is
that the test runner will automatically restore all mocked timers
functionality once the test finishes.</p>

<pre class="with-38-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> { test } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;

<span class="hljs-title function_">test</span>(<span class="hljs-string">'mocks setTimeout to be executed synchronously without having to actually wait for it'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
  <span class="hljs-keyword">const</span> fn = context.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>();

  <span class="hljs-comment">// Optionally choose what to mock</span>
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>] });
  <span class="hljs-built_in">setTimeout</span>(fn, <span class="hljs-number">9999</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">0</span>);

  <span class="hljs-comment">// Advance in time</span>
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(<span class="hljs-number">9999</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { test } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);

<span class="hljs-title function_">test</span>(<span class="hljs-string">'mocks setTimeout to be executed synchronously without having to actually wait for it'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
  <span class="hljs-keyword">const</span> fn = context.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>();

  <span class="hljs-comment">// Optionally choose what to mock</span>
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>] });
  <span class="hljs-built_in">setTimeout</span>(fn, <span class="hljs-number">9999</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">0</span>);

  <span class="hljs-comment">// Advance in time</span>
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(<span class="hljs-number">9999</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);
});</code><button class="copy-button">copy</button></pre>
<h4>Dates<span><a class="mark" href="#all_test_dates" id="all_test_dates">#</a></span><a aria-hidden="true" class="legacy" id="test_dates"></a></h4>
<p>The mock timers API also allows the mocking of the <code>Date</code> object. This is a
useful feature for testing time-dependent functionality, or to simulate
internal calendar functions such as <code>Date.now()</code>.</p>
<p>The dates implementation is also part of the <a href="#all_test_class-mocktimers"><code>MockTimers</code></a> class. Refer to it
for a full list of methods and features.</p>
<p><strong>Note:</strong> Dates and timers are dependent when mocked together. This means that
if you have both the <code>Date</code> and <code>setTimeout</code> mocked, advancing the time will
also advance the mocked date as they simulate a single internal clock.</p>
<p>The example below show how to mock the <code>Date</code> object and obtain the current
<code>Date.now()</code> value.</p>

<pre class="with-38-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> { test } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;

<span class="hljs-title function_">test</span>(<span class="hljs-string">'mocks the Date object'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
  <span class="hljs-comment">// Optionally choose what to mock</span>
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'Date'</span>] });
  <span class="hljs-comment">// If not specified, the initial date will be based on 0 in the UNIX epoch</span>
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">0</span>);

  <span class="hljs-comment">// Advance in time will also advance the date</span>
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(<span class="hljs-number">9999</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">9999</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { test } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);

<span class="hljs-title function_">test</span>(<span class="hljs-string">'mocks the Date object'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
  <span class="hljs-comment">// Optionally choose what to mock</span>
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'Date'</span>] });
  <span class="hljs-comment">// If not specified, the initial date will be based on 0 in the UNIX epoch</span>
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">0</span>);

  <span class="hljs-comment">// Advance in time will also advance the date</span>
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(<span class="hljs-number">9999</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">9999</span>);
});</code><button class="copy-button">copy</button></pre>
<p>If there is no initial epoch set, the initial date will be based on 0 in the
Unix epoch. This is January 1st, 1970, 00:00:00 UTC. You can set an initial date
by passing a <code>now</code> property to the <code>.enable()</code> method. This value will be used
as the initial date for the mocked <code>Date</code> object. It can either be a positive
integer, or another Date object.</p>

<pre class="with-38-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> { test } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;

<span class="hljs-title function_">test</span>(<span class="hljs-string">'mocks the Date object with initial time'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
  <span class="hljs-comment">// Optionally choose what to mock</span>
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'Date'</span>], <span class="hljs-attr">now</span>: <span class="hljs-number">100</span> });
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">100</span>);

  <span class="hljs-comment">// Advance in time will also advance the date</span>
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(<span class="hljs-number">200</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">300</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { test } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);

<span class="hljs-title function_">test</span>(<span class="hljs-string">'mocks the Date object with initial time'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
  <span class="hljs-comment">// Optionally choose what to mock</span>
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'Date'</span>], <span class="hljs-attr">now</span>: <span class="hljs-number">100</span> });
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">100</span>);

  <span class="hljs-comment">// Advance in time will also advance the date</span>
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(<span class="hljs-number">200</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">300</span>);
});</code><button class="copy-button">copy</button></pre>
<p>You can use the <code>.setTime()</code> method to manually move the mocked date to another
time. This method only accepts a positive integer.</p>
<p><strong>Note:</strong> This method will execute any mocked timers that are in the past
from the new time.</p>
<p>In the below example we are setting a new time for the mocked date.</p>

<pre class="with-38-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> { test } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;

<span class="hljs-title function_">test</span>(<span class="hljs-string">'sets the time of a date object'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
  <span class="hljs-comment">// Optionally choose what to mock</span>
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'Date'</span>], <span class="hljs-attr">now</span>: <span class="hljs-number">100</span> });
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">100</span>);

  <span class="hljs-comment">// Advance in time will also advance the date</span>
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">setTime</span>(<span class="hljs-number">1000</span>);
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(<span class="hljs-number">200</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">1200</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { test } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);

<span class="hljs-title function_">test</span>(<span class="hljs-string">'sets the time of a date object'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
  <span class="hljs-comment">// Optionally choose what to mock</span>
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'Date'</span>], <span class="hljs-attr">now</span>: <span class="hljs-number">100</span> });
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">100</span>);

  <span class="hljs-comment">// Advance in time will also advance the date</span>
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">setTime</span>(<span class="hljs-number">1000</span>);
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(<span class="hljs-number">200</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">1200</span>);
});</code><button class="copy-button">copy</button></pre>
<p>If you have any timer that's set to run in the past, it will be executed as if
the <code>.tick()</code> method has been called. This is useful if you want to test
time-dependent functionality that's already in the past.</p>

<pre class="with-38-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> { test } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;

<span class="hljs-title function_">test</span>(<span class="hljs-string">'runs timers as setTime passes ticks'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
  <span class="hljs-comment">// Optionally choose what to mock</span>
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>, <span class="hljs-string">'Date'</span>] });
  <span class="hljs-keyword">const</span> fn = context.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>();
  <span class="hljs-built_in">setTimeout</span>(fn, <span class="hljs-number">1000</span>);

  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">setTime</span>(<span class="hljs-number">800</span>);
  <span class="hljs-comment">// Timer is not executed as the time is not yet reached</span>
  assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">0</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">800</span>);

  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">setTime</span>(<span class="hljs-number">1200</span>);
  <span class="hljs-comment">// Timer is executed as the time is now reached</span>
  assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">1200</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { test } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);

<span class="hljs-title function_">test</span>(<span class="hljs-string">'runs timers as setTime passes ticks'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
  <span class="hljs-comment">// Optionally choose what to mock</span>
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>, <span class="hljs-string">'Date'</span>] });
  <span class="hljs-keyword">const</span> fn = context.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>();
  <span class="hljs-built_in">setTimeout</span>(fn, <span class="hljs-number">1000</span>);

  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">setTime</span>(<span class="hljs-number">800</span>);
  <span class="hljs-comment">// Timer is not executed as the time is not yet reached</span>
  assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">0</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">800</span>);

  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">setTime</span>(<span class="hljs-number">1200</span>);
  <span class="hljs-comment">// Timer is executed as the time is now reached</span>
  assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">1200</span>);
});</code><button class="copy-button">copy</button></pre>
<p>Using <code>.runAll()</code> will execute all timers that are currently in the queue. This
will also advance the mocked date to the time of the last timer that was
executed as if the time has passed.</p>

<pre class="with-38-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> { test } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;

<span class="hljs-title function_">test</span>(<span class="hljs-string">'runs timers as setTime passes ticks'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
  <span class="hljs-comment">// Optionally choose what to mock</span>
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>, <span class="hljs-string">'Date'</span>] });
  <span class="hljs-keyword">const</span> fn = context.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>();
  <span class="hljs-built_in">setTimeout</span>(fn, <span class="hljs-number">1000</span>);
  <span class="hljs-built_in">setTimeout</span>(fn, <span class="hljs-number">2000</span>);
  <span class="hljs-built_in">setTimeout</span>(fn, <span class="hljs-number">3000</span>);

  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">runAll</span>();
  <span class="hljs-comment">// All timers are executed as the time is now reached</span>
  assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">3</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">3000</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { test } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);

<span class="hljs-title function_">test</span>(<span class="hljs-string">'runs timers as setTime passes ticks'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
  <span class="hljs-comment">// Optionally choose what to mock</span>
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>, <span class="hljs-string">'Date'</span>] });
  <span class="hljs-keyword">const</span> fn = context.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>();
  <span class="hljs-built_in">setTimeout</span>(fn, <span class="hljs-number">1000</span>);
  <span class="hljs-built_in">setTimeout</span>(fn, <span class="hljs-number">2000</span>);
  <span class="hljs-built_in">setTimeout</span>(fn, <span class="hljs-number">3000</span>);

  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">runAll</span>();
  <span class="hljs-comment">// All timers are executed as the time is now reached</span>
  assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">3</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">3000</span>);
});</code><button class="copy-button">copy</button></pre>
</section><section><h3>Test reporters<span><a class="mark" href="#all_test_test-reporters" id="all_test_test-reporters">#</a></span><a aria-hidden="true" class="legacy" id="test_test_reporters"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.9.0</td>
<td><p>Reporters are now exposed at <code>node:test/reporters</code>.</p></td></tr>
<tr><td>v19.6.0, v18.15.0</td>
<td><p><span>Added in: v19.6.0, v18.15.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>The <code>node:test</code> module supports passing <a href="#all_cli_--test-reporter"><code>--test-reporter</code></a>
flags for the test runner to use a specific reporter.</p>
<p>The following built-reporters are supported:</p>
<ul>
<li>
<p><code>tap</code>
The <code>tap</code> reporter outputs the test results in the <a href="https://testanything.org/">TAP</a> format.</p>
</li>
<li>
<p><code>spec</code>
The <code>spec</code> reporter outputs the test results in a human-readable format.</p>
</li>
<li>
<p><code>dot</code>
The <code>dot</code> reporter outputs the test results in a compact format,
where each passing test is represented by a <code>.</code>,
and each failing test is represented by a <code>X</code>.</p>
</li>
<li>
<p><code>junit</code>
The junit reporter outputs test results in a jUnit XML format</p>
</li>
<li>
<p><code>lcov</code>
The <code>lcov</code> reporter outputs test coverage when used with the
<a href="#all_cli_--experimental-test-coverage"><code>--experimental-test-coverage</code></a> flag.</p>
</li>
</ul>
<p>When <code>stdout</code> is a <a href="tty.html">TTY</a>, the <code>spec</code> reporter is used by default.
Otherwise, the <code>tap</code> reporter is used by default.</p>
<p>The exact output of these reporters is subject to change between versions of
Node.js, and should not be relied on programmatically. If programmatic access
to the test runner's output is required, use the events emitted by the
<a href="#all_test_class-testsstream" class="type">&#x3C;TestsStream></a>.</p>
<p>The reporters are available via the <code>node:test/reporters</code> module:</p>

<pre class="with-71-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { tap, spec, dot, junit, lcov } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test/reporters'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { tap, spec, dot, junit, lcov } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test/reporters'</span>);</code><button class="copy-button">copy</button></pre>
<h4>Custom reporters<span><a class="mark" href="#all_test_custom-reporters" id="all_test_custom-reporters">#</a></span><a aria-hidden="true" class="legacy" id="test_custom_reporters"></a></h4>
<p><a href="#all_cli_--test-reporter"><code>--test-reporter</code></a> can be used to specify a path to custom reporter.
A custom reporter is a module that exports a value
accepted by <a href="#all_stream_streamcomposestreams">stream.compose</a>.
Reporters should transform events emitted by a <a href="#all_test_class-testsstream" class="type">&#x3C;TestsStream></a></p>
<p>Example of a custom reporter using <a href="#all_stream_class-streamtransform" class="type">&#x3C;stream.Transform></a>:</p>

<pre class="with-45-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Transform</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;

<span class="hljs-keyword">const</span> customReporter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Transform</span>({
  <span class="hljs-attr">writableObjectMode</span>: <span class="hljs-literal">true</span>,
  <span class="hljs-title function_">transform</span>(<span class="hljs-params">event, encoding, callback</span>) {
    <span class="hljs-keyword">switch</span> (event.<span class="hljs-property">type</span>) {
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:dequeue'</span>:
        <span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-string">`test <span class="hljs-subst">${event.data.name}</span> dequeued`</span>);
        <span class="hljs-keyword">break</span>;
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:enqueue'</span>:
        <span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-string">`test <span class="hljs-subst">${event.data.name}</span> enqueued`</span>);
        <span class="hljs-keyword">break</span>;
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:watch:drained'</span>:
        <span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-string">'test watch queue drained'</span>);
        <span class="hljs-keyword">break</span>;
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:start'</span>:
        <span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-string">`test <span class="hljs-subst">${event.data.name}</span> started`</span>);
        <span class="hljs-keyword">break</span>;
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:pass'</span>:
        <span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-string">`test <span class="hljs-subst">${event.data.name}</span> passed`</span>);
        <span class="hljs-keyword">break</span>;
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:fail'</span>:
        <span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-string">`test <span class="hljs-subst">${event.data.name}</span> failed`</span>);
        <span class="hljs-keyword">break</span>;
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:plan'</span>:
        <span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-string">'test plan'</span>);
        <span class="hljs-keyword">break</span>;
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:diagnostic'</span>:
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:stderr'</span>:
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:stdout'</span>:
        <span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, event.<span class="hljs-property">data</span>.<span class="hljs-property">message</span>);
        <span class="hljs-keyword">break</span>;
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:coverage'</span>: {
        <span class="hljs-keyword">const</span> { totalLineCount } = event.<span class="hljs-property">data</span>.<span class="hljs-property">summary</span>.<span class="hljs-property">totals</span>;
        <span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-string">`total line count: <span class="hljs-subst">${totalLineCount}</span>\n`</span>);
        <span class="hljs-keyword">break</span>;
      }
    }
  },
});

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> customReporter;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Transform</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);

<span class="hljs-keyword">const</span> customReporter = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Transform</span>({
  <span class="hljs-attr">writableObjectMode</span>: <span class="hljs-literal">true</span>,
  <span class="hljs-title function_">transform</span>(<span class="hljs-params">event, encoding, callback</span>) {
    <span class="hljs-keyword">switch</span> (event.<span class="hljs-property">type</span>) {
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:dequeue'</span>:
        <span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-string">`test <span class="hljs-subst">${event.data.name}</span> dequeued`</span>);
        <span class="hljs-keyword">break</span>;
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:enqueue'</span>:
        <span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-string">`test <span class="hljs-subst">${event.data.name}</span> enqueued`</span>);
        <span class="hljs-keyword">break</span>;
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:watch:drained'</span>:
        <span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-string">'test watch queue drained'</span>);
        <span class="hljs-keyword">break</span>;
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:start'</span>:
        <span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-string">`test <span class="hljs-subst">${event.data.name}</span> started`</span>);
        <span class="hljs-keyword">break</span>;
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:pass'</span>:
        <span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-string">`test <span class="hljs-subst">${event.data.name}</span> passed`</span>);
        <span class="hljs-keyword">break</span>;
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:fail'</span>:
        <span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-string">`test <span class="hljs-subst">${event.data.name}</span> failed`</span>);
        <span class="hljs-keyword">break</span>;
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:plan'</span>:
        <span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-string">'test plan'</span>);
        <span class="hljs-keyword">break</span>;
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:diagnostic'</span>:
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:stderr'</span>:
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:stdout'</span>:
        <span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, event.<span class="hljs-property">data</span>.<span class="hljs-property">message</span>);
        <span class="hljs-keyword">break</span>;
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:coverage'</span>: {
        <span class="hljs-keyword">const</span> { totalLineCount } = event.<span class="hljs-property">data</span>.<span class="hljs-property">summary</span>.<span class="hljs-property">totals</span>;
        <span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-string">`total line count: <span class="hljs-subst">${totalLineCount}</span>\n`</span>);
        <span class="hljs-keyword">break</span>;
      }
    }
  },
});

<span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = customReporter;</code><button class="copy-button">copy</button></pre>
<p>Example of a custom reporter using a generator function:</p>

<pre class="with-58-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> * <span class="hljs-title function_">customReporter</span>(<span class="hljs-params">source</span>) {
  <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> event <span class="hljs-keyword">of</span> source) {
    <span class="hljs-keyword">switch</span> (event.<span class="hljs-property">type</span>) {
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:dequeue'</span>:
        <span class="hljs-keyword">yield</span> <span class="hljs-string">`test <span class="hljs-subst">${event.data.name}</span> dequeued\n`</span>;
        <span class="hljs-keyword">break</span>;
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:enqueue'</span>:
        <span class="hljs-keyword">yield</span> <span class="hljs-string">`test <span class="hljs-subst">${event.data.name}</span> enqueued\n`</span>;
        <span class="hljs-keyword">break</span>;
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:watch:drained'</span>:
        <span class="hljs-keyword">yield</span> <span class="hljs-string">'test watch queue drained\n'</span>;
        <span class="hljs-keyword">break</span>;
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:start'</span>:
        <span class="hljs-keyword">yield</span> <span class="hljs-string">`test <span class="hljs-subst">${event.data.name}</span> started\n`</span>;
        <span class="hljs-keyword">break</span>;
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:pass'</span>:
        <span class="hljs-keyword">yield</span> <span class="hljs-string">`test <span class="hljs-subst">${event.data.name}</span> passed\n`</span>;
        <span class="hljs-keyword">break</span>;
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:fail'</span>:
        <span class="hljs-keyword">yield</span> <span class="hljs-string">`test <span class="hljs-subst">${event.data.name}</span> failed\n`</span>;
        <span class="hljs-keyword">break</span>;
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:plan'</span>:
        <span class="hljs-keyword">yield</span> <span class="hljs-string">'test plan\n'</span>;
        <span class="hljs-keyword">break</span>;
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:diagnostic'</span>:
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:stderr'</span>:
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:stdout'</span>:
        <span class="hljs-keyword">yield</span> <span class="hljs-string">`<span class="hljs-subst">${event.data.message}</span>\n`</span>;
        <span class="hljs-keyword">break</span>;
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:coverage'</span>: {
        <span class="hljs-keyword">const</span> { totalLineCount } = event.<span class="hljs-property">data</span>.<span class="hljs-property">summary</span>.<span class="hljs-property">totals</span>;
        <span class="hljs-keyword">yield</span> <span class="hljs-string">`total line count: <span class="hljs-subst">${totalLineCount}</span>\n`</span>;
        <span class="hljs-keyword">break</span>;
      }
    }
  }
}</code><code class="language-js cjs"><span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> * <span class="hljs-title function_">customReporter</span>(<span class="hljs-params">source</span>) {
  <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> event <span class="hljs-keyword">of</span> source) {
    <span class="hljs-keyword">switch</span> (event.<span class="hljs-property">type</span>) {
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:dequeue'</span>:
        <span class="hljs-keyword">yield</span> <span class="hljs-string">`test <span class="hljs-subst">${event.data.name}</span> dequeued\n`</span>;
        <span class="hljs-keyword">break</span>;
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:enqueue'</span>:
        <span class="hljs-keyword">yield</span> <span class="hljs-string">`test <span class="hljs-subst">${event.data.name}</span> enqueued\n`</span>;
        <span class="hljs-keyword">break</span>;
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:watch:drained'</span>:
        <span class="hljs-keyword">yield</span> <span class="hljs-string">'test watch queue drained\n'</span>;
        <span class="hljs-keyword">break</span>;
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:start'</span>:
        <span class="hljs-keyword">yield</span> <span class="hljs-string">`test <span class="hljs-subst">${event.data.name}</span> started\n`</span>;
        <span class="hljs-keyword">break</span>;
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:pass'</span>:
        <span class="hljs-keyword">yield</span> <span class="hljs-string">`test <span class="hljs-subst">${event.data.name}</span> passed\n`</span>;
        <span class="hljs-keyword">break</span>;
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:fail'</span>:
        <span class="hljs-keyword">yield</span> <span class="hljs-string">`test <span class="hljs-subst">${event.data.name}</span> failed\n`</span>;
        <span class="hljs-keyword">break</span>;
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:plan'</span>:
        <span class="hljs-keyword">yield</span> <span class="hljs-string">'test plan\n'</span>;
        <span class="hljs-keyword">break</span>;
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:diagnostic'</span>:
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:stderr'</span>:
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:stdout'</span>:
        <span class="hljs-keyword">yield</span> <span class="hljs-string">`<span class="hljs-subst">${event.data.message}</span>\n`</span>;
        <span class="hljs-keyword">break</span>;
      <span class="hljs-keyword">case</span> <span class="hljs-string">'test:coverage'</span>: {
        <span class="hljs-keyword">const</span> { totalLineCount } = event.<span class="hljs-property">data</span>.<span class="hljs-property">summary</span>.<span class="hljs-property">totals</span>;
        <span class="hljs-keyword">yield</span> <span class="hljs-string">`total line count: <span class="hljs-subst">${totalLineCount}</span>\n`</span>;
        <span class="hljs-keyword">break</span>;
      }
    }
  }
};</code><button class="copy-button">copy</button></pre>
<p>The value provided to <code>--test-reporter</code> should be a string like one used in an
<code>import()</code> in JavaScript code, or a value provided for <a href="#all_cli_--importmodule"><code>--import</code></a>.</p>
<h4>Multiple reporters<span><a class="mark" href="#all_test_multiple-reporters" id="all_test_multiple-reporters">#</a></span><a aria-hidden="true" class="legacy" id="test_multiple_reporters"></a></h4>
<p>The <a href="#all_cli_--test-reporter"><code>--test-reporter</code></a> flag can be specified multiple times to report test
results in several formats. In this situation
it is required to specify a destination for each reporter
using <a href="#all_cli_--test-reporter-destination"><code>--test-reporter-destination</code></a>.
Destination can be <code>stdout</code>, <code>stderr</code>, or a file path.
Reporters and destinations are paired according
to the order they were specified.</p>
<p>In the following example, the <code>spec</code> reporter will output to <code>stdout</code>,
and the <code>dot</code> reporter will output to <code>file.txt</code>:</p>
<pre><code class="language-bash">node --test-reporter=spec --test-reporter=dot --test-reporter-destination=stdout --test-reporter-destination=file.txt</code> <button class="copy-button">copy</button></pre>
<p>When a single reporter is specified, the destination will default to <code>stdout</code>,
unless a destination is explicitly provided.</p>
</section><section><h3><code>run([options])</code><span><a class="mark" href="#all_test_runoptions" id="all_test_runoptions">#</a></span><a aria-hidden="true" class="legacy" id="test_run_options"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.14.0</td>
<td><p>Added the <code>forceExit</code> option.</p></td></tr>
<tr><td>v20.1.0, v18.17.0</td>
<td><p>Add a testNamePatterns option.</p></td></tr>
<tr><td>v18.9.0, v16.19.0</td>
<td><p><span>Added in: v18.9.0, v16.19.0</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> Configuration options for running tests. The following
properties are supported:
<ul>
<li><code>concurrency</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#Boolean_type" class="type">&#x3C;boolean></a> If a number is provided,
then that many test processes would run in parallel, where each process
corresponds to one test file.
If <code>true</code>, it would run <code>os.availableParallelism() - 1</code> test files in
parallel.
If <code>false</code>, it would only run one test file at a time.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>files</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 list of files to run.
<strong>Default</strong> matching files from <a href="#all_test_test-runner-execution-model">test runner execution model</a>.</li>
<li><code>forceExit</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Configures the test runner to exit the process once
all known tests have finished executing even if the event loop would
otherwise remain active. <strong>Default:</strong> <code>false</code>.</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 test child process.
This can be a number, or a function that takes no arguments and returns a
number. If a nullish value is provided, each process gets its own port,
incremented from the primary's <code>process.debugPort</code>.
<strong>Default:</strong> <code>undefined</code>.</li>
<li><code>only</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If truthy, the test context will only run tests that
have the <code>only</code> option set</li>
<li><code>setup</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> A function that accepts the <code>TestsStream</code> instance
and can be used to setup listeners before any tests are run.
<strong>Default:</strong> <code>undefined</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> Allows aborting an in-progress test execution.</li>
<li><code>testNamePatterns</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/RegExp" class="type">&#x3C;RegExp></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type">&#x3C;Array></a> A String, RegExp or a RegExp Array,
that can be used to only run tests whose name matches the provided pattern.
Test name patterns are interpreted as JavaScript regular expressions.
For each test that is executed, any corresponding test hooks, such as
<code>beforeEach()</code>, are also run.
<strong>Default:</strong> <code>undefined</code>.</li>
<li><code>testSkipPatterns</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/RegExp" class="type">&#x3C;RegExp></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type">&#x3C;Array></a> A String, RegExp or a RegExp Array,
that can be used to exclude running tests whose name matches the provided pattern.
Test name patterns are interpreted as JavaScript regular expressions.
For each test that is executed, any corresponding test hooks, such as
<code>beforeEach()</code>, are also run.
<strong>Default:</strong> <code>undefined</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> A number of milliseconds the test execution will
fail after.
If unspecified, subtests inherit this value from their parent.
<strong>Default:</strong> <code>Infinity</code>.</li>
<li><code>watch</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Whether to run in watch mode or not. <strong>Default:</strong> <code>false</code>.</li>
<li><code>shard</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Running tests in a specific shard. <strong>Default:</strong> <code>undefined</code>.
<ul>
<li><code>index</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> is a positive integer between 1 and <code>&#x3C;total></code>
that specifies the index of the shard to run. This option is <em>required</em>.</li>
<li><code>total</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> is a positive integer that specifies the total number
of shards to split the test files to. This option is <em>required</em>.</li>
</ul>
</li>
</ul>
</li>
<li>Returns: <a href="#all_test_class-testsstream" class="type">&#x3C;TestsStream></a></li>
</ul>
<p><strong>Note:</strong> <code>shard</code> is used to horizontally parallelize test running across
machines or processes, ideal for large-scale executions across varied
environments. It's incompatible with <code>watch</code> mode, tailored for rapid
code iteration by automatically rerunning tests on file changes.</p>

<pre class="with-47-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { tap } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test/reporters'</span>;
<span class="hljs-keyword">import</span> { run } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;
<span class="hljs-keyword">import</span> process <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;
<span class="hljs-keyword">import</span> path <span class="hljs-keyword">from</span> <span class="hljs-string">'node:path'</span>;

<span class="hljs-title function_">run</span>({ <span class="hljs-attr">files</span>: [path.<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'./tests/test.js'</span>)] })
 .<span class="hljs-title function_">on</span>(<span class="hljs-string">'test:fail'</span>, <span class="hljs-function">() =></span> {
   process.<span class="hljs-property">exitCode</span> = <span class="hljs-number">1</span>;
 })
 .<span class="hljs-title function_">compose</span>(tap)
 .<span class="hljs-title function_">pipe</span>(process.<span class="hljs-property">stdout</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { tap } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test/reporters'</span>);
<span class="hljs-keyword">const</span> { run } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);
<span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:path'</span>);

<span class="hljs-title function_">run</span>({ <span class="hljs-attr">files</span>: [path.<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'./tests/test.js'</span>)] })
 .<span class="hljs-title function_">on</span>(<span class="hljs-string">'test:fail'</span>, <span class="hljs-function">() =></span> {
   process.<span class="hljs-property">exitCode</span> = <span class="hljs-number">1</span>;
 })
 .<span class="hljs-title function_">compose</span>(tap)
 .<span class="hljs-title function_">pipe</span>(process.<span class="hljs-property">stdout</span>);</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>suite([name][, options][, fn])</code><span><a class="mark" href="#all_test_suitename-options-fn" id="all_test_suitename-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_suite_name_options_fn"></a></h3>
<div class="api_metadata">
<span>Added in: v20.13.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> The name of the suite, which is displayed when reporting test
results. <strong>Default:</strong> The <code>name</code> property of <code>fn</code>, or <code>'&#x3C;anonymous>'</code> if <code>fn</code>
does not have a name.</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> Optional configuration options for the suite.
This supports the same options as <code>test([name][, options][, fn])</code>.</li>
<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://tc39.es/ecma262/#sec-async-function-constructor" class="type">&#x3C;AsyncFunction></a> The suite function declaring nested tests and
suites. The first argument to this function is a <a href="#all_test_class-suitecontext"><code>SuiteContext</code></a> object.
<strong>Default:</strong> A no-op function.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> Immediately fulfilled with <code>undefined</code>.</li>
</ul>
<p>The <code>suite()</code> function is imported from the <code>node:test</code> module.</p>
</section><section><h3><code>suite.skip([name][, options][, fn])</code><span><a class="mark" href="#all_test_suiteskipname-options-fn" id="all_test_suiteskipname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_suite_skip_name_options_fn"></a></h3>
<div class="api_metadata">
<span>Added in: v20.13.0</span>
</div>
<p>Shorthand for skipping a suite. This is the same as
<a href="#all_test_suitename-options-fn"><code>suite([name], { skip: true }[, fn])</code></a>.</p>
</section><section><h3><code>suite.todo([name][, options][, fn])</code><span><a class="mark" href="#all_test_suitetodoname-options-fn" id="all_test_suitetodoname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_suite_todo_name_options_fn"></a></h3>
<div class="api_metadata">
<span>Added in: v20.13.0</span>
</div>
<p>Shorthand for marking a suite as <code>TODO</code>. This is the same as
<a href="#all_test_suitename-options-fn"><code>suite([name], { todo: true }[, fn])</code></a>.</p>
</section><section><h3><code>suite.only([name][, options][, fn])</code><span><a class="mark" href="#all_test_suiteonlyname-options-fn" id="all_test_suiteonlyname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_suite_only_name_options_fn"></a></h3>
<div class="api_metadata">
<span>Added in: v20.13.0</span>
</div>
<p>Shorthand for marking a suite as <code>only</code>. This is the same as
<a href="#all_test_suitename-options-fn"><code>suite([name], { only: true }[, fn])</code></a>.</p>
</section><section><h3><code>test([name][, options][, fn])</code><span><a class="mark" href="#all_test_testname-options-fn" id="all_test_testname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_test_name_options_fn"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.2.0</td>
<td><p>Added the <code>skip</code>, <code>todo</code>, and <code>only</code> shorthands.</p></td></tr>
<tr><td>v18.8.0, v16.18.0</td>
<td><p>Add a <code>signal</code> option.</p></td></tr>
<tr><td>v18.7.0, v16.17.0</td>
<td><p>Add a <code>timeout</code> option.</p></td></tr>
<tr><td>v18.0.0, v16.17.0</td>
<td><p><span>Added in: v18.0.0, v16.17.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> The name of the test, which is displayed when reporting test
results. <strong>Default:</strong> The <code>name</code> property of <code>fn</code>, or <code>'&#x3C;anonymous>'</code> if <code>fn</code>
does not have a name.</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> Configuration options for the test. The following
properties are supported:
<ul>
<li><code>concurrency</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#Boolean_type" class="type">&#x3C;boolean></a> If a number is provided,
then that many tests would run in parallel within the application thread.
If <code>true</code>, all scheduled asynchronous tests run concurrently within the
thread. If <code>false</code>, only one test runs at a time.
If unspecified, subtests inherit this value from their parent.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>only</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If truthy, and the test context is configured to run
<code>only</code> tests, then this test will be run. Otherwise, the test is skipped.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> Allows aborting an in-progress test.</li>
<li><code>skip</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 truthy, the test is skipped. If a string is
provided, that string is displayed in the test results as the reason for
skipping the test. <strong>Default:</strong> <code>false</code>.</li>
<li><code>todo</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 truthy, the test marked as <code>TODO</code>. If a string
is provided, that string is displayed in the test results as the reason why
the test is <code>TODO</code>. <strong>Default:</strong> <code>false</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> A number of milliseconds the test will fail after.
If unspecified, subtests inherit this value from their parent.
<strong>Default:</strong> <code>Infinity</code>.</li>
<li><code>plan</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The number of assertions and subtests expected to be run in the test.
If the number of assertions run in the test does not match the number
specified in the plan, the test will fail.
<strong>Default:</strong> <code>undefined</code>.</li>
</ul>
</li>
<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://tc39.es/ecma262/#sec-async-function-constructor" class="type">&#x3C;AsyncFunction></a> The function under test. The first argument
to this function is a <a href="#all_test_class-testcontext"><code>TestContext</code></a> object. If the test uses callbacks,
the callback function is passed as the second argument. <strong>Default:</strong> A no-op
function.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> Fulfilled with <code>undefined</code> once
the test completes, or immediately if the test runs within a suite.</li>
</ul>
<p>The <code>test()</code> function is the value imported from the <code>test</code> module. Each
invocation of this function results in reporting the test to the <a href="#all_test_class-testsstream" class="type">&#x3C;TestsStream></a>.</p>
<p>The <code>TestContext</code> object passed to the <code>fn</code> argument can be used to perform
actions related to the current test. Examples include skipping the test, adding
additional diagnostic information, or creating subtests.</p>
<p><code>test()</code> returns a <code>Promise</code> that fulfills once the test completes.
if <code>test()</code> is called within a suite, it fulfills immediately.
The return value can usually be discarded for top level tests.
However, the return value from subtests should be used to prevent the parent
test from finishing first and cancelling the subtest
as shown in the following example.</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'top level test'</span>, <span class="hljs-keyword">async</span> (t) => {
  <span class="hljs-comment">// The setTimeout() in the following subtest would cause it to outlive its</span>
  <span class="hljs-comment">// parent test if 'await' is removed on the next line. Once the parent test</span>
  <span class="hljs-comment">// completes, it will cancel any outstanding subtests.</span>
  <span class="hljs-keyword">await</span> t.<span class="hljs-title function_">test</span>(<span class="hljs-string">'longer running subtest'</span>, <span class="hljs-keyword">async</span> (t) => {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =></span> {
      <span class="hljs-built_in">setTimeout</span>(resolve, <span class="hljs-number">1000</span>);
    });
  });
});</code> <button class="copy-button">copy</button></pre>
<p>The <code>timeout</code> option can be used to fail the test if it takes longer than
<code>timeout</code> milliseconds to complete. However, it is not a reliable mechanism for
canceling tests because a running test might block the application thread and
thus prevent the scheduled cancellation.</p>
</section><section><h3><code>test.skip([name][, options][, fn])</code><span><a class="mark" href="#all_test_testskipname-options-fn" id="all_test_testskipname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_test_skip_name_options_fn"></a></h3>
<p>Shorthand for skipping a test,
same as <a href="#all_test_testname-options-fn"><code>test([name], { skip: true }[, fn])</code></a>.</p>
</section><section><h3><code>test.todo([name][, options][, fn])</code><span><a class="mark" href="#all_test_testtodoname-options-fn" id="all_test_testtodoname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_test_todo_name_options_fn"></a></h3>
<p>Shorthand for marking a test as <code>TODO</code>,
same as <a href="#all_test_testname-options-fn"><code>test([name], { todo: true }[, fn])</code></a>.</p>
</section><section><h3><code>test.only([name][, options][, fn])</code><span><a class="mark" href="#all_test_testonlyname-options-fn" id="all_test_testonlyname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_test_only_name_options_fn"></a></h3>
<p>Shorthand for marking a test as <code>only</code>,
same as <a href="#all_test_testname-options-fn"><code>test([name], { only: true }[, fn])</code></a>.</p>
</section><section><h3><code>describe([name][, options][, fn])</code><span><a class="mark" href="#all_test_describename-options-fn" id="all_test_describename-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_describe_name_options_fn"></a></h3>
<p>Alias for <a href="#all_test_suitename-options-fn"><code>suite()</code></a>.</p>
<p>The <code>describe()</code> function is imported from the <code>node:test</code> module.</p>
</section><section><h3><code>describe.skip([name][, options][, fn])</code><span><a class="mark" href="#all_test_describeskipname-options-fn" id="all_test_describeskipname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_describe_skip_name_options_fn"></a></h3>
<p>Shorthand for skipping a suite. This is the same as
<a href="#all_test_describename-options-fn"><code>describe([name], { skip: true }[, fn])</code></a>.</p>
</section><section><h3><code>describe.todo([name][, options][, fn])</code><span><a class="mark" href="#all_test_describetodoname-options-fn" id="all_test_describetodoname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_describe_todo_name_options_fn"></a></h3>
<p>Shorthand for marking a suite as <code>TODO</code>. This is the same as
<a href="#all_test_describename-options-fn"><code>describe([name], { todo: true }[, fn])</code></a>.</p>
</section><section><h3><code>describe.only([name][, options][, fn])</code><span><a class="mark" href="#all_test_describeonlyname-options-fn" id="all_test_describeonlyname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_describe_only_name_options_fn"></a></h3>
<div class="api_metadata">
<span>Added in: v19.8.0, v18.15.0</span>
</div>
<p>Shorthand for marking a suite as <code>only</code>. This is the same as
<a href="#all_test_describename-options-fn"><code>describe([name], { only: true }[, fn])</code></a>.</p>
</section><section><h3><code>it([name][, options][, fn])</code><span><a class="mark" href="#all_test_itname-options-fn" id="all_test_itname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_it_name_options_fn"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.8.0</td>
<td><p>Calling <code>it()</code> is now equivalent to calling <code>test()</code>.</p></td></tr>
<tr><td>v18.6.0, v16.17.0</td>
<td><p><span>Added in: v18.6.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Alias for <a href="#all_test_testname-options-fn"><code>test()</code></a>.</p>
<p>The <code>it()</code> function is imported from the <code>node:test</code> module.</p>
</section><section><h3><code>it.skip([name][, options][, fn])</code><span><a class="mark" href="#all_test_itskipname-options-fn" id="all_test_itskipname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_it_skip_name_options_fn"></a></h3>
<p>Shorthand for skipping a test,
same as <a href="#all_test_testname-options-fn"><code>it([name], { skip: true }[, fn])</code></a>.</p>
</section><section><h3><code>it.todo([name][, options][, fn])</code><span><a class="mark" href="#all_test_ittodoname-options-fn" id="all_test_ittodoname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_it_todo_name_options_fn"></a></h3>
<p>Shorthand for marking a test as <code>TODO</code>,
same as <a href="#all_test_testname-options-fn"><code>it([name], { todo: true }[, fn])</code></a>.</p>
</section><section><h3><code>it.only([name][, options][, fn])</code><span><a class="mark" href="#all_test_itonlyname-options-fn" id="all_test_itonlyname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_it_only_name_options_fn"></a></h3>
<div class="api_metadata">
<span>Added in: v19.8.0, v18.15.0</span>
</div>
<p>Shorthand for marking a test as <code>only</code>,
same as <a href="#all_test_testname-options-fn"><code>it([name], { only: true }[, fn])</code></a>.</p>
</section><section><h3><code>before([fn][, options])</code><span><a class="mark" href="#all_test_beforefn-options" id="all_test_beforefn-options">#</a></span><a aria-hidden="true" class="legacy" id="test_before_fn_options"></a></h3>
<div class="api_metadata">
<span>Added in: v18.8.0, v16.18.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://tc39.es/ecma262/#sec-async-function-constructor" class="type">&#x3C;AsyncFunction></a> The hook function.
If the hook uses callbacks,
the callback function is passed as the second argument. <strong>Default:</strong> A no-op
function.</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> Configuration options for the hook. The following
properties are supported:
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> Allows aborting an in-progress hook.</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 of milliseconds the hook will fail after.
If unspecified, subtests inherit this value from their parent.
<strong>Default:</strong> <code>Infinity</code>.</li>
</ul>
</li>
</ul>
<p>This function creates a hook that runs before executing a suite.</p>
<pre><code class="language-js"><span class="hljs-title function_">describe</span>(<span class="hljs-string">'tests'</span>, <span class="hljs-keyword">async</span> () => {
  <span class="hljs-title function_">before</span>(<span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'about to run some test'</span>));
  <span class="hljs-title function_">it</span>(<span class="hljs-string">'is a subtest'</span>, <span class="hljs-function">() =></span> {
    assert.<span class="hljs-title function_">ok</span>(<span class="hljs-string">'some relevant assertion here'</span>);
  });
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>after([fn][, options])</code><span><a class="mark" href="#all_test_afterfn-options" id="all_test_afterfn-options">#</a></span><a aria-hidden="true" class="legacy" id="test_after_fn_options"></a></h3>
<div class="api_metadata">
<span>Added in: v18.8.0, v16.18.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://tc39.es/ecma262/#sec-async-function-constructor" class="type">&#x3C;AsyncFunction></a> The hook function.
If the hook uses callbacks,
the callback function is passed as the second argument. <strong>Default:</strong> A no-op
function.</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> Configuration options for the hook. The following
properties are supported:
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> Allows aborting an in-progress hook.</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 of milliseconds the hook will fail after.
If unspecified, subtests inherit this value from their parent.
<strong>Default:</strong> <code>Infinity</code>.</li>
</ul>
</li>
</ul>
<p>This function creates a hook that runs after executing a suite.</p>
<pre><code class="language-js"><span class="hljs-title function_">describe</span>(<span class="hljs-string">'tests'</span>, <span class="hljs-keyword">async</span> () => {
  <span class="hljs-title function_">after</span>(<span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'finished running tests'</span>));
  <span class="hljs-title function_">it</span>(<span class="hljs-string">'is a subtest'</span>, <span class="hljs-function">() =></span> {
    assert.<span class="hljs-title function_">ok</span>(<span class="hljs-string">'some relevant assertion here'</span>);
  });
});</code> <button class="copy-button">copy</button></pre>
<p><strong>Note:</strong> The <code>after</code> hook is guaranteed to run,
even if tests within the suite fail.</p>
</section><section><h3><code>beforeEach([fn][, options])</code><span><a class="mark" href="#all_test_beforeeachfn-options" id="all_test_beforeeachfn-options">#</a></span><a aria-hidden="true" class="legacy" id="test_beforeeach_fn_options"></a></h3>
<div class="api_metadata">
<span>Added in: v18.8.0, v16.18.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://tc39.es/ecma262/#sec-async-function-constructor" class="type">&#x3C;AsyncFunction></a> The hook function.
If the hook uses callbacks,
the callback function is passed as the second argument. <strong>Default:</strong> A no-op
function.</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> Configuration options for the hook. The following
properties are supported:
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> Allows aborting an in-progress hook.</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 of milliseconds the hook will fail after.
If unspecified, subtests inherit this value from their parent.
<strong>Default:</strong> <code>Infinity</code>.</li>
</ul>
</li>
</ul>
<p>This function creates a hook that runs before each test in the current suite.</p>
<pre><code class="language-js"><span class="hljs-title function_">describe</span>(<span class="hljs-string">'tests'</span>, <span class="hljs-keyword">async</span> () => {
  <span class="hljs-title function_">beforeEach</span>(<span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'about to run a test'</span>));
  <span class="hljs-title function_">it</span>(<span class="hljs-string">'is a subtest'</span>, <span class="hljs-function">() =></span> {
    assert.<span class="hljs-title function_">ok</span>(<span class="hljs-string">'some relevant assertion here'</span>);
  });
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>afterEach([fn][, options])</code><span><a class="mark" href="#all_test_aftereachfn-options" id="all_test_aftereachfn-options">#</a></span><a aria-hidden="true" class="legacy" id="test_aftereach_fn_options"></a></h3>
<div class="api_metadata">
<span>Added in: v18.8.0, v16.18.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://tc39.es/ecma262/#sec-async-function-constructor" class="type">&#x3C;AsyncFunction></a> The hook function.
If the hook uses callbacks,
the callback function is passed as the second argument. <strong>Default:</strong> A no-op
function.</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> Configuration options for the hook. The following
properties are supported:
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> Allows aborting an in-progress hook.</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 of milliseconds the hook will fail after.
If unspecified, subtests inherit this value from their parent.
<strong>Default:</strong> <code>Infinity</code>.</li>
</ul>
</li>
</ul>
<p>This function creates a hook that runs after each test in the current suite.
The <code>afterEach()</code> hook is run even if the test fails.</p>
<pre><code class="language-js"><span class="hljs-title function_">describe</span>(<span class="hljs-string">'tests'</span>, <span class="hljs-keyword">async</span> () => {
  <span class="hljs-title function_">afterEach</span>(<span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'finished running a test'</span>));
  <span class="hljs-title function_">it</span>(<span class="hljs-string">'is a subtest'</span>, <span class="hljs-function">() =></span> {
    assert.<span class="hljs-title function_">ok</span>(<span class="hljs-string">'some relevant assertion here'</span>);
  });
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>MockFunctionContext</code><span><a class="mark" href="#all_test_class-mockfunctioncontext" id="all_test_class-mockfunctioncontext">#</a></span><a aria-hidden="true" class="legacy" id="test_class_mockfunctioncontext"></a></h3>
<div class="api_metadata">
<span>Added in: v19.1.0, v18.13.0</span>
</div>
<p>The <code>MockFunctionContext</code> class is used to inspect or manipulate the behavior of
mocks created via the <a href="#all_test_class-mocktracker"><code>MockTracker</code></a> APIs.</p>
<h4><code>ctx.calls</code><span><a class="mark" href="#all_test_ctxcalls" id="all_test_ctxcalls">#</a></span><a aria-hidden="true" class="legacy" id="test_ctx_calls"></a></h4>
<div class="api_metadata">
<span>Added in: v19.1.0, v18.13.0</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 getter that returns a copy of the internal array used to track calls to the
mock. Each entry in the array is an object with the following properties.</p>
<ul>
<li><code>arguments</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type">&#x3C;Array></a> An array of the arguments passed to the mock function.</li>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> If the mocked function threw then this property contains the
thrown value. <strong>Default:</strong> <code>undefined</code>.</li>
<li><code>result</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> The value returned by the mocked function.</li>
<li><code>stack</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 whose stack can be used to determine the
callsite of the mocked function invocation.</li>
<li><code>target</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> If the mocked function is a constructor, this
field contains the class being constructed. Otherwise this will be
<code>undefined</code>.</li>
<li><code>this</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> The mocked function's <code>this</code> value.</li>
</ul>
<h4><code>ctx.callCount()</code><span><a class="mark" href="#all_test_ctxcallcount" id="all_test_ctxcallcount">#</a></span><a aria-hidden="true" class="legacy" id="test_ctx_callcount"></a></h4>
<div class="api_metadata">
<span>Added in: v19.1.0, v18.13.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> The number of times that this mock has been invoked.</li>
</ul>
<p>This function returns the number of times that this mock has been invoked. This
function is more efficient than checking <code>ctx.calls.length</code> because <code>ctx.calls</code>
is a getter that creates a copy of the internal call tracking array.</p>
<h4><code>ctx.mockImplementation(implementation)</code><span><a class="mark" href="#all_test_ctxmockimplementationimplementation" id="all_test_ctxmockimplementationimplementation">#</a></span><a aria-hidden="true" class="legacy" id="test_ctx_mockimplementation_implementation"></a></h4>
<div class="api_metadata">
<span>Added in: v19.1.0, v18.13.0</span>
</div>
<ul>
<li><code>implementation</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> | <a href="https://tc39.es/ecma262/#sec-async-function-constructor" class="type">&#x3C;AsyncFunction></a> The function to be used as the
mock's new implementation.</li>
</ul>
<p>This function is used to change the behavior of an existing mock.</p>
<p>The following example creates a mock function using <code>t.mock.fn()</code>, calls the
mock function, and then changes the mock implementation to a different function.</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'changes a mock behavior'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
  <span class="hljs-keyword">let</span> cnt = <span class="hljs-number">0</span>;

  <span class="hljs-keyword">function</span> <span class="hljs-title function_">addOne</span>(<span class="hljs-params"></span>) {
    cnt++;
    <span class="hljs-keyword">return</span> cnt;
  }

  <span class="hljs-keyword">function</span> <span class="hljs-title function_">addTwo</span>(<span class="hljs-params"></span>) {
    cnt += <span class="hljs-number">2</span>;
    <span class="hljs-keyword">return</span> cnt;
  }

  <span class="hljs-keyword">const</span> fn = t.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>(addOne);

  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title function_">fn</span>(), <span class="hljs-number">1</span>);
  fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">mockImplementation</span>(addTwo);
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title function_">fn</span>(), <span class="hljs-number">3</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title function_">fn</span>(), <span class="hljs-number">5</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4><code>ctx.mockImplementationOnce(implementation[, onCall])</code><span><a class="mark" href="#all_test_ctxmockimplementationonceimplementation-oncall" id="all_test_ctxmockimplementationonceimplementation-oncall">#</a></span><a aria-hidden="true" class="legacy" id="test_ctx_mockimplementationonce_implementation_oncall"></a></h4>
<div class="api_metadata">
<span>Added in: v19.1.0, v18.13.0</span>
</div>
<ul>
<li><code>implementation</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> | <a href="https://tc39.es/ecma262/#sec-async-function-constructor" class="type">&#x3C;AsyncFunction></a> The function to be used as the
mock's implementation for the invocation number specified by <code>onCall</code>.</li>
<li><code>onCall</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> The invocation number that will use <code>implementation</code>. If
the specified invocation has already occurred then an exception is thrown.
<strong>Default:</strong> The number of the next invocation.</li>
</ul>
<p>This function is used to change the behavior of an existing mock for a single
invocation. Once invocation <code>onCall</code> has occurred, the mock will revert to
whatever behavior it would have used had <code>mockImplementationOnce()</code> not been
called.</p>
<p>The following example creates a mock function using <code>t.mock.fn()</code>, calls the
mock function, changes the mock implementation to a different function for the
next invocation, and then resumes its previous behavior.</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'changes a mock behavior once'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
  <span class="hljs-keyword">let</span> cnt = <span class="hljs-number">0</span>;

  <span class="hljs-keyword">function</span> <span class="hljs-title function_">addOne</span>(<span class="hljs-params"></span>) {
    cnt++;
    <span class="hljs-keyword">return</span> cnt;
  }

  <span class="hljs-keyword">function</span> <span class="hljs-title function_">addTwo</span>(<span class="hljs-params"></span>) {
    cnt += <span class="hljs-number">2</span>;
    <span class="hljs-keyword">return</span> cnt;
  }

  <span class="hljs-keyword">const</span> fn = t.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>(addOne);

  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title function_">fn</span>(), <span class="hljs-number">1</span>);
  fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">mockImplementationOnce</span>(addTwo);
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title function_">fn</span>(), <span class="hljs-number">3</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title function_">fn</span>(), <span class="hljs-number">4</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4><code>ctx.resetCalls()</code><span><a class="mark" href="#all_test_ctxresetcalls" id="all_test_ctxresetcalls">#</a></span><a aria-hidden="true" class="legacy" id="test_ctx_resetcalls"></a></h4>
<div class="api_metadata">
<span>Added in: v19.3.0, v18.13.0</span>
</div>
<p>Resets the call history of the mock function.</p>
<h4><code>ctx.restore()</code><span><a class="mark" href="#all_test_ctxrestore" id="all_test_ctxrestore">#</a></span><a aria-hidden="true" class="legacy" id="test_ctx_restore"></a></h4>
<div class="api_metadata">
<span>Added in: v19.1.0, v18.13.0</span>
</div>
<p>Resets the implementation of the mock function to its original behavior. The
mock can still be used after calling this function.</p>
</section><section><h3>Class: <code>MockModuleContext</code><span><a class="mark" href="#all_test_class-mockmodulecontext" id="all_test_class-mockmodulecontext">#</a></span><a aria-hidden="true" class="legacy" id="test_class_mockmodulecontext"></a></h3>
<div class="api_metadata">
<span>Added in: v20.18.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.0 - Early development</div><p></p>
<p>The <code>MockModuleContext</code> class is used to manipulate the behavior of module mocks
created via the <a href="#all_test_class-mocktracker"><code>MockTracker</code></a> APIs.</p>
<h4><code>ctx.restore()</code><span><a class="mark" href="#all_test_ctxrestore_1" id="all_test_ctxrestore_1">#</a></span><a aria-hidden="true" class="legacy" id="test_ctx_restore_1"></a></h4>
<div class="api_metadata">
<span>Added in: v20.18.0</span>
</div>
<p>Resets the implementation of the mock module.</p>
</section><section><h3>Class: <code>MockTracker</code><span><a class="mark" href="#all_test_class-mocktracker" id="all_test_class-mocktracker">#</a></span><a aria-hidden="true" class="legacy" id="test_class_mocktracker"></a></h3>
<div class="api_metadata">
<span>Added in: v19.1.0, v18.13.0</span>
</div>
<p>The <code>MockTracker</code> class is used to manage mocking functionality. The test runner
module provides a top level <code>mock</code> export which is a <code>MockTracker</code> instance.
Each test also provides its own <code>MockTracker</code> instance via the test context's
<code>mock</code> property.</p>
<h4><code>mock.fn([original[, implementation]][, options])</code><span><a class="mark" href="#all_test_mockfnoriginal-implementation-options" id="all_test_mockfnoriginal-implementation-options">#</a></span><a aria-hidden="true" class="legacy" id="test_mock_fn_original_implementation_options"></a></h4>
<div class="api_metadata">
<span>Added in: v19.1.0, v18.13.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> | <a href="https://tc39.es/ecma262/#sec-async-function-constructor" class="type">&#x3C;AsyncFunction></a> An optional function to create a mock on.
<strong>Default:</strong> A no-op function.</li>
<li><code>implementation</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> | <a href="https://tc39.es/ecma262/#sec-async-function-constructor" class="type">&#x3C;AsyncFunction></a> An optional function used as the
mock implementation for <code>original</code>. This is useful for creating mocks that
exhibit one behavior for a specified number of calls and then restore the
behavior of <code>original</code>. <strong>Default:</strong> The function specified by <code>original</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> Optional configuration options for the mock function. The
following properties are supported:
<ul>
<li><code>times</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> The number of times that the mock will use the behavior of
<code>implementation</code>. Once the mock function has been called <code>times</code> times, it
will automatically restore the behavior of <code>original</code>. This value must be an
integer greater than zero. <strong>Default:</strong> <code>Infinity</code>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy" class="type">&#x3C;Proxy></a> The mocked function. The mocked function contains a special
<code>mock</code> property, which is an instance of <a href="#all_test_class-mockfunctioncontext"><code>MockFunctionContext</code></a>, and can
be used for inspecting and changing the behavior of the mocked function.</li>
</ul>
<p>This function is used to create a mock function.</p>
<p>The following example creates a mock function that increments a counter by one
on each invocation. The <code>times</code> option is used to modify the mock behavior such
that the first two invocations add two to the counter instead of one.</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'mocks a counting function'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
  <span class="hljs-keyword">let</span> cnt = <span class="hljs-number">0</span>;

  <span class="hljs-keyword">function</span> <span class="hljs-title function_">addOne</span>(<span class="hljs-params"></span>) {
    cnt++;
    <span class="hljs-keyword">return</span> cnt;
  }

  <span class="hljs-keyword">function</span> <span class="hljs-title function_">addTwo</span>(<span class="hljs-params"></span>) {
    cnt += <span class="hljs-number">2</span>;
    <span class="hljs-keyword">return</span> cnt;
  }

  <span class="hljs-keyword">const</span> fn = t.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>(addOne, addTwo, { <span class="hljs-attr">times</span>: <span class="hljs-number">2</span> });

  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title function_">fn</span>(), <span class="hljs-number">2</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title function_">fn</span>(), <span class="hljs-number">4</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title function_">fn</span>(), <span class="hljs-number">5</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title function_">fn</span>(), <span class="hljs-number">6</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4><code>mock.getter(object, methodName[, implementation][, options])</code><span><a class="mark" href="#all_test_mockgetterobject-methodname-implementation-options" id="all_test_mockgetterobject-methodname-implementation-options">#</a></span><a aria-hidden="true" class="legacy" id="test_mock_getter_object_methodname_implementation_options"></a></h4>
<div class="api_metadata">
<span>Added in: v19.3.0, v18.13.0</span>
</div>
<p>This function is syntax sugar for <a href="#all_test_mockmethodobject-methodname-implementation-options"><code>MockTracker.method</code></a> with <code>options.getter</code>
set to <code>true</code>.</p>
<h4><code>mock.method(object, methodName[, implementation][, options])</code><span><a class="mark" href="#all_test_mockmethodobject-methodname-implementation-options" id="all_test_mockmethodobject-methodname-implementation-options">#</a></span><a aria-hidden="true" class="legacy" id="test_mock_method_object_methodname_implementation_options"></a></h4>
<div class="api_metadata">
<span>Added in: v19.1.0, v18.13.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> The object whose method is being mocked.</li>
<li><code>methodName</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 identifier of the method on <code>object</code> to mock.
If <code>object[methodName]</code> is not a function, an error is thrown.</li>
<li><code>implementation</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> | <a href="https://tc39.es/ecma262/#sec-async-function-constructor" class="type">&#x3C;AsyncFunction></a> An optional function used as the
mock implementation for <code>object[methodName]</code>. <strong>Default:</strong> The original method
specified by <code>object[methodName]</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> Optional configuration options for the mock method. The
following properties are supported:
<ul>
<li><code>getter</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[methodName]</code> is treated as a getter.
This option cannot be used with the <code>setter</code> option. <strong>Default:</strong> false.</li>
<li><code>setter</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[methodName]</code> is treated as a setter.
This option cannot be used with the <code>getter</code> option. <strong>Default:</strong> false.</li>
<li><code>times</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> The number of times that the mock will use the behavior of
<code>implementation</code>. Once the mocked method has been called <code>times</code> times, it
will automatically restore the original behavior. This value must be an
integer greater than zero. <strong>Default:</strong> <code>Infinity</code>.</li>
</ul>
</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy" class="type">&#x3C;Proxy></a> The mocked method. The mocked method contains a special
<code>mock</code> property, which is an instance of <a href="#all_test_class-mockfunctioncontext"><code>MockFunctionContext</code></a>, and can
be used for inspecting and changing the behavior of the mocked method.</li>
</ul>
<p>This function is used to create a mock on an existing object method. The
following example demonstrates how a mock is created on an existing object
method.</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'spies on an object method'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
  <span class="hljs-keyword">const</span> number = {
    <span class="hljs-attr">value</span>: <span class="hljs-number">5</span>,
    <span class="hljs-title function_">subtract</span>(<span class="hljs-params">a</span>) {
      <span class="hljs-keyword">return</span> <span class="hljs-variable language_">this</span>.<span class="hljs-property">value</span> - a;
    },
  };

  t.<span class="hljs-property">mock</span>.<span class="hljs-title function_">method</span>(number, <span class="hljs-string">'subtract'</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(number.<span class="hljs-property">subtract</span>.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">0</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(number.<span class="hljs-title function_">subtract</span>(<span class="hljs-number">3</span>), <span class="hljs-number">2</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(number.<span class="hljs-property">subtract</span>.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);

  <span class="hljs-keyword">const</span> call = number.<span class="hljs-property">subtract</span>.<span class="hljs-property">mock</span>.<span class="hljs-property">calls</span>[<span class="hljs-number">0</span>];

  assert.<span class="hljs-title function_">deepStrictEqual</span>(call.<span class="hljs-property">arguments</span>, [<span class="hljs-number">3</span>]);
  assert.<span class="hljs-title function_">strictEqual</span>(call.<span class="hljs-property">result</span>, <span class="hljs-number">2</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(call.<span class="hljs-property">error</span>, <span class="hljs-literal">undefined</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(call.<span class="hljs-property">target</span>, <span class="hljs-literal">undefined</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(call.<span class="hljs-property">this</span>, number);
});</code> <button class="copy-button">copy</button></pre>
<h4><code>mock.module(specifier[, options])</code><span><a class="mark" href="#all_test_mockmodulespecifier-options" id="all_test_mockmodulespecifier-options">#</a></span><a aria-hidden="true" class="legacy" id="test_mock_module_specifier_options"></a></h4>
<div class="api_metadata">
<span>Added in: v20.18.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.0 - Early development</div><p></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> A string identifying the module to mock.</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> Optional configuration options for the mock module. The
following properties are supported:
<ul>
<li><code>cache</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>, each call to <code>require()</code> or <code>import()</code>
generates a new mock module. If <code>true</code>, subsequent calls will return the same
module mock, and the mock module is inserted into the CommonJS cache.
<strong>Default:</strong> false.</li>
<li><code>defaultExport</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> An optional value used as the mocked module's default
export. If this value is not provided, ESM mocks do not include a default
export. If the mock is a CommonJS or builtin module, this setting is used as
the value of <code>module.exports</code>. If this value is not provided, CJS and builtin
mocks use an empty object as the value of <code>module.exports</code>.</li>
<li><code>namedExports</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> An optional object whose keys and values are used to
create the named exports of the mock module. If the mock is a CommonJS or
builtin module, these values are copied onto <code>module.exports</code>. Therefore, if a
mock is created with both named exports and a non-object default export, the
mock will throw an exception when used as a CJS or builtin module.</li>
</ul>
</li>
<li>Returns: <a href="#all_test_class-mockmodulecontext" class="type">&#x3C;MockModuleContext></a> An object that can be used to manipulate the mock.</li>
</ul>
<p>This function is used to mock the exports of ECMAScript modules, CommonJS
modules, and Node.js builtin modules. Any references to the original module
prior to mocking are not impacted. The following example demonstrates how a mock
is created for a module.</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'mocks a builtin module in both module systems'</span>, <span class="hljs-keyword">async</span> (t) => {
  <span class="hljs-comment">// Create a mock of 'node:readline' with a named export named 'fn', which</span>
  <span class="hljs-comment">// does not exist in the original 'node:readline' module.</span>
  <span class="hljs-keyword">const</span> mock = t.<span class="hljs-property">mock</span>.<span class="hljs-title function_">module</span>(<span class="hljs-string">'node:readline'</span>, {
    <span class="hljs-attr">namedExports</span>: { <span class="hljs-title function_">fn</span>(<span class="hljs-params"></span>) { <span class="hljs-keyword">return</span> <span class="hljs-number">42</span>; } },
  });

  <span class="hljs-keyword">let</span> esmImpl = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:readline'</span>);
  <span class="hljs-keyword">let</span> cjsImpl = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:readline'</span>);

  <span class="hljs-comment">// cursorTo() is an export of the original 'node:readline' module.</span>
  assert.<span class="hljs-title function_">strictEqual</span>(esmImpl.<span class="hljs-property">cursorTo</span>, <span class="hljs-literal">undefined</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(cjsImpl.<span class="hljs-property">cursorTo</span>, <span class="hljs-literal">undefined</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(esmImpl.<span class="hljs-title function_">fn</span>(), <span class="hljs-number">42</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(cjsImpl.<span class="hljs-title function_">fn</span>(), <span class="hljs-number">42</span>);

  mock.<span class="hljs-title function_">restore</span>();

  <span class="hljs-comment">// The mock is restored, so the original builtin module is returned.</span>
  esmImpl = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:readline'</span>);
  cjsImpl = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:readline'</span>);

  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-keyword">typeof</span> esmImpl.<span class="hljs-property">cursorTo</span>, <span class="hljs-string">'function'</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-keyword">typeof</span> cjsImpl.<span class="hljs-property">cursorTo</span>, <span class="hljs-string">'function'</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(esmImpl.<span class="hljs-property">fn</span>, <span class="hljs-literal">undefined</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(cjsImpl.<span class="hljs-property">fn</span>, <span class="hljs-literal">undefined</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4><code>mock.reset()</code><span><a class="mark" href="#all_test_mockreset" id="all_test_mockreset">#</a></span><a aria-hidden="true" class="legacy" id="test_mock_reset"></a></h4>
<div class="api_metadata">
<span>Added in: v19.1.0, v18.13.0</span>
</div>
<p>This function restores the default behavior of all mocks that were previously
created by this <code>MockTracker</code> and disassociates the mocks from the
<code>MockTracker</code> instance. Once disassociated, the mocks can still be used, but the
<code>MockTracker</code> instance can no longer be used to reset their behavior or
otherwise interact with them.</p>
<p>After each test completes, this function is called on the test context's
<code>MockTracker</code>. If the global <code>MockTracker</code> is used extensively, calling this
function manually is recommended.</p>
<h4><code>mock.restoreAll()</code><span><a class="mark" href="#all_test_mockrestoreall" id="all_test_mockrestoreall">#</a></span><a aria-hidden="true" class="legacy" id="test_mock_restoreall"></a></h4>
<div class="api_metadata">
<span>Added in: v19.1.0, v18.13.0</span>
</div>
<p>This function restores the default behavior of all mocks that were previously
created by this <code>MockTracker</code>. Unlike <code>mock.reset()</code>, <code>mock.restoreAll()</code> does
not disassociate the mocks from the <code>MockTracker</code> instance.</p>
<h4><code>mock.setter(object, methodName[, implementation][, options])</code><span><a class="mark" href="#all_test_mocksetterobject-methodname-implementation-options" id="all_test_mocksetterobject-methodname-implementation-options">#</a></span><a aria-hidden="true" class="legacy" id="test_mock_setter_object_methodname_implementation_options"></a></h4>
<div class="api_metadata">
<span>Added in: v19.3.0, v18.13.0</span>
</div>
<p>This function is syntax sugar for <a href="#all_test_mockmethodobject-methodname-implementation-options"><code>MockTracker.method</code></a> with <code>options.setter</code>
set to <code>true</code>.</p>
</section><section><h3>Class: <code>MockTimers</code><span><a class="mark" href="#all_test_class-mocktimers" id="all_test_class-mocktimers">#</a></span><a aria-hidden="true" class="legacy" id="test_class_mocktimers"></a></h3>
<div class="api_metadata">
<span>Added in: v20.4.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Mocking timers is a technique commonly used in software testing to simulate and
control the behavior of timers, such as <code>setInterval</code> and <code>setTimeout</code>,
without actually waiting for the specified time intervals.</p>
<p>MockTimers is also able to mock the <code>Date</code> object.</p>
<p>The <a href="#all_test_class-mocktracker"><code>MockTracker</code></a> provides a top-level <code>timers</code> export
which is a <code>MockTimers</code> instance.</p>
<h4><code>timers.enable([enableOptions])</code><span><a class="mark" href="#all_test_timersenableenableoptions" id="all_test_timersenableenableoptions">#</a></span><a aria-hidden="true" class="legacy" id="test_timers_enable_enableoptions"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.11.0</td>
<td><p>Updated parameters to be an option object with available APIs and the default initial epoch.</p></td></tr>
<tr><td>v20.4.0</td>
<td><p><span>Added in: v20.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Enables timer mocking for the specified timers.</p>
<ul>
<li><code>enableOptions</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Optional configuration options for enabling timer
mocking. The following properties are supported:
<ul>
<li><code>apis</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type">&#x3C;Array></a> An optional array containing the timers to mock.
The currently supported timer values are <code>'setInterval'</code>, <code>'setTimeout'</code>, <code>'setImmediate'</code>,
and <code>'Date'</code>. <strong>Default:</strong> <code>['setInterval', 'setTimeout', 'setImmediate', 'Date']</code>.
If no array is provided, all time related APIs (<code>'setInterval'</code>, <code>'clearInterval'</code>,
<code>'setTimeout'</code>, <code>'clearTimeout'</code>, <code>'setImmediate'</code>, <code>'clearImmediate'</code>, and
<code>'Date'</code>) will be mocked by default.</li>
<li><code>now</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/Date" class="type">&#x3C;Date></a> An optional number or Date object representing the
initial time (in milliseconds) to use as the value
for <code>Date.now()</code>. <strong>Default:</strong> <code>0</code>.</li>
</ul>
</li>
</ul>
<p><strong>Note:</strong> When you enable mocking for a specific timer, its associated
clear function will also be implicitly mocked.</p>
<p><strong>Note:</strong> Mocking <code>Date</code> will affect the behavior of the mocked timers
as they use the same internal clock.</p>
<p>Example usage without setting initial time:</p>

<pre class="with-46-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { mock } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;
mock.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setInterval'</span>] });</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { mock } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);
mock.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setInterval'</span>] });</code><button class="copy-button">copy</button></pre>
<p>The above example enables mocking for the <code>setInterval</code> timer and
implicitly mocks the <code>clearInterval</code> function. Only the <code>setInterval</code>
and <code>clearInterval</code> functions from <a href="./timers.html">node:timers</a>,
<a href="./timers.html#timers-promises-api">node:timers/promises</a>, and
<code>globalThis</code> will be mocked.</p>
<p>Example usage with initial time set</p>

<pre class="with-50-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { mock } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;
mock.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'Date'</span>], <span class="hljs-attr">now</span>: <span class="hljs-number">1000</span> });</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { mock } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);
mock.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'Date'</span>], <span class="hljs-attr">now</span>: <span class="hljs-number">1000</span> });</code><button class="copy-button">copy</button></pre>
<p>Example usage with initial Date object as time set</p>

<pre class="with-56-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { mock } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;
mock.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'Date'</span>], <span class="hljs-attr">now</span>: <span class="hljs-keyword">new</span> <span class="hljs-title class_">Date</span>() });</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { mock } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);
mock.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'Date'</span>], <span class="hljs-attr">now</span>: <span class="hljs-keyword">new</span> <span class="hljs-title class_">Date</span>() });</code><button class="copy-button">copy</button></pre>
<p>Alternatively, if you call <code>mock.timers.enable()</code> without any parameters:</p>
<p>All timers (<code>'setInterval'</code>, <code>'clearInterval'</code>, <code>'setTimeout'</code>, <code>'clearTimeout'</code>,
<code>'setImmediate'</code>, and <code>'clearImmediate'</code>) will be mocked. The <code>setInterval</code>,
<code>clearInterval</code>, <code>setTimeout</code>, <code>clearTimeout</code>, <code>setImmediate</code>, and
<code>clearImmediate</code> functions from <code>node:timers</code>, <code>node:timers/promises</code>, and
<code>globalThis</code> will be mocked. As well as the global <code>Date</code> object.</p>
<h4><code>timers.reset()</code><span><a class="mark" href="#all_test_timersreset" id="all_test_timersreset">#</a></span><a aria-hidden="true" class="legacy" id="test_timers_reset"></a></h4>
<div class="api_metadata">
<span>Added in: v20.4.0</span>
</div>
<p>This function restores the default behavior of all mocks that were previously
created by this  <code>MockTimers</code> instance and disassociates the mocks
from the  <code>MockTracker</code> instance.</p>
<p><strong>Note:</strong> After each test completes, this function is called on
the test context's  <code>MockTracker</code>.</p>

<pre class="with-38-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { mock } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;
mock.<span class="hljs-property">timers</span>.<span class="hljs-title function_">reset</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { mock } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);
mock.<span class="hljs-property">timers</span>.<span class="hljs-title function_">reset</span>();</code><button class="copy-button">copy</button></pre>
<h4><code>timers[Symbol.dispose]()</code><span><a class="mark" href="#all_test_timerssymboldispose" id="all_test_timerssymboldispose">#</a></span><a aria-hidden="true" class="legacy" id="test_timers_symbol_dispose"></a></h4>
<p>Calls <code>timers.reset()</code>.</p>
<h4><code>timers.tick([milliseconds])</code><span><a class="mark" href="#all_test_timerstickmilliseconds" id="all_test_timerstickmilliseconds">#</a></span><a aria-hidden="true" class="legacy" id="test_timers_tick_milliseconds"></a></h4>
<div class="api_metadata">
<span>Added in: v20.4.0</span>
</div>
<p>Advances time for all mocked timers.</p>
<ul>
<li><code>milliseconds</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The amount of time, in milliseconds,
to advance the timers. <strong>Default:</strong> <code>1</code>.</li>
</ul>
<p><strong>Note:</strong> This diverges from how <code>setTimeout</code> in Node.js behaves and accepts
only positive numbers. In Node.js, <code>setTimeout</code> with negative numbers is
only supported for web compatibility reasons.</p>
<p>The following example mocks a <code>setTimeout</code> function and
by using <code>.tick</code> advances in
time triggering all pending timers.</p>

<pre class="with-38-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> { test } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;

<span class="hljs-title function_">test</span>(<span class="hljs-string">'mocks setTimeout to be executed synchronously without having to actually wait for it'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
  <span class="hljs-keyword">const</span> fn = context.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>();

  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>] });

  <span class="hljs-built_in">setTimeout</span>(fn, <span class="hljs-number">9999</span>);

  assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">0</span>);

  <span class="hljs-comment">// Advance in time</span>
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(<span class="hljs-number">9999</span>);

  assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { test } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);

<span class="hljs-title function_">test</span>(<span class="hljs-string">'mocks setTimeout to be executed synchronously without having to actually wait for it'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
  <span class="hljs-keyword">const</span> fn = context.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>();
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>] });

  <span class="hljs-built_in">setTimeout</span>(fn, <span class="hljs-number">9999</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">0</span>);

  <span class="hljs-comment">// Advance in time</span>
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(<span class="hljs-number">9999</span>);

  assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);
});</code><button class="copy-button">copy</button></pre>
<p>Alternatively, the <code>.tick</code> function can be called many times</p>

<pre class="with-38-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> { test } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;

<span class="hljs-title function_">test</span>(<span class="hljs-string">'mocks setTimeout to be executed synchronously without having to actually wait for it'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
  <span class="hljs-keyword">const</span> fn = context.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>();
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>] });
  <span class="hljs-keyword">const</span> nineSecs = <span class="hljs-number">9000</span>;
  <span class="hljs-built_in">setTimeout</span>(fn, nineSecs);

  <span class="hljs-keyword">const</span> threeSeconds = <span class="hljs-number">3000</span>;
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(threeSeconds);
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(threeSeconds);
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(threeSeconds);

  assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { test } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);

<span class="hljs-title function_">test</span>(<span class="hljs-string">'mocks setTimeout to be executed synchronously without having to actually wait for it'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
  <span class="hljs-keyword">const</span> fn = context.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>();
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>] });
  <span class="hljs-keyword">const</span> nineSecs = <span class="hljs-number">9000</span>;
  <span class="hljs-built_in">setTimeout</span>(fn, nineSecs);

  <span class="hljs-keyword">const</span> threeSeconds = <span class="hljs-number">3000</span>;
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(threeSeconds);
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(threeSeconds);
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(threeSeconds);

  assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);
});</code><button class="copy-button">copy</button></pre>
<p>Advancing time using <code>.tick</code> will also advance the time for any <code>Date</code> object
created after the mock was enabled (if <code>Date</code> was also set to be mocked).</p>

<pre class="with-38-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> { test } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;

<span class="hljs-title function_">test</span>(<span class="hljs-string">'mocks setTimeout to be executed synchronously without having to actually wait for it'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
  <span class="hljs-keyword">const</span> fn = context.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>();

  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>, <span class="hljs-string">'Date'</span>] });
  <span class="hljs-built_in">setTimeout</span>(fn, <span class="hljs-number">9999</span>);

  assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">0</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">0</span>);

  <span class="hljs-comment">// Advance in time</span>
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(<span class="hljs-number">9999</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">9999</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { test } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);

<span class="hljs-title function_">test</span>(<span class="hljs-string">'mocks setTimeout to be executed synchronously without having to actually wait for it'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
  <span class="hljs-keyword">const</span> fn = context.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>();
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>, <span class="hljs-string">'Date'</span>] });

  <span class="hljs-built_in">setTimeout</span>(fn, <span class="hljs-number">9999</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">0</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">0</span>);

  <span class="hljs-comment">// Advance in time</span>
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(<span class="hljs-number">9999</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">9999</span>);
});</code><button class="copy-button">copy</button></pre>
<h5>Using clear functions<span><a class="mark" href="#all_test_using-clear-functions" id="all_test_using-clear-functions">#</a></span><a aria-hidden="true" class="legacy" id="test_using_clear_functions"></a></h5>
<p>As mentioned, all clear functions from timers (<code>clearTimeout</code>, <code>clearInterval</code>,and
<code>clearImmediate</code>) are implicitly mocked. Take a look at this example using <code>setTimeout</code>:</p>

<pre class="with-38-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> { test } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;

<span class="hljs-title function_">test</span>(<span class="hljs-string">'mocks setTimeout to be executed synchronously without having to actually wait for it'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
  <span class="hljs-keyword">const</span> fn = context.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>();

  <span class="hljs-comment">// Optionally choose what to mock</span>
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>] });
  <span class="hljs-keyword">const</span> id = <span class="hljs-built_in">setTimeout</span>(fn, <span class="hljs-number">9999</span>);

  <span class="hljs-comment">// Implicitly mocked as well</span>
  <span class="hljs-built_in">clearTimeout</span>(id);
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(<span class="hljs-number">9999</span>);

  <span class="hljs-comment">// As that setTimeout was cleared the mock function will never be called</span>
  assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">0</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { test } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);

<span class="hljs-title function_">test</span>(<span class="hljs-string">'mocks setTimeout to be executed synchronously without having to actually wait for it'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
  <span class="hljs-keyword">const</span> fn = context.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>();

  <span class="hljs-comment">// Optionally choose what to mock</span>
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>] });
  <span class="hljs-keyword">const</span> id = <span class="hljs-built_in">setTimeout</span>(fn, <span class="hljs-number">9999</span>);

  <span class="hljs-comment">// Implicitly mocked as well</span>
  <span class="hljs-built_in">clearTimeout</span>(id);
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(<span class="hljs-number">9999</span>);

  <span class="hljs-comment">// As that setTimeout was cleared the mock function will never be called</span>
  assert.<span class="hljs-title function_">strictEqual</span>(fn.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">0</span>);
});</code><button class="copy-button">copy</button></pre>
<h5>Working with Node.js timers modules<span><a class="mark" href="#all_test_working-with-nodejs-timers-modules" id="all_test_working-with-nodejs-timers-modules">#</a></span><a aria-hidden="true" class="legacy" id="test_working_with_node_js_timers_modules"></a></h5>
<p>Once you enable mocking timers, <a href="./timers.html">node:timers</a>,
<a href="./timers.html#timers-promises-api">node:timers/promises</a> modules,
and timers from the Node.js global context are enabled:</p>
<p><strong>Note:</strong> Destructuring functions such as
<code>import { setTimeout } from 'node:timers'</code> is currently
not supported by this API.</p>

<pre class="with-38-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> { test } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;
<span class="hljs-keyword">import</span> nodeTimers <span class="hljs-keyword">from</span> <span class="hljs-string">'node:timers'</span>;
<span class="hljs-keyword">import</span> nodeTimersPromises <span class="hljs-keyword">from</span> <span class="hljs-string">'node:timers/promises'</span>;

<span class="hljs-title function_">test</span>(<span class="hljs-string">'mocks setTimeout to be executed synchronously without having to actually wait for it'</span>, <span class="hljs-keyword">async</span> (context) => {
  <span class="hljs-keyword">const</span> globalTimeoutObjectSpy = context.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>();
  <span class="hljs-keyword">const</span> nodeTimerSpy = context.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>();
  <span class="hljs-keyword">const</span> nodeTimerPromiseSpy = context.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>();

  <span class="hljs-comment">// Optionally choose what to mock</span>
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>] });
  <span class="hljs-built_in">setTimeout</span>(globalTimeoutObjectSpy, <span class="hljs-number">9999</span>);
  nodeTimers.<span class="hljs-built_in">setTimeout</span>(nodeTimerSpy, <span class="hljs-number">9999</span>);

  <span class="hljs-keyword">const</span> promise = nodeTimersPromises.<span class="hljs-built_in">setTimeout</span>(<span class="hljs-number">9999</span>).<span class="hljs-title function_">then</span>(nodeTimerPromiseSpy);

  <span class="hljs-comment">// Advance in time</span>
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(<span class="hljs-number">9999</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(globalTimeoutObjectSpy.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(nodeTimerSpy.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);
  <span class="hljs-keyword">await</span> promise;
  assert.<span class="hljs-title function_">strictEqual</span>(nodeTimerPromiseSpy.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { test } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);
<span class="hljs-keyword">const</span> nodeTimers = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:timers'</span>);
<span class="hljs-keyword">const</span> nodeTimersPromises = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:timers/promises'</span>);

<span class="hljs-title function_">test</span>(<span class="hljs-string">'mocks setTimeout to be executed synchronously without having to actually wait for it'</span>, <span class="hljs-keyword">async</span> (context) => {
  <span class="hljs-keyword">const</span> globalTimeoutObjectSpy = context.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>();
  <span class="hljs-keyword">const</span> nodeTimerSpy = context.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>();
  <span class="hljs-keyword">const</span> nodeTimerPromiseSpy = context.<span class="hljs-property">mock</span>.<span class="hljs-title function_">fn</span>();

  <span class="hljs-comment">// Optionally choose what to mock</span>
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>] });
  <span class="hljs-built_in">setTimeout</span>(globalTimeoutObjectSpy, <span class="hljs-number">9999</span>);
  nodeTimers.<span class="hljs-built_in">setTimeout</span>(nodeTimerSpy, <span class="hljs-number">9999</span>);

  <span class="hljs-keyword">const</span> promise = nodeTimersPromises.<span class="hljs-built_in">setTimeout</span>(<span class="hljs-number">9999</span>).<span class="hljs-title function_">then</span>(nodeTimerPromiseSpy);

  <span class="hljs-comment">// Advance in time</span>
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(<span class="hljs-number">9999</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(globalTimeoutObjectSpy.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);
  assert.<span class="hljs-title function_">strictEqual</span>(nodeTimerSpy.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);
  <span class="hljs-keyword">await</span> promise;
  assert.<span class="hljs-title function_">strictEqual</span>(nodeTimerPromiseSpy.<span class="hljs-property">mock</span>.<span class="hljs-title function_">callCount</span>(), <span class="hljs-number">1</span>);
});</code><button class="copy-button">copy</button></pre>
<p>In Node.js, <code>setInterval</code> from <a href="./timers.html#timers-promises-api">node:timers/promises</a>
is an <code>AsyncGenerator</code> and is also supported by this API:</p>

<pre class="with-38-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> { test } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;
<span class="hljs-keyword">import</span> nodeTimersPromises <span class="hljs-keyword">from</span> <span class="hljs-string">'node:timers/promises'</span>;
<span class="hljs-title function_">test</span>(<span class="hljs-string">'should tick five times testing a real use case'</span>, <span class="hljs-keyword">async</span> (context) => {
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setInterval'</span>] });

  <span class="hljs-keyword">const</span> expectedIterations = <span class="hljs-number">3</span>;
  <span class="hljs-keyword">const</span> interval = <span class="hljs-number">1000</span>;
  <span class="hljs-keyword">const</span> startedAt = <span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>();
  <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">run</span>(<span class="hljs-params"></span>) {
    <span class="hljs-keyword">const</span> times = [];
    <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> time <span class="hljs-keyword">of</span> nodeTimersPromises.<span class="hljs-built_in">setInterval</span>(interval, startedAt)) {
      times.<span class="hljs-title function_">push</span>(time);
      <span class="hljs-keyword">if</span> (times.<span class="hljs-property">length</span> === expectedIterations) <span class="hljs-keyword">break</span>;
    }
    <span class="hljs-keyword">return</span> times;
  }

  <span class="hljs-keyword">const</span> r = <span class="hljs-title function_">run</span>();
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(interval);
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(interval);
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(interval);

  <span class="hljs-keyword">const</span> timeResults = <span class="hljs-keyword">await</span> r;
  assert.<span class="hljs-title function_">strictEqual</span>(timeResults.<span class="hljs-property">length</span>, expectedIterations);
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> it = <span class="hljs-number">1</span>; it &#x3C; expectedIterations; it++) {
    assert.<span class="hljs-title function_">strictEqual</span>(timeResults[it - <span class="hljs-number">1</span>], startedAt + (interval * it));
  }
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { test } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);
<span class="hljs-keyword">const</span> nodeTimersPromises = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:timers/promises'</span>);
<span class="hljs-title function_">test</span>(<span class="hljs-string">'should tick five times testing a real use case'</span>, <span class="hljs-keyword">async</span> (context) => {
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setInterval'</span>] });

  <span class="hljs-keyword">const</span> expectedIterations = <span class="hljs-number">3</span>;
  <span class="hljs-keyword">const</span> interval = <span class="hljs-number">1000</span>;
  <span class="hljs-keyword">const</span> startedAt = <span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>();
  <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">run</span>(<span class="hljs-params"></span>) {
    <span class="hljs-keyword">const</span> times = [];
    <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> time <span class="hljs-keyword">of</span> nodeTimersPromises.<span class="hljs-built_in">setInterval</span>(interval, startedAt)) {
      times.<span class="hljs-title function_">push</span>(time);
      <span class="hljs-keyword">if</span> (times.<span class="hljs-property">length</span> === expectedIterations) <span class="hljs-keyword">break</span>;
    }
    <span class="hljs-keyword">return</span> times;
  }

  <span class="hljs-keyword">const</span> r = <span class="hljs-title function_">run</span>();
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(interval);
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(interval);
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">tick</span>(interval);

  <span class="hljs-keyword">const</span> timeResults = <span class="hljs-keyword">await</span> r;
  assert.<span class="hljs-title function_">strictEqual</span>(timeResults.<span class="hljs-property">length</span>, expectedIterations);
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> it = <span class="hljs-number">1</span>; it &#x3C; expectedIterations; it++) {
    assert.<span class="hljs-title function_">strictEqual</span>(timeResults[it - <span class="hljs-number">1</span>], startedAt + (interval * it));
  }
});</code><button class="copy-button">copy</button></pre>
<h4><code>timers.runAll()</code><span><a class="mark" href="#all_test_timersrunall" id="all_test_timersrunall">#</a></span><a aria-hidden="true" class="legacy" id="test_timers_runall"></a></h4>
<div class="api_metadata">
<span>Added in: v20.4.0</span>
</div>
<p>Triggers all pending mocked timers immediately. If the <code>Date</code> object is also
mocked, it will also advance the <code>Date</code> object to the furthest timer's time.</p>
<p>The example below triggers all pending timers immediately,
causing them to execute without any delay.</p>

<pre class="with-38-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> { test } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;

<span class="hljs-title function_">test</span>(<span class="hljs-string">'runAll functions following the given order'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>, <span class="hljs-string">'Date'</span>] });
  <span class="hljs-keyword">const</span> results = [];
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> results.<span class="hljs-title function_">push</span>(<span class="hljs-number">1</span>), <span class="hljs-number">9999</span>);

  <span class="hljs-comment">// Notice that if both timers have the same timeout,</span>
  <span class="hljs-comment">// the order of execution is guaranteed</span>
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> results.<span class="hljs-title function_">push</span>(<span class="hljs-number">3</span>), <span class="hljs-number">8888</span>);
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> results.<span class="hljs-title function_">push</span>(<span class="hljs-number">2</span>), <span class="hljs-number">8888</span>);

  assert.<span class="hljs-title function_">deepStrictEqual</span>(results, []);

  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">runAll</span>();
  assert.<span class="hljs-title function_">deepStrictEqual</span>(results, [<span class="hljs-number">3</span>, <span class="hljs-number">2</span>, <span class="hljs-number">1</span>]);
  <span class="hljs-comment">// The Date object is also advanced to the furthest timer's time</span>
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">9999</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { test } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);

<span class="hljs-title function_">test</span>(<span class="hljs-string">'runAll functions following the given order'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>, <span class="hljs-string">'Date'</span>] });
  <span class="hljs-keyword">const</span> results = [];
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> results.<span class="hljs-title function_">push</span>(<span class="hljs-number">1</span>), <span class="hljs-number">9999</span>);

  <span class="hljs-comment">// Notice that if both timers have the same timeout,</span>
  <span class="hljs-comment">// the order of execution is guaranteed</span>
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> results.<span class="hljs-title function_">push</span>(<span class="hljs-number">3</span>), <span class="hljs-number">8888</span>);
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> results.<span class="hljs-title function_">push</span>(<span class="hljs-number">2</span>), <span class="hljs-number">8888</span>);

  assert.<span class="hljs-title function_">deepStrictEqual</span>(results, []);

  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">runAll</span>();
  assert.<span class="hljs-title function_">deepStrictEqual</span>(results, [<span class="hljs-number">3</span>, <span class="hljs-number">2</span>, <span class="hljs-number">1</span>]);
  <span class="hljs-comment">// The Date object is also advanced to the furthest timer's time</span>
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">9999</span>);
});</code><button class="copy-button">copy</button></pre>
<p><strong>Note:</strong> The <code>runAll()</code> function is specifically designed for
triggering timers in the context of timer mocking.
It does not have any effect on real-time system
clocks or actual timers outside of the mocking environment.</p>
<h4><code>timers.setTime(milliseconds)</code><span><a class="mark" href="#all_test_timerssettimemilliseconds" id="all_test_timerssettimemilliseconds">#</a></span><a aria-hidden="true" class="legacy" id="test_timers_settime_milliseconds"></a></h4>
<div class="api_metadata">
<span>Added in: v20.11.0</span>
</div>
<p>Sets the current Unix timestamp that will be used as reference for any mocked
<code>Date</code> objects.</p>

<pre class="with-38-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> { test } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;

<span class="hljs-title function_">test</span>(<span class="hljs-string">'runAll functions following the given order'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
  <span class="hljs-keyword">const</span> now = <span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>();
  <span class="hljs-keyword">const</span> setTime = <span class="hljs-number">1000</span>;
  <span class="hljs-comment">// Date.now is not mocked</span>
  assert.<span class="hljs-title function_">deepStrictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), now);

  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'Date'</span>] });
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">setTime</span>(setTime);
  <span class="hljs-comment">// Date.now is now 1000</span>
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), setTime);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { test } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);

<span class="hljs-title function_">test</span>(<span class="hljs-string">'setTime replaces current time'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
  <span class="hljs-keyword">const</span> now = <span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>();
  <span class="hljs-keyword">const</span> setTime = <span class="hljs-number">1000</span>;
  <span class="hljs-comment">// Date.now is not mocked</span>
  assert.<span class="hljs-title function_">deepStrictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), now);

  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'Date'</span>] });
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">setTime</span>(setTime);
  <span class="hljs-comment">// Date.now is now 1000</span>
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), setTime);
});</code><button class="copy-button">copy</button></pre>
<h5>Dates and Timers working together<span><a class="mark" href="#all_test_dates-and-timers-working-together" id="all_test_dates-and-timers-working-together">#</a></span><a aria-hidden="true" class="legacy" id="test_dates_and_timers_working_together"></a></h5>
<p>Dates and timer objects are dependent on each other. If you use <code>setTime()</code> to
pass the current time to the mocked <code>Date</code> object, the set timers with
<code>setTimeout</code> and <code>setInterval</code> will <strong>not</strong> be affected.</p>
<p>However, the <code>tick</code> method <strong>will</strong> advanced the mocked <code>Date</code> object.</p>

<pre class="with-38-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> assert <span class="hljs-keyword">from</span> <span class="hljs-string">'node:assert'</span>;
<span class="hljs-keyword">import</span> { test } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:test'</span>;

<span class="hljs-title function_">test</span>(<span class="hljs-string">'runAll functions following the given order'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>, <span class="hljs-string">'Date'</span>] });
  <span class="hljs-keyword">const</span> results = [];
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> results.<span class="hljs-title function_">push</span>(<span class="hljs-number">1</span>), <span class="hljs-number">9999</span>);

  assert.<span class="hljs-title function_">deepStrictEqual</span>(results, []);
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">setTime</span>(<span class="hljs-number">12000</span>);
  assert.<span class="hljs-title function_">deepStrictEqual</span>(results, []);
  <span class="hljs-comment">// The date is advanced but the timers don't tick</span>
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">12000</span>);
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> { test } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:test'</span>);

<span class="hljs-title function_">test</span>(<span class="hljs-string">'runAll functions following the given order'</span>, <span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">enable</span>({ <span class="hljs-attr">apis</span>: [<span class="hljs-string">'setTimeout'</span>, <span class="hljs-string">'Date'</span>] });
  <span class="hljs-keyword">const</span> results = [];
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> results.<span class="hljs-title function_">push</span>(<span class="hljs-number">1</span>), <span class="hljs-number">9999</span>);

  assert.<span class="hljs-title function_">deepStrictEqual</span>(results, []);
  context.<span class="hljs-property">mock</span>.<span class="hljs-property">timers</span>.<span class="hljs-title function_">setTime</span>(<span class="hljs-number">12000</span>);
  assert.<span class="hljs-title function_">deepStrictEqual</span>(results, []);
  <span class="hljs-comment">// The date is advanced but the timers don't tick</span>
  assert.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>(), <span class="hljs-number">12000</span>);
});</code><button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>TestsStream</code><span><a class="mark" href="#all_test_class-testsstream" id="all_test_class-testsstream">#</a></span><a aria-hidden="true" class="legacy" id="test_class_testsstream"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0, v19.9.0, v18.17.0</td>
<td><p>added type to test:pass and test:fail events for when the test is a suite.</p></td></tr>
<tr><td>v18.9.0, v16.19.0</td>
<td><p><span>Added in: v18.9.0, v16.19.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Extends <a href="#all_stream_class-streamreadable" class="type">&#x3C;Readable></a></li>
</ul>
<p>A successful call to <a href="#all_test_runoptions"><code>run()</code></a> method will return a new <a href="#all_test_class-testsstream" class="type">&#x3C;TestsStream></a>
object, streaming a series of events representing the execution of the tests.
<code>TestsStream</code> will emit events, in the order of the tests definition</p>
<p>Some of the events are guaranteed to be emitted in the same order as the tests
are defined, while others are emitted in the order that the tests execute.</p>
<h4>Event: <code>'test:coverage'</code><span><a class="mark" href="#all_test_event-testcoverage" id="all_test_event-testcoverage">#</a></span><a aria-hidden="true" class="legacy" id="test_event_test_coverage"></a></h4>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>summary</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 coverage report.
<ul>
<li><code>files</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type">&#x3C;Array></a> An array of coverage reports for individual files. Each
report is an object with the following schema:
<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 absolute path of the file.</li>
<li><code>totalLineCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The total number of lines.</li>
<li><code>totalBranchCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The total number of branches.</li>
<li><code>totalFunctionCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The total number of functions.</li>
<li><code>coveredLineCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The number of covered lines.</li>
<li><code>coveredBranchCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The number of covered branches.</li>
<li><code>coveredFunctionCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The number of covered functions.</li>
<li><code>coveredLinePercent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The percentage of lines covered.</li>
<li><code>coveredBranchPercent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The percentage of branches covered.</li>
<li><code>coveredFunctionPercent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The percentage of functions covered.</li>
<li><code>functions</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type">&#x3C;Array></a> An array of functions representing function
coverage.
<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 function.</li>
<li><code>line</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The line number where the function is defined.</li>
<li><code>count</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The number of times the function was called.</li>
</ul>
</li>
<li><code>branches</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type">&#x3C;Array></a> An array of branches representing branch coverage.
<ul>
<li><code>line</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The line number where the branch is defined.</li>
<li><code>count</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The number of times the branch was taken.</li>
</ul>
</li>
<li><code>lines</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type">&#x3C;Array></a> An array of lines representing line
numbers and the number of times they were covered.
<ul>
<li><code>line</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The line number.</li>
<li><code>count</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The number of times the line was covered.</li>
</ul>
</li>
</ul>
</li>
<li><code>totals</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> An object containing a summary of coverage for all
files.
<ul>
<li><code>totalLineCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The total number of lines.</li>
<li><code>totalBranchCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The total number of branches.</li>
<li><code>totalFunctionCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The total number of functions.</li>
<li><code>coveredLineCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The number of covered lines.</li>
<li><code>coveredBranchCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The number of covered branches.</li>
<li><code>coveredFunctionCount</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The number of covered functions.</li>
<li><code>coveredLinePercent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The percentage of lines covered.</li>
<li><code>coveredBranchPercent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The percentage of branches covered.</li>
<li><code>coveredFunctionPercent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The percentage of functions covered.</li>
</ul>
</li>
<li><code>workingDirectory</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The working directory when code coverage
began. This is useful for displaying relative path names in case the tests
changed the working directory of the Node.js process.</li>
</ul>
</li>
<li><code>nesting</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The nesting level of the test.</li>
</ul>
</li>
</ul>
<p>Emitted when code coverage is enabled and all tests have completed.</p>
<h4>Event: <code>'test:complete'</code><span><a class="mark" href="#all_test_event-testcomplete" id="all_test_event-testcomplete">#</a></span><a aria-hidden="true" class="legacy" id="test_event_test_complete"></a></h4>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>column</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#Undefined_type" class="type">&#x3C;undefined></a> The column number where the test is defined, or
<code>undefined</code> if the test was run through the REPL.</li>
<li><code>details</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Additional execution metadata.
<ul>
<li><code>passed</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Whether the test passed or not.</li>
<li><code>duration_ms</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The duration of the test in milliseconds.</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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> An error wrapping the error thrown by the test
if it did not pass.
<ul>
<li><code>cause</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a> The actual error thrown by the test.</li>
</ul>
</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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> The type of the test, used to denote whether
this is a suite.</li>
</ul>
</li>
<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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> The path of the test file,
<code>undefined</code> if test was run through the REPL.</li>
<li><code>line</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#Undefined_type" class="type">&#x3C;undefined></a> The line number where the test is defined, or
<code>undefined</code> if the test was run through the REPL.</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 test name.</li>
<li><code>nesting</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The nesting level of the test.</li>
<li><code>testNumber</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The ordinal number of the test.</li>
<li><code>todo</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#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> Present if <a href="#all_test_contexttodomessage"><code>context.todo</code></a> is called</li>
<li><code>skip</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#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> Present if <a href="#all_test_contextskipmessage"><code>context.skip</code></a> is called</li>
</ul>
</li>
</ul>
<p>Emitted when a test completes its execution.
This event is not emitted in the same order as the tests are
defined.
The corresponding declaration ordered events are <code>'test:pass'</code> and <code>'test:fail'</code>.</p>
<h4>Event: <code>'test:dequeue'</code><span><a class="mark" href="#all_test_event-testdequeue" id="all_test_event-testdequeue">#</a></span><a aria-hidden="true" class="legacy" id="test_event_test_dequeue"></a></h4>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>column</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#Undefined_type" class="type">&#x3C;undefined></a> The column number where the test is defined, or
<code>undefined</code> if the test was run through the REPL.</li>
<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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> The path of the test file,
<code>undefined</code> if test was run through the REPL.</li>
<li><code>line</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#Undefined_type" class="type">&#x3C;undefined></a> The line number where the test is defined, or
<code>undefined</code> if the test was run through the REPL.</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 test name.</li>
<li><code>nesting</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The nesting level of the test.</li>
</ul>
</li>
</ul>
<p>Emitted when a test is dequeued, right before it is executed.
This event is not guaranteed to be emitted in the same order as the tests are
defined. The corresponding declaration ordered event is <code>'test:start'</code>.</p>
<h4>Event: <code>'test:diagnostic'</code><span><a class="mark" href="#all_test_event-testdiagnostic" id="all_test_event-testdiagnostic">#</a></span><a aria-hidden="true" class="legacy" id="test_event_test_diagnostic"></a></h4>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>column</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#Undefined_type" class="type">&#x3C;undefined></a> The column number where the test is defined, or
<code>undefined</code> if the test was run through the REPL.</li>
<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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> The path of the test file,
<code>undefined</code> if test was run through the REPL.</li>
<li><code>line</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#Undefined_type" class="type">&#x3C;undefined></a> The line number where the test is defined, or
<code>undefined</code> if the test was run through the REPL.</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> The diagnostic message.</li>
<li><code>nesting</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The nesting level of the test.</li>
</ul>
</li>
</ul>
<p>Emitted when <a href="#all_test_contextdiagnosticmessage"><code>context.diagnostic</code></a> is called.
This event is guaranteed to be emitted in the same order as the tests are
defined.</p>
<h4>Event: <code>'test:enqueue'</code><span><a class="mark" href="#all_test_event-testenqueue" id="all_test_event-testenqueue">#</a></span><a aria-hidden="true" class="legacy" id="test_event_test_enqueue"></a></h4>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>column</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#Undefined_type" class="type">&#x3C;undefined></a> The column number where the test is defined, or
<code>undefined</code> if the test was run through the REPL.</li>
<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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> The path of the test file,
<code>undefined</code> if test was run through the REPL.</li>
<li><code>line</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#Undefined_type" class="type">&#x3C;undefined></a> The line number where the test is defined, or
<code>undefined</code> if the test was run through the REPL.</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 test name.</li>
<li><code>nesting</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The nesting level of the test.</li>
</ul>
</li>
</ul>
<p>Emitted when a test is enqueued for execution.</p>
<h4>Event: <code>'test:fail'</code><span><a class="mark" href="#all_test_event-testfail" id="all_test_event-testfail">#</a></span><a aria-hidden="true" class="legacy" id="test_event_test_fail"></a></h4>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>column</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#Undefined_type" class="type">&#x3C;undefined></a> The column number where the test is defined, or
<code>undefined</code> if the test was run through the REPL.</li>
<li><code>details</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Additional execution metadata.
<ul>
<li><code>duration_ms</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The duration of the test in milliseconds.</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> An error wrapping the error thrown by the test.
<ul>
<li><code>cause</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a> The actual error thrown by the test.</li>
</ul>
</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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> The type of the test, used to denote whether
this is a suite.</li>
</ul>
</li>
<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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> The path of the test file,
<code>undefined</code> if test was run through the REPL.</li>
<li><code>line</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#Undefined_type" class="type">&#x3C;undefined></a> The line number where the test is defined, or
<code>undefined</code> if the test was run through the REPL.</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 test name.</li>
<li><code>nesting</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The nesting level of the test.</li>
<li><code>testNumber</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The ordinal number of the test.</li>
<li><code>todo</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#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> Present if <a href="#all_test_contexttodomessage"><code>context.todo</code></a> is called</li>
<li><code>skip</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#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> Present if <a href="#all_test_contextskipmessage"><code>context.skip</code></a> is called</li>
</ul>
</li>
</ul>
<p>Emitted when a test fails.
This event is guaranteed to be emitted in the same order as the tests are
defined.
The corresponding execution ordered event is <code>'test:complete'</code>.</p>
<h4>Event: <code>'test:pass'</code><span><a class="mark" href="#all_test_event-testpass" id="all_test_event-testpass">#</a></span><a aria-hidden="true" class="legacy" id="test_event_test_pass"></a></h4>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>column</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#Undefined_type" class="type">&#x3C;undefined></a> The column number where the test is defined, or
<code>undefined</code> if the test was run through the REPL.</li>
<li><code>details</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Additional execution metadata.
<ul>
<li><code>duration_ms</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The duration of the test in milliseconds.</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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> The type of the test, used to denote whether
this is a suite.</li>
</ul>
</li>
<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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> The path of the test file,
<code>undefined</code> if test was run through the REPL.</li>
<li><code>line</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#Undefined_type" class="type">&#x3C;undefined></a> The line number where the test is defined, or
<code>undefined</code> if the test was run through the REPL.</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 test name.</li>
<li><code>nesting</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The nesting level of the test.</li>
<li><code>testNumber</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The ordinal number of the test.</li>
<li><code>todo</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#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> Present if <a href="#all_test_contexttodomessage"><code>context.todo</code></a> is called</li>
<li><code>skip</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#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> Present if <a href="#all_test_contextskipmessage"><code>context.skip</code></a> is called</li>
</ul>
</li>
</ul>
<p>Emitted when a test passes.
This event is guaranteed to be emitted in the same order as the tests are
defined.
The corresponding execution ordered event is <code>'test:complete'</code>.</p>
<h4>Event: <code>'test:plan'</code><span><a class="mark" href="#all_test_event-testplan" id="all_test_event-testplan">#</a></span><a aria-hidden="true" class="legacy" id="test_event_test_plan"></a></h4>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>column</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#Undefined_type" class="type">&#x3C;undefined></a> The column number where the test is defined, or
<code>undefined</code> if the test was run through the REPL.</li>
<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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> The path of the test file,
<code>undefined</code> if test was run through the REPL.</li>
<li><code>line</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#Undefined_type" class="type">&#x3C;undefined></a> The line number where the test is defined, or
<code>undefined</code> if the test was run through the REPL.</li>
<li><code>nesting</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The nesting level of the test.</li>
<li><code>count</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The number of subtests that have ran.</li>
</ul>
</li>
</ul>
<p>Emitted when all subtests have completed for a given test.
This event is guaranteed to be emitted in the same order as the tests are
defined.</p>
<h4>Event: <code>'test:start'</code><span><a class="mark" href="#all_test_event-teststart" id="all_test_event-teststart">#</a></span><a aria-hidden="true" class="legacy" id="test_event_test_start"></a></h4>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>column</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#Undefined_type" class="type">&#x3C;undefined></a> The column number where the test is defined, or
<code>undefined</code> if the test was run through the REPL.</li>
<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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a> The path of the test file,
<code>undefined</code> if test was run through the REPL.</li>
<li><code>line</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#Undefined_type" class="type">&#x3C;undefined></a> The line number where the test is defined, or
<code>undefined</code> if the test was run through the REPL.</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 test name.</li>
<li><code>nesting</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The nesting level of the test.</li>
</ul>
</li>
</ul>
<p>Emitted when a test starts reporting its own and its subtests status.
This event is guaranteed to be emitted in the same order as the tests are
defined.
The corresponding execution ordered event is <code>'test:dequeue'</code>.</p>
<h4>Event: <code>'test:stderr'</code><span><a class="mark" href="#all_test_event-teststderr" id="all_test_event-teststderr">#</a></span><a aria-hidden="true" class="legacy" id="test_event_test_stderr"></a></h4>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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 path of the test file.</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> The message written to <code>stderr</code>.</li>
</ul>
</li>
</ul>
<p>Emitted when a running test writes to <code>stderr</code>.
This event is only emitted if <code>--test</code> flag is passed.
This event is not guaranteed to be emitted in the same order as the tests are
defined.</p>
<h4>Event: <code>'test:stdout'</code><span><a class="mark" href="#all_test_event-teststdout" id="all_test_event-teststdout">#</a></span><a aria-hidden="true" class="legacy" id="test_event_test_stdout"></a></h4>
<ul>
<li><code>data</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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 path of the test file.</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> The message written to <code>stdout</code>.</li>
</ul>
</li>
</ul>
<p>Emitted when a running test writes to <code>stdout</code>.
This event is only emitted if <code>--test</code> flag is passed.
This event is not guaranteed to be emitted in the same order as the tests are
defined.</p>
<h4>Event: <code>'test:watch:drained'</code><span><a class="mark" href="#all_test_event-testwatchdrained" id="all_test_event-testwatchdrained">#</a></span><a aria-hidden="true" class="legacy" id="test_event_test_watch_drained"></a></h4>
<p>Emitted when no more tests are queued for execution in watch mode.</p>
</section><section><h3>Class: <code>TestContext</code><span><a class="mark" href="#all_test_class-testcontext" id="all_test_class-testcontext">#</a></span><a aria-hidden="true" class="legacy" id="test_class_testcontext"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.1.0</td>
<td><p>The <code>before</code> function was added to TestContext.</p></td></tr>
<tr><td>v18.0.0, v16.17.0</td>
<td><p><span>Added in: v18.0.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>An instance of <code>TestContext</code> is passed to each test function in order to
interact with the test runner. However, the <code>TestContext</code> constructor is not
exposed as part of the API.</p>
<h4><code>context.before([fn][, options])</code><span><a class="mark" href="#all_test_contextbeforefn-options" id="all_test_contextbeforefn-options">#</a></span><a aria-hidden="true" class="legacy" id="test_context_before_fn_options"></a></h4>
<div class="api_metadata">
<span>Added in: v20.1.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://tc39.es/ecma262/#sec-async-function-constructor" class="type">&#x3C;AsyncFunction></a> The hook function. The first argument
to this function is a <a href="#all_test_class-testcontext"><code>TestContext</code></a> object. If the hook uses callbacks,
the callback function is passed as the second argument. <strong>Default:</strong> A no-op
function.</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> Configuration options for the hook. The following
properties are supported:
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> Allows aborting an in-progress hook.</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 of milliseconds the hook will fail after.
If unspecified, subtests inherit this value from their parent.
<strong>Default:</strong> <code>Infinity</code>.</li>
</ul>
</li>
</ul>
<p>This function is used to create a hook running before
subtest of the current test.</p>
<h4><code>context.beforeEach([fn][, options])</code><span><a class="mark" href="#all_test_contextbeforeeachfn-options" id="all_test_contextbeforeeachfn-options">#</a></span><a aria-hidden="true" class="legacy" id="test_context_beforeeach_fn_options"></a></h4>
<div class="api_metadata">
<span>Added in: v18.8.0, v16.18.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://tc39.es/ecma262/#sec-async-function-constructor" class="type">&#x3C;AsyncFunction></a> The hook function. The first argument
to this function is a <a href="#all_test_class-testcontext"><code>TestContext</code></a> object. If the hook uses callbacks,
the callback function is passed as the second argument. <strong>Default:</strong> A no-op
function.</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> Configuration options for the hook. The following
properties are supported:
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> Allows aborting an in-progress hook.</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 of milliseconds the hook will fail after.
If unspecified, subtests inherit this value from their parent.
<strong>Default:</strong> <code>Infinity</code>.</li>
</ul>
</li>
</ul>
<p>This function is used to create a hook running
before each subtest of the current test.</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'top level test'</span>, <span class="hljs-keyword">async</span> (t) => {
  t.<span class="hljs-title function_">beforeEach</span>(<span class="hljs-function">(<span class="hljs-params">t</span>) =></span> t.<span class="hljs-title function_">diagnostic</span>(<span class="hljs-string">`about to run <span class="hljs-subst">${t.name}</span>`</span>));
  <span class="hljs-keyword">await</span> t.<span class="hljs-title function_">test</span>(
    <span class="hljs-string">'This is a subtest'</span>,
    <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
      assert.<span class="hljs-title function_">ok</span>(<span class="hljs-string">'some relevant assertion here'</span>);
    },
  );
});</code> <button class="copy-button">copy</button></pre>
<h4><code>context.after([fn][, options])</code><span><a class="mark" href="#all_test_contextafterfn-options" id="all_test_contextafterfn-options">#</a></span><a aria-hidden="true" class="legacy" id="test_context_after_fn_options"></a></h4>
<div class="api_metadata">
<span>Added in: v19.3.0, v18.13.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://tc39.es/ecma262/#sec-async-function-constructor" class="type">&#x3C;AsyncFunction></a> The hook function. The first argument
to this function is a <a href="#all_test_class-testcontext"><code>TestContext</code></a> object. If the hook uses callbacks,
the callback function is passed as the second argument. <strong>Default:</strong> A no-op
function.</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> Configuration options for the hook. The following
properties are supported:
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> Allows aborting an in-progress hook.</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 of milliseconds the hook will fail after.
If unspecified, subtests inherit this value from their parent.
<strong>Default:</strong> <code>Infinity</code>.</li>
</ul>
</li>
</ul>
<p>This function is used to create a hook that runs after the current test
finishes.</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'top level test'</span>, <span class="hljs-keyword">async</span> (t) => {
  t.<span class="hljs-title function_">after</span>(<span class="hljs-function">(<span class="hljs-params">t</span>) =></span> t.<span class="hljs-title function_">diagnostic</span>(<span class="hljs-string">`finished running <span class="hljs-subst">${t.name}</span>`</span>));
  assert.<span class="hljs-title function_">ok</span>(<span class="hljs-string">'some relevant assertion here'</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4><code>context.afterEach([fn][, options])</code><span><a class="mark" href="#all_test_contextaftereachfn-options" id="all_test_contextaftereachfn-options">#</a></span><a aria-hidden="true" class="legacy" id="test_context_aftereach_fn_options"></a></h4>
<div class="api_metadata">
<span>Added in: v18.8.0, v16.18.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://tc39.es/ecma262/#sec-async-function-constructor" class="type">&#x3C;AsyncFunction></a> The hook function. The first argument
to this function is a <a href="#all_test_class-testcontext"><code>TestContext</code></a> object. If the hook uses callbacks,
the callback function is passed as the second argument. <strong>Default:</strong> A no-op
function.</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> Configuration options for the hook. The following
properties are supported:
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> Allows aborting an in-progress hook.</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 of milliseconds the hook will fail after.
If unspecified, subtests inherit this value from their parent.
<strong>Default:</strong> <code>Infinity</code>.</li>
</ul>
</li>
</ul>
<p>This function is used to create a hook running
after each subtest of the current test.</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'top level test'</span>, <span class="hljs-keyword">async</span> (t) => {
  t.<span class="hljs-title function_">afterEach</span>(<span class="hljs-function">(<span class="hljs-params">t</span>) =></span> t.<span class="hljs-title function_">diagnostic</span>(<span class="hljs-string">`finished running <span class="hljs-subst">${t.name}</span>`</span>));
  <span class="hljs-keyword">await</span> t.<span class="hljs-title function_">test</span>(
    <span class="hljs-string">'This is a subtest'</span>,
    <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
      assert.<span class="hljs-title function_">ok</span>(<span class="hljs-string">'some relevant assertion here'</span>);
    },
  );
});</code> <button class="copy-button">copy</button></pre>
<h4><code>context.assert</code><span><a class="mark" href="#all_test_contextassert" id="all_test_contextassert">#</a></span><a aria-hidden="true" class="legacy" id="test_context_assert"></a></h4>
<div class="api_metadata">
<span>Added in: v22.2.0</span>
</div>
<p>An object containing assertion methods bound to <code>context</code>. The top-level
functions from the <code>node:assert</code> module are exposed here for the purpose of
creating test plans.</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'test'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
  t.<span class="hljs-title function_">plan</span>(<span class="hljs-number">1</span>);
  t.<span class="hljs-property">assert</span>.<span class="hljs-title function_">strictEqual</span>(<span class="hljs-literal">true</span>, <span class="hljs-literal">true</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4><code>context.diagnostic(message)</code><span><a class="mark" href="#all_test_contextdiagnosticmessage" id="all_test_contextdiagnosticmessage">#</a></span><a aria-hidden="true" class="legacy" id="test_context_diagnostic_message"></a></h4>
<div class="api_metadata">
<span>Added in: v18.0.0, v16.17.0</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> Message to be reported.</li>
</ul>
<p>This function is used to write diagnostics to the output. Any diagnostic
information is included at the end of the test's results. This function does
not return a value.</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'top level test'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
  t.<span class="hljs-title function_">diagnostic</span>(<span class="hljs-string">'A diagnostic message'</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4><code>context.fullName</code><span><a class="mark" href="#all_test_contextfullname" id="all_test_contextfullname">#</a></span><a aria-hidden="true" class="legacy" id="test_context_fullname"></a></h4>
<div class="api_metadata">
<span>Added in: v20.16.0</span>
</div>
<p>The name of the test and each of its ancestors, separated by <code>></code>.</p>
<h4><code>context.name</code><span><a class="mark" href="#all_test_contextname" id="all_test_contextname">#</a></span><a aria-hidden="true" class="legacy" id="test_context_name"></a></h4>
<div class="api_metadata">
<span>Added in: v18.8.0, v16.18.0</span>
</div>
<p>The name of the test.</p>
<h4><code>context.plan(count)</code><span><a class="mark" href="#all_test_contextplancount" id="all_test_contextplancount">#</a></span><a aria-hidden="true" class="legacy" id="test_context_plan_count"></a></h4>
<div class="api_metadata">
<span>Added in: v20.15.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>count</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The number of assertions and subtests that are expected to run.</li>
</ul>
<p>This function is used to set the number of assertions and subtests that are expected to run
within the test. If the number of assertions and subtests that run does not match the
expected count, the test will fail.</p>
<blockquote>
<p>Note: To make sure assertions are tracked, <code>t.assert</code> must be used instead of <code>assert</code> directly.</p>
</blockquote>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'top level test'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
  t.<span class="hljs-title function_">plan</span>(<span class="hljs-number">2</span>);
  t.<span class="hljs-property">assert</span>.<span class="hljs-title function_">ok</span>(<span class="hljs-string">'some relevant assertion here'</span>);
  t.<span class="hljs-title function_">test</span>(<span class="hljs-string">'subtest'</span>, <span class="hljs-function">() =></span> {});
});</code> <button class="copy-button">copy</button></pre>
<p>When working with asynchronous code, the <code>plan</code> function can be used to ensure that the
correct number of assertions are run:</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'planning with streams'</span>, <span class="hljs-function">(<span class="hljs-params">t, done</span>) =></span> {
  <span class="hljs-keyword">function</span>* <span class="hljs-title function_">generate</span>(<span class="hljs-params"></span>) {
    <span class="hljs-keyword">yield</span> <span class="hljs-string">'a'</span>;
    <span class="hljs-keyword">yield</span> <span class="hljs-string">'b'</span>;
    <span class="hljs-keyword">yield</span> <span class="hljs-string">'c'</span>;
  }
  <span class="hljs-keyword">const</span> expected = [<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>];
  t.<span class="hljs-title function_">plan</span>(expected.<span class="hljs-property">length</span>);
  <span class="hljs-keyword">const</span> stream = <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>(<span class="hljs-title function_">generate</span>());
  stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> {
    t.<span class="hljs-property">assert</span>.<span class="hljs-title function_">strictEqual</span>(chunk, expected.<span class="hljs-title function_">shift</span>());
  });

  stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> {
    <span class="hljs-title function_">done</span>();
  });
});</code> <button class="copy-button">copy</button></pre>
<h4><code>context.runOnly(shouldRunOnlyTests)</code><span><a class="mark" href="#all_test_contextrunonlyshouldrunonlytests" id="all_test_contextrunonlyshouldrunonlytests">#</a></span><a aria-hidden="true" class="legacy" id="test_context_runonly_shouldrunonlytests"></a></h4>
<div class="api_metadata">
<span>Added in: v18.0.0, v16.17.0</span>
</div>
<ul>
<li><code>shouldRunOnlyTests</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 run <code>only</code> tests.</li>
</ul>
<p>If <code>shouldRunOnlyTests</code> is truthy, the test context will only run tests that
have the <code>only</code> option set. Otherwise, all tests are run. If Node.js was not
started with the <a href="#all_cli_--test-only"><code>--test-only</code></a> command-line option, this function is a
no-op.</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'top level test'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
  <span class="hljs-comment">// The test context can be set to run subtests with the 'only' option.</span>
  t.<span class="hljs-title function_">runOnly</span>(<span class="hljs-literal">true</span>);
  <span class="hljs-keyword">return</span> <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">all</span>([
    t.<span class="hljs-title function_">test</span>(<span class="hljs-string">'this subtest is now skipped'</span>),
    t.<span class="hljs-title function_">test</span>(<span class="hljs-string">'this subtest is run'</span>, { <span class="hljs-attr">only</span>: <span class="hljs-literal">true</span> }),
  ]);
});</code> <button class="copy-button">copy</button></pre>
<h4><code>context.signal</code><span><a class="mark" href="#all_test_contextsignal" id="all_test_contextsignal">#</a></span><a aria-hidden="true" class="legacy" id="test_context_signal"></a></h4>
<div class="api_metadata">
<span>Added in: v18.7.0, v16.17.0</span>
</div>
<ul>
<li>Type: <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a></li>
</ul>
<p>Can be used to abort test subtasks when the test has been aborted.</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'top level test'</span>, <span class="hljs-keyword">async</span> (t) => {
  <span class="hljs-keyword">await</span> <span class="hljs-title function_">fetch</span>(<span class="hljs-string">'some/uri'</span>, { <span class="hljs-attr">signal</span>: t.<span class="hljs-property">signal</span> });
});</code> <button class="copy-button">copy</button></pre>
<h4><code>context.skip([message])</code><span><a class="mark" href="#all_test_contextskipmessage" id="all_test_contextskipmessage">#</a></span><a aria-hidden="true" class="legacy" id="test_context_skip_message"></a></h4>
<div class="api_metadata">
<span>Added in: v18.0.0, v16.17.0</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> Optional skip message.</li>
</ul>
<p>This function causes the test's output to indicate the test as skipped. If
<code>message</code> is provided, it is included in the output. Calling <code>skip()</code> does
not terminate execution of the test function. This function does not return a
value.</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'top level test'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
  <span class="hljs-comment">// Make sure to return here as well if the test contains additional logic.</span>
  t.<span class="hljs-title function_">skip</span>(<span class="hljs-string">'this is skipped'</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4><code>context.todo([message])</code><span><a class="mark" href="#all_test_contexttodomessage" id="all_test_contexttodomessage">#</a></span><a aria-hidden="true" class="legacy" id="test_context_todo_message"></a></h4>
<div class="api_metadata">
<span>Added in: v18.0.0, v16.17.0</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> Optional <code>TODO</code> message.</li>
</ul>
<p>This function adds a <code>TODO</code> directive to the test's output. If <code>message</code> is
provided, it is included in the output. Calling <code>todo()</code> does not terminate
execution of the test function. This function does not return a value.</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'top level test'</span>, <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
  <span class="hljs-comment">// This test is marked as `TODO`</span>
  t.<span class="hljs-title function_">todo</span>(<span class="hljs-string">'this is a todo'</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4><code>context.test([name][, options][, fn])</code><span><a class="mark" href="#all_test_contexttestname-options-fn" id="all_test_contexttestname-options-fn">#</a></span><a aria-hidden="true" class="legacy" id="test_context_test_name_options_fn"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.8.0, v16.18.0</td>
<td><p>Add a <code>signal</code> option.</p></td></tr>
<tr><td>v18.7.0, v16.17.0</td>
<td><p>Add a <code>timeout</code> option.</p></td></tr>
<tr><td>v18.0.0, v16.17.0</td>
<td><p><span>Added in: v18.0.0, v16.17.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> The name of the subtest, which is displayed when reporting
test results. <strong>Default:</strong> The <code>name</code> property of <code>fn</code>, or <code>'&#x3C;anonymous>'</code> if
<code>fn</code> does not have a name.</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> Configuration options for the subtest. The following
properties are supported:
<ul>
<li><code>concurrency</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#Boolean_type" class="type">&#x3C;boolean></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a> If a number is provided,
then that many tests would run in parallel within the application thread.
If <code>true</code>, it would run all subtests in parallel.
If <code>false</code>, it would only run one test at a time.
If unspecified, subtests inherit this value from their parent.
<strong>Default:</strong> <code>null</code>.</li>
<li><code>only</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If truthy, and the test context is configured to run
<code>only</code> tests, then this test will be run. Otherwise, the test is skipped.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> Allows aborting an in-progress test.</li>
<li><code>skip</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 truthy, the test is skipped. If a string is
provided, that string is displayed in the test results as the reason for
skipping the test. <strong>Default:</strong> <code>false</code>.</li>
<li><code>todo</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 truthy, the test marked as <code>TODO</code>. If a string
is provided, that string is displayed in the test results as the reason why
the test is <code>TODO</code>. <strong>Default:</strong> <code>false</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> A number of milliseconds the test will fail after.
If unspecified, subtests inherit this value from their parent.
<strong>Default:</strong> <code>Infinity</code>.</li>
<li><code>plan</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The number of assertions and subtests expected to be run in the test.
If the number of assertions run in the test does not match the number
specified in the plan, the test will fail.
<strong>Default:</strong> <code>undefined</code>.</li>
</ul>
</li>
<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://tc39.es/ecma262/#sec-async-function-constructor" class="type">&#x3C;AsyncFunction></a> The function under test. The first argument
to this function is a <a href="#all_test_class-testcontext"><code>TestContext</code></a> object. If the test uses callbacks,
the callback function is passed as the second argument. <strong>Default:</strong> A no-op
function.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> Fulfilled with <code>undefined</code> once the test completes.</li>
</ul>
<p>This function is used to create subtests under the current test. This function
behaves in the same fashion as the top level <a href="#all_test_testname-options-fn"><code>test()</code></a> function.</p>
<pre><code class="language-js"><span class="hljs-title function_">test</span>(<span class="hljs-string">'top level test'</span>, <span class="hljs-keyword">async</span> (t) => {
  <span class="hljs-keyword">await</span> t.<span class="hljs-title function_">test</span>(
    <span class="hljs-string">'This is a subtest'</span>,
    { <span class="hljs-attr">only</span>: <span class="hljs-literal">false</span>, <span class="hljs-attr">skip</span>: <span class="hljs-literal">false</span>, <span class="hljs-attr">concurrency</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">todo</span>: <span class="hljs-literal">false</span>, <span class="hljs-attr">plan</span>: <span class="hljs-number">1</span> },
    <span class="hljs-function">(<span class="hljs-params">t</span>) =></span> {
      t.<span class="hljs-property">assert</span>.<span class="hljs-title function_">ok</span>(<span class="hljs-string">'some relevant assertion here'</span>);
    },
  );
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>SuiteContext</code><span><a class="mark" href="#all_test_class-suitecontext" id="all_test_class-suitecontext">#</a></span><a aria-hidden="true" class="legacy" id="test_class_suitecontext"></a></h3>
<div class="api_metadata">
<span>Added in: v18.7.0, v16.17.0</span>
</div>
<p>An instance of <code>SuiteContext</code> is passed to each suite function in order to
interact with the test runner. However, the <code>SuiteContext</code> constructor is not
exposed as part of the API.</p>
<h4><code>context.name</code><span><a class="mark" href="#all_test_contextname_1" id="all_test_contextname_1">#</a></span><a aria-hidden="true" class="legacy" id="test_context_name_1"></a></h4>
<div class="api_metadata">
<span>Added in: v18.8.0, v16.18.0</span>
</div>
<p>The name of the suite.</p>
<h4><code>context.signal</code><span><a class="mark" href="#all_test_contextsignal_1" id="all_test_contextsignal_1">#</a></span><a aria-hidden="true" class="legacy" id="test_context_signal_1"></a></h4>
<div class="api_metadata">
<span>Added in: v18.7.0, v16.17.0</span>
</div>
<ul>
<li>Type: <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a></li>
</ul>
<p>Can be used to abort test subtasks when the test has been aborted.</p></section>
        </section>
<section><h2>Timers<span><a class="mark" href="#all_timers_timers" id="all_timers_timers">#</a></span><a aria-hidden="true" class="legacy" id="timers_timers"></a></h2>

<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/timers.js">lib/timers.js</a></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('node: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>
<section><h3>Class: <code>Immediate</code><span><a class="mark" href="#all_timers_class-immediate" id="all_timers_class-immediate">#</a></span><a aria-hidden="true" class="legacy" id="timers_class_immediate"></a></h3>
<p>This object is created internally and is returned from <a href="#all_timers_setimmediatecallback-args"><code>setImmediate()</code></a>. It
can be passed to <a href="#all_timers_clearimmediateimmediate"><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="#all_timers_setimmediatecallback-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>
<h4><code>immediate.hasRef()</code><span><a class="mark" href="#all_timers_immediatehasref" id="all_timers_immediatehasref">#</a></span><a aria-hidden="true" class="legacy" id="timers_immediate_hasref"></a></h4>
<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>
<h4><code>immediate.ref()</code><span><a class="mark" href="#all_timers_immediateref" id="all_timers_immediateref">#</a></span><a aria-hidden="true" class="legacy" id="timers_immediate_ref"></a></h4>
<div class="api_metadata">
<span>Added in: v9.7.0</span>
</div>
<ul>
<li>Returns: <a href="#all_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>
<h4><code>immediate.unref()</code><span><a class="mark" href="#all_timers_immediateunref" id="all_timers_immediateunref">#</a></span><a aria-hidden="true" class="legacy" id="timers_immediate_unref"></a></h4>
<div class="api_metadata">
<span>Added in: v9.7.0</span>
</div>
<ul>
<li>Returns: <a href="#all_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>
<h4><code>immediate[Symbol.dispose]()</code><span><a class="mark" href="#all_timers_immediatesymboldispose" id="all_timers_immediatesymboldispose">#</a></span><a aria-hidden="true" class="legacy" id="timers_immediate_symbol_dispose"></a></h4>
<div class="api_metadata">
<span>Added in: v20.5.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Cancels the immediate. This is similar to calling <code>clearImmediate()</code>.</p>
</section><section><h3>Class: <code>Timeout</code><span><a class="mark" href="#all_timers_class-timeout" id="all_timers_class-timeout">#</a></span><a aria-hidden="true" class="legacy" id="timers_class_timeout"></a></h3>
<p>This object is created internally and is returned from <a href="#all_timers_settimeoutcallback-delay-args"><code>setTimeout()</code></a> and
<a href="#all_timers_setintervalcallback-delay-args"><code>setInterval()</code></a>. It can be passed to either <a href="#all_timers_cleartimeouttimeout"><code>clearTimeout()</code></a> or
<a href="#all_timers_clearintervaltimeout"><code>clearInterval()</code></a> in order to cancel the scheduled actions.</p>
<p>By default, when a timer is scheduled using either <a href="#all_timers_settimeoutcallback-delay-args"><code>setTimeout()</code></a> or
<a href="#all_timers_setintervalcallback-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>
<h4><code>timeout.close()</code><span><a class="mark" href="#all_timers_timeoutclose" id="all_timers_timeoutclose">#</a></span><a aria-hidden="true" class="legacy" id="timers_timeout_close"></a></h4>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy: Use <a href="#all_timers_cleartimeouttimeout"><code>clearTimeout()</code></a> instead.</div><p></p>
<ul>
<li>Returns: <a href="#all_timers_class-timeout" class="type">&#x3C;Timeout></a> a reference to <code>timeout</code></li>
</ul>
<p>Cancels the timeout.</p>
<h4><code>timeout.hasRef()</code><span><a class="mark" href="#all_timers_timeouthasref" id="all_timers_timeouthasref">#</a></span><a aria-hidden="true" class="legacy" id="timers_timeout_hasref"></a></h4>
<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>
<h4><code>timeout.ref()</code><span><a class="mark" href="#all_timers_timeoutref" id="all_timers_timeoutref">#</a></span><a aria-hidden="true" class="legacy" id="timers_timeout_ref"></a></h4>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div>
<ul>
<li>Returns: <a href="#all_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>
<h4><code>timeout.refresh()</code><span><a class="mark" href="#all_timers_timeoutrefresh" id="all_timers_timeoutrefresh">#</a></span><a aria-hidden="true" class="legacy" id="timers_timeout_refresh"></a></h4>
<div class="api_metadata">
<span>Added in: v10.2.0</span>
</div>
<ul>
<li>Returns: <a href="#all_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>
<h4><code>timeout.unref()</code><span><a class="mark" href="#all_timers_timeoutunref" id="all_timers_timeoutunref">#</a></span><a aria-hidden="true" class="legacy" id="timers_timeout_unref"></a></h4>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div>
<ul>
<li>Returns: <a href="#all_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>
<h4><code>timeout[Symbol.toPrimitive]()</code><span><a class="mark" href="#all_timers_timeoutsymboltoprimitive" id="all_timers_timeoutsymboltoprimitive">#</a></span><a aria-hidden="true" class="legacy" id="timers_timeout_symbol_toprimitive"></a></h4>
<div class="api_metadata">
<span>Added in: v14.9.0, v12.19.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> a number that can be used to reference this <code>timeout</code></li>
</ul>
<p>Coerce a <code>Timeout</code> to a primitive. The primitive can be used to
clear the <code>Timeout</code>. The primitive can only be used in the
same thread where the timeout was created. Therefore, to use it
across <a href="worker_threads.html"><code>worker_threads</code></a> it must first be passed to the correct
thread. This allows enhanced compatibility with browser
<code>setTimeout()</code> and <code>setInterval()</code> implementations.</p>
<h4><code>timeout[Symbol.dispose]()</code><span><a class="mark" href="#all_timers_timeoutsymboldispose" id="all_timers_timeoutsymboldispose">#</a></span><a aria-hidden="true" class="legacy" id="timers_timeout_symbol_dispose"></a></h4>
<div class="api_metadata">
<span>Added in: v20.5.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Cancels the timeout.</p>
</section><section><h3>Scheduling timers<span><a class="mark" href="#all_timers_scheduling-timers" id="all_timers_scheduling-timers">#</a></span><a aria-hidden="true" class="legacy" id="timers_scheduling_timers"></a></h3>
<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>
<h4><code>setImmediate(callback[, ...args])</code><span><a class="mark" href="#all_timers_setimmediatecallback-args" id="all_timers_setimmediatecallback-args">#</a></span><a aria-hidden="true" class="legacy" id="timers_setimmediate_callback_args"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></tr>
<tr><td>v0.9.1</td>
<td><p><span>Added in: v0.9.1</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> 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="#all_timers_class-immediate" class="type">&#x3C;Immediate></a> for use with <a href="#all_timers_clearimmediateimmediate"><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="#all_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="#all_timers_timerspromisessetimmediatevalue-options"><code>timersPromises.setImmediate()</code></a>.</p>
<h4><code>setInterval(callback[, delay[, ...args]])</code><span><a class="mark" href="#all_timers_setintervalcallback-delay-args" id="all_timers_setintervalcallback-delay-args">#</a></span><a aria-hidden="true" class="legacy" id="timers_setinterval_callback_delay_args"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></tr>
<tr><td>v0.0.1</td>
<td><p><span>Added in: v0.0.1</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> 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>. <strong>Default:</strong> <code>1</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="#all_timers_class-timeout" class="type">&#x3C;Timeout></a> for use with <a href="#all_timers_clearintervaltimeout"><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="#all_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="#all_timers_timerspromisessetintervaldelay-value-options"><code>timersPromises.setInterval()</code></a>.</p>
<h4><code>setTimeout(callback[, delay[, ...args]])</code><span><a class="mark" href="#all_timers_settimeoutcallback-delay-args" id="all_timers_settimeoutcallback-delay-args">#</a></span><a aria-hidden="true" class="legacy" id="timers_settimeout_callback_delay_args"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></tr>
<tr><td>v0.0.1</td>
<td><p><span>Added in: v0.0.1</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> 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>. <strong>Default:</strong> <code>1</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="#all_timers_class-timeout" class="type">&#x3C;Timeout></a> for use with <a href="#all_timers_cleartimeouttimeout"><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="#all_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="#all_timers_timerspromisessettimeoutdelay-value-options"><code>timersPromises.setTimeout()</code></a>.</p>
</section><section><h3>Cancelling timers<span><a class="mark" href="#all_timers_cancelling-timers" id="all_timers_cancelling-timers">#</a></span><a aria-hidden="true" class="legacy" id="timers_cancelling_timers"></a></h3>
<p>The <a href="#all_timers_setimmediatecallback-args"><code>setImmediate()</code></a>, <a href="#all_timers_setintervalcallback-delay-args"><code>setInterval()</code></a>, and <a href="#all_timers_settimeoutcallback-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>For the promisified variants of <a href="#all_timers_setimmediatecallback-args"><code>setImmediate()</code></a> and <a href="#all_timers_settimeoutcallback-delay-args"><code>setTimeout()</code></a>,
an <a href="#all_globals_class-abortcontroller"><code>AbortController</code></a> may be used to cancel the timer. When canceled, the
returned Promises will be rejected with an <code>'AbortError'</code>.</p>
<p>For <code>setImmediate()</code>:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-attr">setImmediate</span>: setImmediatePromise } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:timers/promises'</span>);

<span class="hljs-keyword">const</span> ac = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
<span class="hljs-keyword">const</span> signal = ac.<span class="hljs-property">signal</span>;

<span class="hljs-title function_">setImmediatePromise</span>(<span class="hljs-string">'foobar'</span>, { signal })
  .<span class="hljs-title function_">then</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>)
  .<span class="hljs-title function_">catch</span>(<span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
    <span class="hljs-keyword">if</span> (err.<span class="hljs-property">name</span> === <span class="hljs-string">'AbortError'</span>)
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'The immediate was aborted'</span>);
  });

ac.<span class="hljs-title function_">abort</span>();</code> <button class="copy-button">copy</button></pre>
<p>For <code>setTimeout()</code>:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-attr">setTimeout</span>: setTimeoutPromise } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:timers/promises'</span>);

<span class="hljs-keyword">const</span> ac = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
<span class="hljs-keyword">const</span> signal = ac.<span class="hljs-property">signal</span>;

setTimeoutPromise(<span class="hljs-number">1000</span>, <span class="hljs-string">'foobar'</span>, { signal })
  .<span class="hljs-title function_">then</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>)
  .<span class="hljs-title function_">catch</span>(<span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
    <span class="hljs-keyword">if</span> (err.<span class="hljs-property">name</span> === <span class="hljs-string">'AbortError'</span>)
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'The timeout was aborted'</span>);
  });

ac.<span class="hljs-title function_">abort</span>();</code> <button class="copy-button">copy</button></pre>
<h4><code>clearImmediate(immediate)</code><span><a class="mark" href="#all_timers_clearimmediateimmediate" id="all_timers_clearimmediateimmediate">#</a></span><a aria-hidden="true" class="legacy" id="timers_clearimmediate_immediate"></a></h4>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div>
<ul>
<li><code>immediate</code> <a href="#all_timers_class-immediate" class="type">&#x3C;Immediate></a> An <code>Immediate</code> object as returned by
<a href="#all_timers_setimmediatecallback-args"><code>setImmediate()</code></a>.</li>
</ul>
<p>Cancels an <code>Immediate</code> object created by <a href="#all_timers_setimmediatecallback-args"><code>setImmediate()</code></a>.</p>
<h4><code>clearInterval(timeout)</code><span><a class="mark" href="#all_timers_clearintervaltimeout" id="all_timers_clearintervaltimeout">#</a></span><a aria-hidden="true" class="legacy" id="timers_clearinterval_timeout"></a></h4>
<div class="api_metadata">
<span>Added in: v0.0.1</span>
</div>
<ul>
<li><code>timeout</code> <a href="#all_timers_class-timeout" class="type">&#x3C;Timeout></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 <code>Timeout</code> object as returned by <a href="#all_timers_setintervalcallback-delay-args"><code>setInterval()</code></a>
or the <a href="#all_timers_timeoutsymboltoprimitive">primitive</a> of the <code>Timeout</code> object as a string or a number.</li>
</ul>
<p>Cancels a <code>Timeout</code> object created by <a href="#all_timers_setintervalcallback-delay-args"><code>setInterval()</code></a>.</p>
<h4><code>clearTimeout(timeout)</code><span><a class="mark" href="#all_timers_cleartimeouttimeout" id="all_timers_cleartimeouttimeout">#</a></span><a aria-hidden="true" class="legacy" id="timers_cleartimeout_timeout"></a></h4>
<div class="api_metadata">
<span>Added in: v0.0.1</span>
</div>
<ul>
<li><code>timeout</code> <a href="#all_timers_class-timeout" class="type">&#x3C;Timeout></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 <code>Timeout</code> object as returned by <a href="#all_timers_settimeoutcallback-delay-args"><code>setTimeout()</code></a>
or the <a href="#all_timers_timeoutsymboltoprimitive">primitive</a> of the <code>Timeout</code> object as a string or a number.</li>
</ul>
<p>Cancels a <code>Timeout</code> object created by <a href="#all_timers_settimeoutcallback-delay-args"><code>setTimeout()</code></a>.</p>
</section><section><h3>Timers Promises API<span><a class="mark" href="#all_timers_timers-promises-api" id="all_timers_timers-promises-api">#</a></span><a aria-hidden="true" class="legacy" id="timers_timers_promises_api"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.0.0</td>
<td><p>Graduated from experimental.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p><span>Added in: v15.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>The <code>timers/promises</code> API provides an alternative set of timer functions
that return <code>Promise</code> objects. The API is accessible via
<code>require('node:timers/promises')</code>.</p>

<pre class="with-13-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> {
  <span class="hljs-built_in">setTimeout</span>,
  setImmediate,
  <span class="hljs-built_in">setInterval</span>,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:timers/promises'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
  <span class="hljs-built_in">setTimeout</span>,
  setImmediate,
  <span class="hljs-built_in">setInterval</span>,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:timers/promises'</span>);</code><button class="copy-button">copy</button></pre>
<h4><code>timersPromises.setTimeout([delay[, value[, options]]])</code><span><a class="mark" href="#all_timers_timerspromisessettimeoutdelay-value-options" id="all_timers_timerspromisessettimeoutdelay-value-options">#</a></span><a aria-hidden="true" class="legacy" id="timers_timerspromises_settimeout_delay_value_options"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<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 fulfilling the
promise. <strong>Default:</strong> <code>1</code>.</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> A value with which the promise is fulfilled.</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>
<ul>
<li><code>ref</code> <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> to indicate that the scheduled <code>Timeout</code>
should not require the Node.js event loop to remain active.
<strong>Default:</strong> <code>true</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> An optional <code>AbortSignal</code> that can be used to
cancel the scheduled <code>Timeout</code>.</li>
</ul>
</li>
</ul>

<pre class="with-13-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> {
  <span class="hljs-built_in">setTimeout</span>,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:timers/promises'</span>;

<span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> <span class="hljs-built_in">setTimeout</span>(<span class="hljs-number">100</span>, <span class="hljs-string">'result'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(res);  <span class="hljs-comment">// Prints 'result'</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
  <span class="hljs-built_in">setTimeout</span>,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:timers/promises'</span>);

<span class="hljs-built_in">setTimeout</span>(<span class="hljs-number">100</span>, <span class="hljs-string">'result'</span>).<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(res);  <span class="hljs-comment">// Prints 'result'</span>
});</code><button class="copy-button">copy</button></pre>
<h4><code>timersPromises.setImmediate([value[, options]])</code><span><a class="mark" href="#all_timers_timerspromisessetimmediatevalue-options" id="all_timers_timerspromisessetimmediatevalue-options">#</a></span><a aria-hidden="true" class="legacy" id="timers_timerspromises_setimmediate_value_options"></a></h4>
<div class="api_metadata">
<span>Added in: v15.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> A value with which the promise is fulfilled.</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>
<ul>
<li><code>ref</code> <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> to indicate that the scheduled <code>Immediate</code>
should not require the Node.js event loop to remain active.
<strong>Default:</strong> <code>true</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> An optional <code>AbortSignal</code> that can be used to
cancel the scheduled <code>Immediate</code>.</li>
</ul>
</li>
</ul>

<pre class="with-15-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> {
  setImmediate,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:timers/promises'</span>;

<span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> <span class="hljs-title function_">setImmediate</span>(<span class="hljs-string">'result'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(res);  <span class="hljs-comment">// Prints 'result'</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
  setImmediate,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:timers/promises'</span>);

<span class="hljs-title function_">setImmediate</span>(<span class="hljs-string">'result'</span>).<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">res</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(res);  <span class="hljs-comment">// Prints 'result'</span>
});</code><button class="copy-button">copy</button></pre>
<h4><code>timersPromises.setInterval([delay[, value[, options]]])</code><span><a class="mark" href="#all_timers_timerspromisessetintervaldelay-value-options" id="all_timers_timerspromisessetintervaldelay-value-options">#</a></span><a aria-hidden="true" class="legacy" id="timers_timerspromises_setinterval_delay_value_options"></a></h4>
<div class="api_metadata">
<span>Added in: v15.9.0</span>
</div>
<p>Returns an async iterator that generates values in an interval of <code>delay</code> ms.
If <code>ref</code> is <code>true</code>, you need to call <code>next()</code> of async iterator explicitly
or implicitly to keep the event loop alive.</p>
<ul>
<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 between iterations.
<strong>Default:</strong> <code>1</code>.</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> A value with which the iterator returns.</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>
<ul>
<li><code>ref</code> <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> to indicate that the scheduled <code>Timeout</code>
between iterations should not require the Node.js event loop to
remain active.
<strong>Default:</strong> <code>true</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> An optional <code>AbortSignal</code> that can be used to
cancel the scheduled <code>Timeout</code> between operations.</li>
</ul>
</li>
</ul>

<pre class="with-14-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> {
  <span class="hljs-built_in">setInterval</span>,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:timers/promises'</span>;

<span class="hljs-keyword">const</span> interval = <span class="hljs-number">100</span>;
<span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> startTime <span class="hljs-keyword">of</span> <span class="hljs-built_in">setInterval</span>(interval, <span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>())) {
  <span class="hljs-keyword">const</span> now = <span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>();
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(now);
  <span class="hljs-keyword">if</span> ((now - startTime) > <span class="hljs-number">1000</span>)
    <span class="hljs-keyword">break</span>;
}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>());</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
  <span class="hljs-built_in">setInterval</span>,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:timers/promises'</span>);
<span class="hljs-keyword">const</span> interval = <span class="hljs-number">100</span>;

(<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> startTime <span class="hljs-keyword">of</span> <span class="hljs-built_in">setInterval</span>(interval, <span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>())) {
    <span class="hljs-keyword">const</span> now = <span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>();
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(now);
    <span class="hljs-keyword">if</span> ((now - startTime) > <span class="hljs-number">1000</span>)
      <span class="hljs-keyword">break</span>;
  }
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>());
})();</code><button class="copy-button">copy</button></pre>
<h4><code>timersPromises.scheduler.wait(delay[, options])</code><span><a class="mark" href="#all_timers_timerspromisesschedulerwaitdelay-options" id="all_timers_timerspromisesschedulerwaitdelay-options">#</a></span><a aria-hidden="true" class="legacy" id="timers_timerspromises_scheduler_wait_delay_options"></a></h4>
<div class="api_metadata">
<span>Added in: v17.3.0, v16.14.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<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 resolving the
promise.</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>
<ul>
<li><code>ref</code> <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> to indicate that the scheduled <code>Timeout</code>
should not require the Node.js event loop to remain active.
<strong>Default:</strong> <code>true</code>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> An optional <code>AbortSignal</code> that can be used to
cancel waiting.</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>An experimental API defined by the <a href="https://github.com/WICG/scheduling-apis">Scheduling APIs</a> draft specification
being developed as a standard Web Platform API.</p>
<p>Calling <code>timersPromises.scheduler.wait(delay, options)</code> is equivalent
to calling <code>timersPromises.setTimeout(delay, undefined, options)</code>.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { scheduler } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:timers/promises'</span>;

<span class="hljs-keyword">await</span> scheduler.<span class="hljs-title function_">wait</span>(<span class="hljs-number">1000</span>); <span class="hljs-comment">// Wait one second before continuing</span></code> <button class="copy-button">copy</button></pre>
<h4><code>timersPromises.scheduler.yield()</code><span><a class="mark" href="#all_timers_timerspromisesscheduleryield" id="all_timers_timerspromisesscheduleryield">#</a></span><a aria-hidden="true" class="legacy" id="timers_timerspromises_scheduler_yield"></a></h4>
<div class="api_metadata">
<span>Added in: v17.3.0, v16.14.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<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>An experimental API defined by the <a href="https://github.com/WICG/scheduling-apis">Scheduling APIs</a> draft specification
being developed as a standard Web Platform API.</p>
<p>Calling <code>timersPromises.scheduler.yield()</code> is equivalent to calling
<code>timersPromises.setImmediate()</code> with no arguments.</p></section>
        </section>
<section><h2>TLS (SSL)<span><a class="mark" href="#all_tls_tls-ssl" id="all_tls_tls-ssl">#</a></span><a aria-hidden="true" class="legacy" id="tls_tls_ssl"></a></h2>

<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/tls.js">lib/tls.js</a></p>
<p>The <code>node: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"><span class="hljs-keyword">const</span> tls = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:tls'</span>);</code> <button class="copy-button">copy</button></pre>
<section><h3>Determining if crypto support is unavailable<span><a class="mark" href="#all_tls_determining-if-crypto-support-is-unavailable" id="all_tls_determining-if-crypto-support-is-unavailable">#</a></span><a aria-hidden="true" class="legacy" id="tls_determining_if_crypto_support_is_unavailable"></a></h3>
<p>It is possible for Node.js to be built without including support for the
<code>node:crypto</code> module. In such cases, attempting to <code>import</code> from <code>tls</code> or
calling <code>require('node:tls')</code> will result in an error being thrown.</p>
<p>When using CommonJS, the error thrown can be caught using try/catch:</p>
<pre><code class="language-js cjs"><span class="hljs-keyword">let</span> tls;
<span class="hljs-keyword">try</span> {
  tls = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:tls'</span>);
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'tls support is disabled!'</span>);
}</code> <button class="copy-button">copy</button></pre>
<p>When using the lexical ESM <code>import</code> keyword, the error can only be
caught if a handler for <code>process.on('uncaughtException')</code> is registered
<em>before</em> any attempt to load the module is made (using, for instance,
a preload module).</p>
<p>When using ESM, if there is a chance that the code may be run on a build
of Node.js where crypto support is not enabled, consider using the
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import"><code>import()</code></a> function instead of the lexical <code>import</code> keyword:</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">let</span> tls;
<span class="hljs-keyword">try</span> {
  tls = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'node:tls'</span>);
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'tls support is disabled!'</span>);
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3>TLS/SSL concepts<span><a class="mark" href="#all_tls_tlsssl-concepts" id="all_tls_tlsssl-concepts">#</a></span><a aria-hidden="true" class="legacy" id="tls_tls_ssl_concepts"></a></h3>
<p>TLS/SSL is a set of protocols that rely on a public key infrastructure (PKI) to
enable secure communication between a client and a server. For most common
cases, each server must have a private key.</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> <button class="copy-button">copy</button></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> <button class="copy-button">copy</button></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 -<span class="hljs-keyword">in</span> ryans-csr.pem -signkey ryans-key.pem -out ryans-cert.pem</code> <button class="copy-button">copy</button></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 -<span class="hljs-built_in">export</span> -<span class="hljs-keyword">in</span> ryans-cert.pem -inkey ryans-key.pem \
      -certfile ca-cert.pem -out ryans.pfx</code> <button class="copy-button">copy</button></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>
<h4>Perfect forward secrecy<span><a class="mark" href="#all_tls_perfect-forward-secrecy" id="all_tls_perfect-forward-secrecy">#</a></span><a aria-hidden="true" class="legacy" id="tls_perfect_forward_secrecy"></a></h4>

<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/Elliptic_curve_Diffie%E2%80%93Hellman">ECDHE</a>: An ephemeral version of the Elliptic Curve Diffie-Hellman
key-agreement protocol.</li>
<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>
</ul>
<p>Perfect forward secrecy using ECDHE is enabled by default. The <code>ecdhCurve</code>
option can be used when creating a TLS server to customize the list of supported
ECDH curves to use. See <a href="#all_tls_tlscreateserveroptions-secureconnectionlistener"><code>tls.createServer()</code></a> for more info.</p>
<p>DHE is disabled by default but can be enabled alongside ECDHE by setting the
<code>dhparam</code> option to <code>'auto'</code>. Custom DHE parameters are also supported but
discouraged in favor of automatically selected, well-known parameters.</p>
<p>Perfect forward secrecy was optional up to TLSv1.2. As of TLSv1.3, (EC)DHE is
always used (with the exception of PSK-only connections).</p>
<h4>ALPN and SNI<span><a class="mark" href="#all_tls_alpn-and-sni" id="all_tls_alpn-and-sni">#</a></span><a aria-hidden="true" class="legacy" id="tls_alpn_and_sni"></a></h4>

<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
certificates.</li>
</ul>
<h4>Pre-shared keys<span><a class="mark" href="#all_tls_pre-shared-keys" id="all_tls_pre-shared-keys">#</a></span><a aria-hidden="true" class="legacy" id="tls_pre_shared_keys"></a></h4>

<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 the public key
infrastructure (PKI) 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 and can be retrieved via
<code>openssl ciphers -v -s -tls1_3 -psk</code>.
On the client connection, a custom <code>checkServerIdentity</code> should be passed
because the default one will fail in the absence of a certificate.</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>
<p>To use TLS-PSK, client and server must specify the <code>pskCallback</code> option,
a function that returns the PSK to use (which must be compatible with
the selected cipher's digest).</p>
<p>It will be called first on the client:</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 the 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>.</li>
</ul>
<p>Then on the server:</p>
<ul>
<li>socket: <a href="#all_tls_class-tlstlssocket" class="type">&#x3C;tls.TLSSocket></a> the server socket instance, equivalent to <code>this</code>.</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="#all_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 PSK (or <code>null</code>).</li>
</ul>
<p>A return value of <code>null</code> stops the negotiation process and sends an
<code>unknown_psk_identity</code> alert message 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 <code>decrypt_error</code> before negotiation is finished.</p>
<h4>Client-initiated renegotiation attack mitigation<span><a class="mark" href="#all_tls_client-initiated-renegotiation-attack-mitigation" id="all_tls_client-initiated-renegotiation-attack-mitigation">#</a></span><a aria-hidden="true" class="legacy" id="tls_client_initiated_renegotiation_attack_mitigation"></a></h4>

<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="#all_tls_class-tlstlssocket"><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>
<h4>Session resumption<span><a class="mark" href="#all_tls_session-resumption" id="all_tls_session-resumption">#</a></span><a aria-hidden="true" class="legacy" id="tls_session_resumption"></a></h4>
<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>
<h5>Session identifiers<span><a class="mark" href="#all_tls_session-identifiers" id="all_tls_session-identifiers">#</a></span><a aria-hidden="true" class="legacy" id="tls_session_identifiers"></a></h5>
<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="#all_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="#all_tls_tlsconnectoptions-callback"><code>tls.connect()</code></a>
to reuse the session. Servers must
implement handlers for the <a href="#all_tls_event-newsession"><code>'newSession'</code></a> and <a href="#all_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>
<h5>Session tickets<span><a class="mark" href="#all_tls_session-tickets" id="all_tls_session-tickets">#</a></span><a aria-hidden="true" class="legacy" id="tls_session_tickets"></a></h5>
<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 a 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="#all_tls_tlssocketgettlsticket"><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="#all_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>It's possible to get the ticket keys by calling <a href="#all_tls_servergetticketkeys"><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="#all_tls_tlscreateserveroptions-secureconnectionlistener"><code>tls.createServer()</code></a>. The keys should be regularly
regenerated and server's keys can be reset with
<a href="#all_tls_serversetticketkeyskeys"><code>server.setTicketKeys()</code></a>.</p>
<p>Session ticket keys are cryptographic keys, and they <em><strong>must be stored
securely</strong></em>. 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('node: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="#all_tls_tlscreateserveroptions-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-bash">openssl s_client -connect localhost:443 -reconnect</code> <button class="copy-button">copy</button></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> <button class="copy-button">copy</button></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> <button class="copy-button">copy</button></pre>
</section><section><h3>Modifying the default TLS cipher suite<span><a class="mark" href="#all_tls_modifying-the-default-tls-cipher-suite" id="all_tls_modifying-the-default-tls-cipher-suite">#</a></span><a aria-hidden="true" class="legacy" id="tls_modifying_the_default_tls_cipher_suite"></a></h3>
<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> <button class="copy-button">copy</button></pre>
<p>This default can be replaced entirely using the <a href="#all_cli_--tls-cipher-listlist"><code>--tls-cipher-list</code></a>
command-line switch (directly, or via the <a href="#all_cli_node_optionsoptions"><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=<span class="hljs-string">'ECDHE-RSA-AES128-GCM-SHA256:!RC4'</span> server.js

<span class="hljs-built_in">export</span> NODE_OPTIONS=--tls-cipher-list=<span class="hljs-string">'ECDHE-RSA-AES128-GCM-SHA256:!RC4'</span>
node server.js</code> <button class="copy-button">copy</button></pre>
<p>To verify, use the following command to show the set cipher list, note the
difference between <code>defaultCoreCipherList</code> and <code>defaultCipherList</code>:</p>
<pre><code class="language-bash">node --tls-cipher-list=<span class="hljs-string">'ECDHE-RSA-AES128-GCM-SHA256:!RC4'</span> -p crypto.constants.defaultCipherList | <span class="hljs-built_in">tr</span> <span class="hljs-string">':'</span> <span class="hljs-string">'\n'</span>
ECDHE-RSA-AES128-GCM-SHA256
!RC4</code> <button class="copy-button">copy</button></pre>
<p>i.e. the <code>defaultCoreCipherList</code> list is set at compilation time and the
<code>defaultCipherList</code> is set at runtime.</p>
<p>To modify the default cipher suites from within the runtime, modify the
<code>tls.DEFAULT_CIPHERS</code> variable, this must be performed before listening on any
sockets, it will not affect sockets already opened. For example:</p>
<pre><code class="language-js"><span class="hljs-comment">// Remove Obsolete CBC Ciphers and RSA Key Exchange based Ciphers as they don't provide Forward Secrecy</span>
tls.<span class="hljs-property">DEFAULT_CIPHERS</span> +=
  <span class="hljs-string">':!ECDHE-RSA-AES128-SHA:!ECDHE-RSA-AES128-SHA256:!ECDHE-RSA-AES256-SHA:!ECDHE-RSA-AES256-SHA384'</span> +
  <span class="hljs-string">':!ECDHE-ECDSA-AES128-SHA:!ECDHE-ECDSA-AES128-SHA256:!ECDHE-ECDSA-AES256-SHA:!ECDHE-ECDSA-AES256-SHA384'</span> +
  <span class="hljs-string">':!kRSA'</span>;</code> <button class="copy-button">copy</button></pre>
<p>The default can also be replaced on a per client or server basis using the
<code>ciphers</code> option from <a href="#all_tls_tlscreatesecurecontextoptions"><code>tls.createSecureContext()</code></a>, which is also available
in <a href="#all_tls_tlscreateserveroptions-secureconnectionlistener"><code>tls.createServer()</code></a>, <a href="#all_tls_tlsconnectoptions-callback"><code>tls.connect()</code></a>, and when creating new
<a href="#all_tls_class-tlstlssocket"><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>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 five 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 three are enabled by default. The two <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>
</section><section><h3>X509 certificate error codes<span><a class="mark" href="#all_tls_x509-certificate-error-codes" id="all_tls_x509-certificate-error-codes">#</a></span><a aria-hidden="true" class="legacy" id="tls_x509_certificate_error_codes"></a></h3>
<p>Multiple functions can fail due to certificate errors that are reported by
OpenSSL. In such a case, the function provides an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type">&#x3C;Error></a> via its callback that
has the property <code>code</code> which can take one of the following values:</p>
<!--
values are taken from src/crypto/crypto_common.cc
description are taken from deps/openssl/openssl/crypto/x509/x509_txt.c
-->
<ul>
<li><code>'UNABLE_TO_GET_ISSUER_CERT'</code>: Unable to get issuer certificate.</li>
<li><code>'UNABLE_TO_GET_CRL'</code>: Unable to get certificate CRL.</li>
<li><code>'UNABLE_TO_DECRYPT_CERT_SIGNATURE'</code>: Unable to decrypt certificate's
signature.</li>
<li><code>'UNABLE_TO_DECRYPT_CRL_SIGNATURE'</code>: Unable to decrypt CRL's signature.</li>
<li><code>'UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY'</code>: Unable to decode issuer public key.</li>
<li><code>'CERT_SIGNATURE_FAILURE'</code>: Certificate signature failure.</li>
<li><code>'CRL_SIGNATURE_FAILURE'</code>: CRL signature failure.</li>
<li><code>'CERT_NOT_YET_VALID'</code>: Certificate is not yet valid.</li>
<li><code>'CERT_HAS_EXPIRED'</code>: Certificate has expired.</li>
<li><code>'CRL_NOT_YET_VALID'</code>: CRL is not yet valid.</li>
<li><code>'CRL_HAS_EXPIRED'</code>: CRL has expired.</li>
<li><code>'ERROR_IN_CERT_NOT_BEFORE_FIELD'</code>: Format error in certificate's notBefore
field.</li>
<li><code>'ERROR_IN_CERT_NOT_AFTER_FIELD'</code>: Format error in certificate's notAfter
field.</li>
<li><code>'ERROR_IN_CRL_LAST_UPDATE_FIELD'</code>: Format error in CRL's lastUpdate field.</li>
<li><code>'ERROR_IN_CRL_NEXT_UPDATE_FIELD'</code>: Format error in CRL's nextUpdate field.</li>
<li><code>'OUT_OF_MEM'</code>: Out of memory.</li>
<li><code>'DEPTH_ZERO_SELF_SIGNED_CERT'</code>: Self signed certificate.</li>
<li><code>'SELF_SIGNED_CERT_IN_CHAIN'</code>: Self signed certificate in certificate chain.</li>
<li><code>'UNABLE_TO_GET_ISSUER_CERT_LOCALLY'</code>: Unable to get local issuer certificate.</li>
<li><code>'UNABLE_TO_VERIFY_LEAF_SIGNATURE'</code>: Unable to verify the first certificate.</li>
<li><code>'CERT_CHAIN_TOO_LONG'</code>: Certificate chain too long.</li>
<li><code>'CERT_REVOKED'</code>: Certificate revoked.</li>
<li><code>'INVALID_CA'</code>: Invalid CA certificate.</li>
<li><code>'PATH_LENGTH_EXCEEDED'</code>: Path length constraint exceeded.</li>
<li><code>'INVALID_PURPOSE'</code>: Unsupported certificate purpose.</li>
<li><code>'CERT_UNTRUSTED'</code>: Certificate not trusted.</li>
<li><code>'CERT_REJECTED'</code>: Certificate rejected.</li>
<li><code>'HOSTNAME_MISMATCH'</code>: Hostname mismatch.</li>
</ul>
</section><section><h3>Class: <code>tls.CryptoStream</code><span><a class="mark" href="#all_tls_class-tlscryptostream" id="all_tls_class-tlscryptostream">#</a></span><a aria-hidden="true" class="legacy" id="tls_class_tls_cryptostream"></a></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="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_tls_class-tlstlssocket"><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="#all_tls_cryptostreambyteswritten" id="all_tls_cryptostreambyteswritten">#</a></span><a aria-hidden="true" class="legacy" id="tls_cryptostream_byteswritten"></a></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>
</section><section><h3>Class: <code>tls.SecurePair</code><span><a class="mark" href="#all_tls_class-tlssecurepair" id="all_tls_class-tlssecurepair">#</a></span><a aria-hidden="true" class="legacy" id="tls_class_tls_securepair"></a></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="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_tls_class-tlstlssocket"><code>tls.TLSSocket</code></a> instead.</div><p></p>
<p>Returned by <a href="#all_tls_tlscreatesecurepaircontext-isserver-requestcert-rejectunauthorized-options"><code>tls.createSecurePair()</code></a>.</p>
<h4>Event: <code>'secure'</code><span><a class="mark" href="#all_tls_event-secure" id="all_tls_event-secure">#</a></span><a aria-hidden="true" class="legacy" id="tls_event_secure"></a></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="#all_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>
</section><section><h3>Class: <code>tls.Server</code><span><a class="mark" href="#all_tls_class-tlsserver" id="all_tls_class-tlsserver">#</a></span><a aria-hidden="true" class="legacy" id="tls_class_tls_server"></a></h3>
<div class="api_metadata">
<span>Added in: v0.3.2</span>
</div>
<ul>
<li>Extends: <a href="#all_net_class-netserver" class="type">&#x3C;net.Server></a></li>
</ul>
<p>Accepts encrypted connections using TLS or SSL.</p>
<h4>Event: <code>'connection'</code><span><a class="mark" href="#all_tls_event-connection" id="all_tls_event-connection">#</a></span><a aria-hidden="true" class="legacy" id="tls_event_connection"></a></h4>
<div class="api_metadata">
<span>Added in: v0.3.2</span>
</div>
<ul>
<li><code>socket</code> <a href="#all_stream_class-streamduplex" class="type">&#x3C;stream.Duplex></a></li>
</ul>
<p>This event is emitted when a new TCP stream is established, before the TLS
handshake begins. <code>socket</code> is typically an object of type <a href="#all_net_class-netsocket"><code>net.Socket</code></a> but
will not receive events unlike the socket created from the <a href="#all_net_class-netserver"><code>net.Server</code></a>
<code>'connection'</code> event. Usually users will not want to access this event.</p>
<p>This event can also be explicitly emitted by users to inject connections
into the TLS server. In that case, any <a href="#all_stream_class-streamduplex"><code>Duplex</code></a> stream can be passed.</p>
<h4>Event: <code>'keylog'</code><span><a class="mark" href="#all_tls_event-keylog" id="all_tls_event-keylog">#</a></span><a aria-hidden="true" class="legacy" id="tls_event_keylog"></a></h4>
<div class="api_metadata">
<span>Added in: v12.3.0, v10.20.0</span>
</div>
<ul>
<li><code>line</code> <a href="#all_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="#all_tls_class-tlstlssocket" 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"><span class="hljs-keyword">const</span> logFile = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'/tmp/ssl-keys.log'</span>, { <span class="hljs-attr">flags</span>: <span class="hljs-string">'a'</span> });
<span class="hljs-comment">// ...</span>
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'keylog'</span>, <span class="hljs-function">(<span class="hljs-params">line, tlsSocket</span>) =></span> {
  <span class="hljs-keyword">if</span> (tlsSocket.<span class="hljs-property">remoteAddress</span> !== <span class="hljs-string">'...'</span>)
    <span class="hljs-keyword">return</span>; <span class="hljs-comment">// Only log keys for a particular IP</span>
  logFile.<span class="hljs-title function_">write</span>(line);
});</code> <button class="copy-button">copy</button></pre>
<h4>Event: <code>'newSession'</code><span><a class="mark" href="#all_tls_event-newsession" id="all_tls_event-newsession">#</a></span><a aria-hidden="true" class="legacy" id="tls_event_newsession"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v0.11.12</td>
<td><p>The <code>callback</code> argument is now supported.</p></td></tr>
<tr><td>v0.9.2</td>
<td><p><span>Added in: v0.9.2</span></p></td></tr>
</tbody></table>
</details>
</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="#all_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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> The TLS session identifier</li>
<li><code>sessionData</code> <a href="#all_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>
<h4>Event: <code>'OCSPRequest'</code><span><a class="mark" href="#all_tls_event-ocsprequest" id="all_tls_event-ocsprequest">#</a></span><a aria-hidden="true" class="legacy" id="tls_event_ocsprequest"></a></h4>
<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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> The server certificate</li>
<li><code>issuer</code> <a href="#all_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>
<h4>Event: <code>'resumeSession'</code><span><a class="mark" href="#all_tls_event-resumesession" id="all_tls_event-resumesession">#</a></span><a aria-hidden="true" class="legacy" id="tls_event_resumesession"></a></h4>
<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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> The TLS session identifier</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 to be called when the prior session
has been recovered: <code>callback([err[, sessionData]])</code>
<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="#all_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="#all_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"><span class="hljs-keyword">const</span> tlsSessionStore = {};
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'newSession'</span>, <span class="hljs-function">(<span class="hljs-params">id, data, cb</span>) =></span> {
  tlsSessionStore[id.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>)] = data;
  <span class="hljs-title function_">cb</span>();
});
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'resumeSession'</span>, <span class="hljs-function">(<span class="hljs-params">id, cb</span>) =></span> {
  <span class="hljs-title function_">cb</span>(<span class="hljs-literal">null</span>, tlsSessionStore[id.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'hex'</span>)] || <span class="hljs-literal">null</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4>Event: <code>'secureConnection'</code><span><a class="mark" href="#all_tls_event-secureconnection" id="all_tls_event-secureconnection">#</a></span><a aria-hidden="true" class="legacy" id="tls_event_secureconnection"></a></h4>
<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="#all_tls_class-tlstlssocket" 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 because the client or the
server did not send an ALPN extension, <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>
<h4>Event: <code>'tlsClientError'</code><span><a class="mark" href="#all_tls_event-tlsclienterror" id="all_tls_event-tlsclienterror">#</a></span><a aria-hidden="true" class="legacy" id="tls_event_tlsclienterror"></a></h4>
<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="#all_tls_class-tlstlssocket" class="type">&#x3C;tls.TLSSocket></a> The <code>tls.TLSSocket</code> instance from which the
error originated.</li>
</ul>
<h4><code>server.addContext(hostname, context)</code><span><a class="mark" href="#all_tls_serveraddcontexthostname-context" id="all_tls_serveraddcontexthostname-context">#</a></span><a aria-hidden="true" class="legacy" id="tls_server_addcontext_hostname_context"></a></h4>
<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> | <a href="#all_tls_tlscreatesecurecontextoptions" class="type">&#x3C;tls.SecureContext></a> An object containing any of the possible
properties from the <a href="#all_tls_tlscreatesecurecontextoptions"><code>tls.createSecureContext()</code></a> <code>options</code> arguments
(e.g. <code>key</code>, <code>cert</code>, <code>ca</code>, etc), or a TLS context object created with
<a href="#all_tls_tlscreatesecurecontextoptions"><code>tls.createSecureContext()</code></a> itself.</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>
<p>When there are multiple matching contexts, the most recently added one is
used.</p>
<h4><code>server.address()</code><span><a class="mark" href="#all_tls_serveraddress" id="all_tls_serveraddress">#</a></span><a aria-hidden="true" class="legacy" id="tls_server_address"></a></h4>
<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="#all_net_serveraddress"><code>net.Server.address()</code></a> for
more information.</p>
<h4><code>server.close([callback])</code><span><a class="mark" href="#all_tls_serverclosecallback" id="all_tls_serverclosecallback">#</a></span><a aria-hidden="true" class="legacy" id="tls_server_close_callback"></a></h4>
<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="#all_tls_class-tlsserver" 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>
<h4><code>server.getTicketKeys()</code><span><a class="mark" href="#all_tls_servergetticketkeys" id="all_tls_servergetticketkeys">#</a></span><a aria-hidden="true" class="legacy" id="tls_server_getticketkeys"></a></h4>
<div class="api_metadata">
<span>Added in: v3.0.0</span>
</div>
<ul>
<li>Returns: <a href="#all_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="#all_tls_session-resumption">Session Resumption</a> for more information.</p>
<h4><code>server.listen()</code><span><a class="mark" href="#all_tls_serverlisten" id="all_tls_serverlisten">#</a></span><a aria-hidden="true" class="legacy" id="tls_server_listen"></a></h4>
<p>Starts the server listening for encrypted connections.
This method is identical to <a href="#all_net_serverlisten"><code>server.listen()</code></a> from <a href="#all_net_class-netserver"><code>net.Server</code></a>.</p>
<h4><code>server.setSecureContext(options)</code><span><a class="mark" href="#all_tls_serversetsecurecontextoptions" id="all_tls_serversetsecurecontextoptions">#</a></span><a aria-hidden="true" class="legacy" id="tls_server_setsecurecontext_options"></a></h4>
<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="#all_tls_tlscreatesecurecontextoptions"><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>
<h4><code>server.setTicketKeys(keys)</code><span><a class="mark" href="#all_tls_serversetticketkeyskeys" id="all_tls_serversetticketkeyskeys">#</a></span><a aria-hidden="true" class="legacy" id="tls_server_setticketkeys_keys"></a></h4>
<div class="api_metadata">
<span>Added in: v3.0.0</span>
</div>
<ul>
<li><code>keys</code> <a href="#all_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 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="#all_tls_session-resumption">Session Resumption</a> for more information.</p>
</section><section><h3>Class: <code>tls.TLSSocket</code><span><a class="mark" href="#all_tls_class-tlstlssocket" id="all_tls_class-tlstlssocket">#</a></span><a aria-hidden="true" class="legacy" id="tls_class_tls_tlssocket"></a></h3>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div>
<ul>
<li>Extends: <a href="#all_net_class-netsocket" 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="#all_stream_stream">Stream</a> interface.</p>
<p>Methods that return TLS connection metadata (e.g.
<a href="#all_tls_tlssocketgetpeercertificatedetailed"><code>tls.TLSSocket.getPeerCertificate()</code></a>) will only return data while the
connection is open.</p>
<h4><code>new tls.TLSSocket(socket[, options])</code><span><a class="mark" href="#all_tls_new-tlstlssocketsocket-options" id="all_tls_new-tlstlssocketsocket-options">#</a></span><a aria-hidden="true" class="legacy" id="tls_new_tls_tlssocket_socket_options"></a></h4>
<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="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a> | <a href="#all_stream_class-streamduplex" class="type">&#x3C;stream.Duplex></a>
On the server side, any <code>Duplex</code> stream. On the client side, any
instance of <a href="#all_net_class-netsocket"><code>net.Socket</code></a> (for generic <code>Duplex</code> stream support
on the client side, <a href="#all_tls_tlsconnectoptions-callback"><code>tls.connect()</code></a> must be used).</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>enableTrace</code>: See <a href="#all_tls_tlscreateserveroptions-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="#all_net_class-netserver" class="type">&#x3C;net.Server></a> A <a href="#all_net_class-netserver"><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="#all_tls_tlscreateserveroptions-secureconnectionlistener"><code>tls.createServer()</code></a></li>
<li><code>ALPNProtocols</code>: See <a href="#all_tls_tlscreateserveroptions-secureconnectionlistener"><code>tls.createServer()</code></a></li>
<li><code>SNICallback</code>: See <a href="#all_tls_tlscreateserveroptions-secureconnectionlistener"><code>tls.createServer()</code></a></li>
<li><code>session</code> <a href="#all_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="#all_tls_tlscreatesecurecontextoptions"><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="#all_tls_tlscreatesecurecontextoptions"><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>
<h4>Event: <code>'keylog'</code><span><a class="mark" href="#all_tls_event-keylog_1" id="all_tls_event-keylog_1">#</a></span><a aria-hidden="true" class="legacy" id="tls_event_keylog_1"></a></h4>
<div class="api_metadata">
<span>Added in: v12.3.0, v10.20.0</span>
</div>
<ul>
<li><code>line</code> <a href="#all_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"><span class="hljs-keyword">const</span> logFile = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'/tmp/ssl-keys.log'</span>, { <span class="hljs-attr">flags</span>: <span class="hljs-string">'a'</span> });
<span class="hljs-comment">// ...</span>
tlsSocket.<span class="hljs-title function_">on</span>(<span class="hljs-string">'keylog'</span>, <span class="hljs-function">(<span class="hljs-params">line</span>) =></span> logFile.<span class="hljs-title function_">write</span>(line));</code> <button class="copy-button">copy</button></pre>
<h4>Event: <code>'OCSPResponse'</code><span><a class="mark" href="#all_tls_event-ocspresponse" id="all_tls_event-ocspresponse">#</a></span><a aria-hidden="true" class="legacy" id="tls_event_ocspresponse"></a></h4>
<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="#all_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>
<h4>Event: <code>'secureConnect'</code><span><a class="mark" href="#all_tls_event-secureconnect" id="all_tls_event-secureconnect">#</a></span><a aria-hidden="true" class="legacy" id="tls_event_secureconnect"></a></h4>
<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>
<p>The <code>'secureConnect'</code> event is not emitted when a <a href="#all_tls_class-tlstlssocket" class="type">&#x3C;tls.TLSSocket></a> is created
using the <code>new tls.TLSSocket()</code> constructor.</p>
<h4>Event: <code>'session'</code><span><a class="mark" href="#all_tls_event-session" id="all_tls_event-session">#</a></span><a aria-hidden="true" class="legacy" id="tls_event_session"></a></h4>
<div class="api_metadata">
<span>Added in: v11.10.0</span>
</div>
<ul>
<li><code>session</code> <a href="#all_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="#all_tls_tlsconnectoptions-callback"><code>tls.connect()</code></a> to resume the connection.</p>
<p>See <a href="#all_tls_session-resumption">Session Resumption</a> for more information.</p>
<p>For TLSv1.2 and below, <a href="#all_tls_tlssocketgetsession"><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.<span class="hljs-title function_">once</span>(<span class="hljs-string">'session'</span>, <span class="hljs-function">(<span class="hljs-params">session</span>) =></span> {
  <span class="hljs-comment">// The session can be used immediately or later.</span>
  tls.<span class="hljs-title function_">connect</span>({
    <span class="hljs-attr">session</span>: session,
    <span class="hljs-comment">// Other connect options...</span>
  });
});</code> <button class="copy-button">copy</button></pre>
<h4><code>tlsSocket.address()</code><span><a class="mark" href="#all_tls_tlssocketaddress" id="all_tls_tlssocketaddress">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_address"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.4.0</td>
<td><p>The <code>family</code> property now returns a string instead of a number.</p></td></tr>
<tr><td>v18.0.0</td>
<td><p>The <code>family</code> property now returns a number instead of a string.</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>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>
<h4><code>tlsSocket.authorizationError</code><span><a class="mark" href="#all_tls_tlssocketauthorizationerror" id="all_tls_tlssocketauthorizationerror">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_authorizationerror"></a></h4>
<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>
<h4><code>tlsSocket.authorized</code><span><a class="mark" href="#all_tls_tlssocketauthorized" id="all_tls_tlssocketauthorized">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_authorized"></a></h4>
<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#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>This property is <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>
<h4><code>tlsSocket.disableRenegotiation()</code><span><a class="mark" href="#all_tls_tlssocketdisablerenegotiation" id="all_tls_tlssocketdisablerenegotiation">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_disablerenegotiation"></a></h4>
<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>
<h4><code>tlsSocket.enableTrace()</code><span><a class="mark" href="#all_tls_tlssocketenabletrace" id="all_tls_tlssocketenabletrace">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_enabletrace"></a></h4>
<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>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>
<h4><code>tlsSocket.encrypted</code><span><a class="mark" href="#all_tls_tlssocketencrypted" id="all_tls_tlssocketencrypted">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_encrypted"></a></h4>
<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>
<h4><code>tlsSocket.exportKeyingMaterial(length, label[, context])</code><span><a class="mark" href="#all_tls_tlssocketexportkeyingmateriallength-label-context" id="all_tls_tlssocketexportkeyingmateriallength-label-context">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_exportkeyingmaterial_length_label_context"></a></h4>
<div class="api_metadata">
<span>Added in: v13.10.0, 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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> Optionally provide a context.</p>
</li>
<li>
<p>Returns: <a href="#all_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"><span class="hljs-keyword">const</span> keyingMaterial = tlsSocket.<span class="hljs-title function_">exportKeyingMaterial</span>(
  <span class="hljs-number">128</span>,
  <span class="hljs-string">'client finished'</span>);

<span class="hljs-comment">/*
 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>
*/</span></code> <button class="copy-button">copy</button></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>
<h4><code>tlsSocket.getCertificate()</code><span><a class="mark" href="#all_tls_tlssocketgetcertificate" id="all_tls_tlssocketgetcertificate">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_getcertificate"></a></h4>
<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="#all_tls_tlssocketgetpeercertificatedetailed"><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>
<h4><code>tlsSocket.getCipher()</code><span><a class="mark" href="#all_tls_tlssocketgetcipher" id="all_tls_tlssocketgetcipher">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_getcipher"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.4.0, 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>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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. For the actual negotiated protocol, see <a href="#all_tls_tlssocketgetprotocol"><code>tls.TLSSocket.getProtocol()</code></a>.</li>
</ul>
</li>
</ul>
<p>Returns an object containing information on the negotiated cipher suite.</p>
<p>For example, a TLSv1.2 protocol with AES256-SHA cipher:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"AES256-SHA"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"standardName"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"TLS_RSA_WITH_AES_256_CBC_SHA"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"version"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"SSLv3"</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></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>
<h4><code>tlsSocket.getEphemeralKeyInfo()</code><span><a class="mark" href="#all_tls_tlssocketgetephemeralkeyinfo" id="all_tls_tlssocketgetephemeralkeyinfo">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_getephemeralkeyinfo"></a></h4>
<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="#all_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>
<h4><code>tlsSocket.getFinished()</code><span><a class="mark" href="#all_tls_tlssocketgetfinished" id="all_tls_tlssocketgetfinished">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_getfinished"></a></h4>
<div class="api_metadata">
<span>Added in: v9.9.0</span>
</div>
<ul>
<li>Returns: <a href="#all_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>
<h4><code>tlsSocket.getPeerCertificate([detailed])</code><span><a class="mark" href="#all_tls_tlssocketgetpeercertificatedetailed" id="all_tls_tlssocketgetpeercertificatedetailed">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_getpeercertificate_detailed"></a></h4>
<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>
<h5>Certificate object<span><a class="mark" href="#all_tls_certificate-object" id="all_tls_certificate-object">#</a></span><a aria-hidden="true" class="legacy" id="tls_certificate_object"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.1.0, v18.13.0</td>
<td><p>Add "ca" property.</p></td></tr>
<tr><td>v17.2.0, v16.14.0</td>
<td><p>Add fingerprint512.</p></td></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>ca</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 a Certificate Authority (CA), <code>false</code> otherwise.</li>
<li><code>raw</code> <a href="#all_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>fingerprint512</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The SHA-512 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="#all_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="#all_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>
<!-- eslint-skip -->
<pre><code class="language-js">{ <span class="hljs-attr">subject</span>:
   { <span class="hljs-attr">OU</span>: [ <span class="hljs-string">'Domain Control Validated'</span>, <span class="hljs-string">'PositiveSSL Wildcard'</span> ],
     <span class="hljs-attr">CN</span>: <span class="hljs-string">'*.nodejs.org'</span> },
  <span class="hljs-attr">issuer</span>:
   { <span class="hljs-attr">C</span>: <span class="hljs-string">'GB'</span>,
     <span class="hljs-attr">ST</span>: <span class="hljs-string">'Greater Manchester'</span>,
     <span class="hljs-attr">L</span>: <span class="hljs-string">'Salford'</span>,
     <span class="hljs-attr">O</span>: <span class="hljs-string">'COMODO CA Limited'</span>,
     <span class="hljs-attr">CN</span>: <span class="hljs-string">'COMODO RSA Domain Validation Secure Server CA'</span> },
  <span class="hljs-attr">subjectaltname</span>: <span class="hljs-string">'DNS:*.nodejs.org, DNS:nodejs.org'</span>,
  <span class="hljs-attr">infoAccess</span>:
   { <span class="hljs-string">'CA Issuers - URI'</span>:
      [ <span class="hljs-string">'http://crt.comodoca.com/COMODORSADomainValidationSecureServerCA.crt'</span> ],
     <span class="hljs-string">'OCSP - URI'</span>: [ <span class="hljs-string">'http://ocsp.comodoca.com'</span> ] },
  <span class="hljs-attr">modulus</span>: <span class="hljs-string">'B56CE45CB740B09A13F64AC543B712FF9EE8E4C284B542A1708A27E82A8D151CA178153E12E6DDA15BF70FFD96CB8A88618641BDFCCA03527E665B70D779C8A349A6F88FD4EF6557180BD4C98192872BCFE3AF56E863C09DDD8BC1EC58DF9D94F914F0369102B2870BECFA1348A0838C9C49BD1C20124B442477572347047506B1FCD658A80D0C44BCC16BC5C5496CFE6E4A8428EF654CD3D8972BF6E5BFAD59C93006830B5EB1056BBB38B53D1464FA6E02BFDF2FF66CD949486F0775EC43034EC2602AEFBF1703AD221DAA2A88353C3B6A688EFE8387811F645CEED7B3FE46E1F8B9F59FAD028F349B9BC14211D5830994D055EEA3D547911E07A0ADDEB8A82B9188E58720D95CD478EEC9AF1F17BE8141BE80906F1A339445A7EB5B285F68039B0F294598A7D1C0005FC22B5271B0752F58CCDEF8C8FD856FB7AE21C80B8A2CE983AE94046E53EDE4CB89F42502D31B5360771C01C80155918637490550E3F555E2EE75CC8C636DDE3633CFEDD62E91BF0F7688273694EEEBA20C2FC9F14A2A435517BC1D7373922463409AB603295CEB0BB53787A334C9CA3CA8B30005C5A62FC0715083462E00719A8FA3ED0A9828C3871360A73F8B04A4FC1E71302844E9BB9940B77E745C9D91F226D71AFCAD4B113AAF68D92B24DDB4A2136B55A1CD1ADF39605B63CB639038ED0F4C987689866743A68769CC55847E4A06D6E2E3F1'</span>,
  <span class="hljs-attr">exponent</span>: <span class="hljs-string">'0x10001'</span>,
  <span class="hljs-attr">pubkey</span>: &#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',
  fingerprint512: '19:2B:3E:C3:B3:5B:32:E8:AE:BB:78:97:27:E4:BA:6C:39:C9:92:79:4F:31:46:39:E2:70:E5:5F:89:42:17:C9:E8:64:CA:FF:BB:72:56:73:6E:28:8A:92:7E:A3:2A:15:8B:C2:E0:45:CA:C3:BC:EA:40:52:EC:CA:A2:68:CB:32',
  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> <button class="copy-button">copy</button></pre>
<h4><code>tlsSocket.getPeerFinished()</code><span><a class="mark" href="#all_tls_tlssocketgetpeerfinished" id="all_tls_tlssocketgetpeerfinished">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_getpeerfinished"></a></h4>
<div class="api_metadata">
<span>Added in: v9.9.0</span>
</div>
<ul>
<li>Returns: <a href="#all_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>
<h4><code>tlsSocket.getPeerX509Certificate()</code><span><a class="mark" href="#all_tls_tlssocketgetpeerx509certificate" id="all_tls_tlssocketgetpeerx509certificate">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_getpeerx509certificate"></a></h4>
<div class="api_metadata">
<span>Added in: v15.9.0</span>
</div>
<ul>
<li>Returns: <a href="#all_crypto_class-x509certificate" class="type">&#x3C;X509Certificate></a></li>
</ul>
<p>Returns the peer certificate as an <a href="#all_crypto_class-x509certificate" class="type">&#x3C;X509Certificate></a> object.</p>
<p>If there is no peer certificate, or the socket has been destroyed,
<code>undefined</code> will be returned.</p>
<h4><code>tlsSocket.getProtocol()</code><span><a class="mark" href="#all_tls_tlssocketgetprotocol" id="all_tls_tlssocketgetprotocol">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_getprotocol"></a></h4>
<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>
<h4><code>tlsSocket.getSession()</code><span><a class="mark" href="#all_tls_tlssocketgetsession" id="all_tls_tlssocketgetsession">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_getsession"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div>
<ul>
<li><a href="#all_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="#all_tls_tlsconnectoptions-callback"><code>tls.connect()</code></a> to resume the connection. On the server, it may be useful
for debugging.</p>
<p>See <a href="#all_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="#all_tls_event-session"><code>'session'</code></a> event (it also works for TLSv1.2 and below).</p>
<h4><code>tlsSocket.getSharedSigalgs()</code><span><a class="mark" href="#all_tls_tlssocketgetsharedsigalgs" id="all_tls_tlssocketgetsharedsigalgs">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_getsharedsigalgs"></a></h4>
<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>
<h4><code>tlsSocket.getTLSTicket()</code><span><a class="mark" href="#all_tls_tlssocketgettlsticket" id="all_tls_tlssocketgettlsticket">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_gettlsticket"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div>
<ul>
<li><a href="#all_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="#all_tls_session-resumption">Session Resumption</a> for more information.</p>
<h4><code>tlsSocket.getX509Certificate()</code><span><a class="mark" href="#all_tls_tlssocketgetx509certificate" id="all_tls_tlssocketgetx509certificate">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_getx509certificate"></a></h4>
<div class="api_metadata">
<span>Added in: v15.9.0</span>
</div>
<ul>
<li>Returns: <a href="#all_crypto_class-x509certificate" class="type">&#x3C;X509Certificate></a></li>
</ul>
<p>Returns the local certificate as an <a href="#all_crypto_class-x509certificate" class="type">&#x3C;X509Certificate></a> object.</p>
<p>If there is no local certificate, or the socket has been destroyed,
<code>undefined</code> will be returned.</p>
<h4><code>tlsSocket.isSessionReused()</code><span><a class="mark" href="#all_tls_tlssocketissessionreused" id="all_tls_tlssocketissessionreused">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_issessionreused"></a></h4>
<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="#all_tls_session-resumption">Session Resumption</a> for more information.</p>
<h4><code>tlsSocket.localAddress</code><span><a class="mark" href="#all_tls_tlssocketlocaladdress" id="all_tls_tlssocketlocaladdress">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_localaddress"></a></h4>
<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>
<h4><code>tlsSocket.localPort</code><span><a class="mark" href="#all_tls_tlssocketlocalport" id="all_tls_tlssocketlocalport">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_localport"></a></h4>
<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;integer></a></li>
</ul>
<p>Returns the numeric representation of the local port.</p>
<h4><code>tlsSocket.remoteAddress</code><span><a class="mark" href="#all_tls_tlssocketremoteaddress" id="all_tls_tlssocketremoteaddress">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_remoteaddress"></a></h4>
<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>
<h4><code>tlsSocket.remoteFamily</code><span><a class="mark" href="#all_tls_tlssocketremotefamily" id="all_tls_tlssocketremotefamily">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_remotefamily"></a></h4>
<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>
<h4><code>tlsSocket.remotePort</code><span><a class="mark" href="#all_tls_tlssocketremoteport" id="all_tls_tlssocketremoteport">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_remoteport"></a></h4>
<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;integer></a></li>
</ul>
<p>Returns the numeric representation of the remote port. For example, <code>443</code>.</p>
<h4><code>tlsSocket.renegotiate(options, callback)</code><span><a class="mark" href="#all_tls_tlssocketrenegotiateoptions-callback" id="all_tls_tlssocketrenegotiateoptions-callback">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_renegotiate_options_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>callback</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</p></td></tr>
<tr><td>v0.11.8</td>
<td><p><span>Added in: v0.11.8</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>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>
<h4><code>tlsSocket.setKeyCert(context)</code><span><a class="mark" href="#all_tls_tlssocketsetkeycertcontext" id="all_tls_tlssocketsetkeycertcontext">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_setkeycert_context"></a></h4>
<div class="api_metadata">
<span>Added in: v20.17.0</span>
</div>
<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 href="#all_tls_tlscreatesecurecontextoptions" class="type">&#x3C;tls.SecureContext></a> An object containing at least <code>key</code> and
<code>cert</code> properties from the <a href="#all_tls_tlscreatesecurecontextoptions"><code>tls.createSecureContext()</code></a> <code>options</code>, or a
TLS context object created with <a href="#all_tls_tlscreatesecurecontextoptions"><code>tls.createSecureContext()</code></a> itself.</li>
</ul>
<p>The <code>tlsSocket.setKeyCert()</code> method sets the private key and certificate to use
for the socket. This is mainly useful if you wish to select a server certificate
from a TLS server's <code>ALPNCallback</code>.</p>
<h4><code>tlsSocket.setMaxSendFragment(size)</code><span><a class="mark" href="#all_tls_tlssocketsetmaxsendfragmentsize" id="all_tls_tlssocketsetmaxsendfragmentsize">#</a></span><a aria-hidden="true" class="legacy" id="tls_tlssocket_setmaxsendfragment_size"></a></h4>
<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>
</section><section><h3><code>tls.checkServerIdentity(hostname, cert)</code><span><a class="mark" href="#all_tls_tlscheckserveridentityhostname-cert" id="all_tls_tlscheckserveridentityhostname-cert">#</a></span><a aria-hidden="true" class="legacy" id="tls_tls_checkserveridentity_hostname_cert"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.3.1, v16.13.2, v14.18.3, v12.22.9</td>
<td><p>Support for <code>uniformResourceIdentifier</code> subject alternative names has been disabled in response to CVE-2021-44531.</p></td></tr>
<tr><td>v0.8.4</td>
<td><p><span>Added in: v0.8.4</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> 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="#all_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 is intended to be used in combination with the
<code>checkServerIdentity</code> option that can be passed to <a href="#all_tls_tlsconnectoptions-callback"><code>tls.connect()</code></a> and as
such operates on a <a href="#all_tls_certificate-object">certificate object</a>. For other purposes, consider using
<a href="#all_crypto_x509checkhostname-options"><code>x509.checkHost()</code></a> instead.</p>
<p>This function can be overwritten by providing an alternative function as the
<code>options.checkServerIdentity</code> option that is passed to <code>tls.connect()</code>. The
overwriting function can call <code>tls.checkServerIdentity()</code> of course, to augment
the checks done with additional verification.</p>
<p>This function is only called if the certificate passed all other checks, such as
being issued by trusted CA (<code>options.ca</code>).</p>
<p>Earlier versions of Node.js incorrectly accepted certificates for a given
<code>hostname</code> if a matching <code>uniformResourceIdentifier</code> subject alternative name
was present (see <a href="https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44531">CVE-2021-44531</a>). Applications that wish to accept
<code>uniformResourceIdentifier</code> subject alternative names can use a custom
<code>options.checkServerIdentity</code> function that implements the desired behavior.</p>
</section><section><h3><code>tls.connect(options[, callback])</code><span><a class="mark" href="#all_tls_tlsconnectoptions-callback" id="all_tls_tlsconnectoptions-callback">#</a></span><a aria-hidden="true" class="legacy" id="tls_tls_connect_options_callback"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.1.0, v14.18.0</td>
<td><p>Added <code>onread</code> option.</p></td></tr>
<tr><td>v14.1.0, v13.14.0</td>
<td><p>The <code>highWaterMark</code> option is accepted now.</p></td></tr>
<tr><td>v13.6.0, 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, v10.16.0</td>
<td><p>The <code>timeout</code> option is supported now.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>lookup</code> option is supported now.</p></td></tr>
<tr><td>v8.0.0</td>
<td><p>The <code>ALPNProtocols</code> option can be a <code>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>v5.3.0, v4.7.0</td>
<td><p>The <code>secureContext</code> option 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>
<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>
<ul>
<li><code>enableTrace</code>: See <a href="#all_tls_tlscreateserveroptions-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="#all_stream_class-streamduplex" 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="#all_net_class-netsocket"><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 set to <code>false</code>, then the socket will
automatically end the writable side when the readable side ends. If the
<code>socket</code> option is set, this option has no effect. See the <code>allowHalfOpen</code>
option of <a href="#all_net_class-netsocket"><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><code>pskCallback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> For TLS-PSK negotiation, see <a href="#all_tls_pre-shared-keys">Pre-shared keys</a>.</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="#all_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="#all_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, <code>TypedArray</code>s, or <code>DataView</code>s, or a
single <code>Buffer</code>, <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="#all_tls_tlscreateserveroptions-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="#all_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>highWaterMark</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Consistent with the readable stream <code>highWaterMark</code> parameter.
<strong>Default:</strong> <code>16 * 1024</code>.</li>
<li><code>secureContext</code>: TLS context object created with
<a href="#all_tls_tlscreatesecurecontextoptions"><code>tls.createSecureContext()</code></a>. If a <code>secureContext</code> is <em>not</em> provided, one
will be created by passing the entire <code>options</code> object to
<code>tls.createSecureContext()</code>.</li>
<li><code>onread</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> If the <code>socket</code> option is missing, incoming data is
stored in a single <code>buffer</code> and passed to the supplied <code>callback</code> when
data arrives on the socket, otherwise the option is ignored. See the
<code>onread</code> option of <a href="#all_net_class-netsocket"><code>net.Socket</code></a> for details.</li>
<li>...: <a href="#all_tls_tlscreatesecurecontextoptions"><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="#all_net_socketconnectoptions-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="#all_tls_class-tlstlssocket" 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="#all_tls_event-secureconnect"><code>'secureConnect'</code></a> event.</p>
<p><code>tls.connect()</code> returns a <a href="#all_tls_class-tlstlssocket"><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="#all_tls_tlscreateserveroptions-secureconnectionlistener"><code>tls.createServer()</code></a>:</p>
<pre><code class="language-js"><span class="hljs-comment">// Assumes an echo server that is listening on port 8000.</span>
<span class="hljs-keyword">const</span> tls = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:tls'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);

<span class="hljs-keyword">const</span> options = {
  <span class="hljs-comment">// Necessary only if the server requires client certificate authentication.</span>
  <span class="hljs-attr">key</span>: fs.<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'client-key.pem'</span>),
  <span class="hljs-attr">cert</span>: fs.<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'client-cert.pem'</span>),

  <span class="hljs-comment">// Necessary only if the server uses a self-signed certificate.</span>
  <span class="hljs-attr">ca</span>: [ fs.<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'server-cert.pem'</span>) ],

  <span class="hljs-comment">// Necessary only if the server's cert isn't for "localhost".</span>
  <span class="hljs-attr">checkServerIdentity</span>: <span class="hljs-function">() =></span> { <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>; },
};

<span class="hljs-keyword">const</span> socket = tls.<span class="hljs-title function_">connect</span>(<span class="hljs-number">8000</span>, options, <span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'client connected'</span>,
              socket.<span class="hljs-property">authorized</span> ? <span class="hljs-string">'authorized'</span> : <span class="hljs-string">'unauthorized'</span>);
  process.<span class="hljs-property">stdin</span>.<span class="hljs-title function_">pipe</span>(socket);
  process.<span class="hljs-property">stdin</span>.<span class="hljs-title function_">resume</span>();
});
socket.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>);
socket.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data);
});
socket.<span class="hljs-title function_">on</span>(<span class="hljs-string">'end'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'server ends connection'</span>);
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>tls.connect(path[, options][, callback])</code><span><a class="mark" href="#all_tls_tlsconnectpath-options-callback" id="all_tls_tlsconnectpath-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="tls_tls_connect_path_options_callback"></a></h3>
<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="#all_tls_tlsconnectoptions-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="#all_tls_tlsconnectoptions-callback"><code>tls.connect()</code></a>.</li>
<li>Returns: <a href="#all_tls_class-tlstlssocket" class="type">&#x3C;tls.TLSSocket></a></li>
</ul>
<p>Same as <a href="#all_tls_tlsconnectoptions-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>
</section><section><h3><code>tls.connect(port[, host][, options][, callback])</code><span><a class="mark" href="#all_tls_tlsconnectport-host-options-callback" id="all_tls_tlsconnectport-host-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="tls_tls_connect_port_host_options_callback"></a></h3>
<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="#all_tls_tlsconnectoptions-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="#all_tls_tlsconnectoptions-callback"><code>tls.connect()</code></a>.</li>
<li>Returns: <a href="#all_tls_class-tlstlssocket" class="type">&#x3C;tls.TLSSocket></a></li>
</ul>
<p>Same as <a href="#all_tls_tlsconnectoptions-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>
</section><section><h3><code>tls.createSecureContext([options])</code><span><a class="mark" href="#all_tls_tlscreatesecurecontextoptions" id="all_tls_tlscreatesecurecontextoptions">#</a></span><a aria-hidden="true" class="legacy" id="tls_tls_createsecurecontext_options"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.18.0</td>
<td><p>The <code>allowPartialTrustChain</code> option has been added.</p></td></tr>
<tr><td>v20.16.0</td>
<td><p>The <code>clientCertEngine</code>, <code>privateKeyEngine</code> and <code>privateKeyIdentifier</code> options depend on custom engine support in OpenSSL which is deprecated in OpenSSL 3.</p></td></tr>
<tr><td>v19.8.0, v18.16.0</td>
<td><p>The <code>dhparam</code> option can now be set to <code>'auto'</code> to enable DHE with appropriate well-known parameters.</p></td></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, v10.16.0</td>
<td><p>The <code>minVersion</code> and <code>maxVersion</code> can be used to restrict the allowed TLS protocol versions.</p></td></tr>
<tr><td>v10.0.0</td>
<td><p>The <code>ecdhCurve</code> cannot be set to <code>false</code> anymore due to a change in OpenSSL.</p></td></tr>
<tr><td>v9.3.0</td>
<td><p>The <code>options</code> parameter can now include <code>clientCertEngine</code>.</p></td></tr>
<tr><td>v9.0.0</td>
<td><p>The <code>ecdhCurve</code> option can now be multiple <code>':'</code> separated curve names or <code>'auto'</code>.</p></td></tr>
<tr><td>v7.3.0</td>
<td><p>If the <code>key</code> option is an array, individual entries do not need a <code>passphrase</code> property anymore. <code>Array</code> entries can also just be <code>string</code>s or <code>Buffer</code>s now.</p></td></tr>
<tr><td>v5.2.0</td>
<td><p>The <code>ca</code> option can now be a single string containing multiple CA certificates.</p></td></tr>
<tr><td>v0.11.13</td>
<td><p><span>Added in: v0.11.13</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>allowPartialTrustChain</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Treat intermediate (non-self-signed)
certificates in the trust CA certificate list as trusted.</li>
<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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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="#all_tls_tlsrootcertificates"><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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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="#all_tls_modifying-the-default-tls-cipher-suite">Modifying the default TLS cipher suite</a>. Permitted
ciphers can be obtained via <a href="#all_tls_tlsgetciphers"><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. <strong>Deprecated.</strong></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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> <code>'auto'</code> or custom Diffie-Hellman parameters,
required for non-ECDHE <a href="#all_tls_perfect-forward-secrecy">perfect forward secrecy</a>. If omitted or invalid,
the parameters are silently discarded and DHE ciphers will not be available.
<a href="https://en.wikipedia.org/wiki/Elliptic_curve_Diffie%E2%80%93Hellman">ECDHE</a>-based <a href="#all_tls_perfect-forward-secrecy">perfect forward secrecy</a> will still 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="#all_crypto_cryptogetcurves"><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="#all_tls_tlsdefault_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="#all_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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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>. <strong>Deprecated.</strong></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. <strong>Deprecated.</strong></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="#all_tls_tlsdefault_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. Avoid
setting to less than TLSv1.2, but it may be required for
interoperability.
<strong>Default:</strong> <a href="#all_tls_tlsdefault_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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> | <a href="#all_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="#all_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>
<li><code>ticketKeys</code>: <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> 48-bytes of cryptographically strong pseudorandom
data. See <a href="#all_tls_session-resumption">Session Resumption</a> for more information.</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="#all_tls_session-resumption">Session Resumption</a> for more information. <strong>Default:</strong> <code>300</code>.</li>
</ul>
</li>
</ul>
<p><a href="#all_tls_tlscreateserveroptions-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="#all_tls_tlscreateserveroptions-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="#all_tls_serveraddcontexthostname-context"><code>server.addContext()</code></a>,
but has no public methods. The <a href="#all_tls_class-tlsserver"><code>tls.Server</code></a> constructor and the
<a href="#all_tls_tlscreateserveroptions-secureconnectionlistener"><code>tls.createServer()</code></a> method do not support the <code>secureContext</code> option.</p>
<p>A key is <em>required</em> for ciphers that use 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>
<p>Custom DHE parameters are discouraged in favor of the new <code>dhparam: 'auto'</code>
option. When set to <code>'auto'</code>, well-known DHE parameters of sufficient strength
will be selected automatically. Otherwise, if necessary, <code>openssl dhparam</code> can
be used to create custom 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.</p>
</section><section><h3><code>tls.createSecurePair([context][, isServer][, requestCert][, rejectUnauthorized][, options])</code><span><a class="mark" href="#all_tls_tlscreatesecurepaircontext-isserver-requestcert-rejectunauthorized-options" id="all_tls_tlscreatesecurepaircontext-isserver-requestcert-rejectunauthorized-options">#</a></span><a aria-hidden="true" class="legacy" id="tls_tls_createsecurepair_context_isserver_requestcert_rejectunauthorized_options"></a></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="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_tls_class-tlstlssocket"><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><code>options</code>
<ul>
<li><code>enableTrace</code>: See <a href="#all_tls_tlscreateserveroptions-secureconnectionlistener"><code>tls.createServer()</code></a></li>
<li><code>secureContext</code>: A TLS context object from <a href="#all_tls_tlscreatesecurecontextoptions"><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="#all_net_class-netserver" class="type">&#x3C;net.Server></a> A <a href="#all_net_class-netserver"><code>net.Server</code></a> instance</li>
<li><code>requestCert</code>: See <a href="#all_tls_tlscreateserveroptions-secureconnectionlistener"><code>tls.createServer()</code></a></li>
<li><code>rejectUnauthorized</code>: See <a href="#all_tls_tlscreateserveroptions-secureconnectionlistener"><code>tls.createServer()</code></a></li>
<li><code>ALPNProtocols</code>: See <a href="#all_tls_tlscreateserveroptions-secureconnectionlistener"><code>tls.createServer()</code></a></li>
<li><code>SNICallback</code>: See <a href="#all_tls_tlscreateserveroptions-secureconnectionlistener"><code>tls.createServer()</code></a></li>
<li><code>session</code> <a href="#all_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="#all_tls_class-tlstlssocket"><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.<span class="hljs-title function_">createSecurePair</span>(<span class="hljs-comment">/* ... */</span>);
pair.<span class="hljs-property">encrypted</span>.<span class="hljs-title function_">pipe</span>(socket);
socket.<span class="hljs-title function_">pipe</span>(pair.<span class="hljs-property">encrypted</span>);</code> <button class="copy-button">copy</button></pre>
<p>can be replaced by:</p>
<pre><code class="language-js">secureSocket = tls.<span class="hljs-title class_">TLSSocket</span>(socket, options);</code> <button class="copy-button">copy</button></pre>
<p>where <code>secureSocket</code> has the same API as <code>pair.cleartext</code>.</p>
</section><section><h3><code>tls.createServer([options][, secureConnectionListener])</code><span><a class="mark" href="#all_tls_tlscreateserveroptions-secureconnectionlistener" id="all_tls_tlscreateserveroptions-secureconnectionlistener">#</a></span><a aria-hidden="true" class="legacy" id="tls_tls_createserver_options_secureconnectionlistener"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.16.0</td>
<td><p>The <code>clientCertEngine</code> option depends on custom engine support in OpenSSL which is deprecated in OpenSSL 3.</p></td></tr>
<tr><td>v19.0.0</td>
<td><p>If <code>ALPNProtocols</code> is set, incoming connections that send an ALPN extension with no supported protocols are terminated with a fatal <code>no_application_protocol</code> alert.</p></td></tr>
<tr><td>v20.4.0, v18.19.0</td>
<td><p>The <code>options</code> parameter can now include <code>ALPNCallback</code>.</p></td></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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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="#all_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="#all_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, <code>TypedArray</code>s, or <code>DataView</code>s, or a single
<code>Buffer</code>, <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>ALPNCallback</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> If set, this will be called when a
client opens a connection using the ALPN extension. One argument will
be passed to the callback: an object containing <code>servername</code> and
<code>protocols</code> fields, respectively containing the server name from
the SNI extension (if any) and an array of ALPN protocol name strings. The
callback must return either one of the strings listed in
<code>protocols</code>, which will be returned to the client as the selected
ALPN protocol, or <code>undefined</code>, to reject the connection with a fatal alert.
If a string is returned that does not match one of the client's ALPN
protocols, an error will be thrown. This option cannot be used with the
<code>ALPNProtocols</code> option, and setting both options will throw an error.</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. <strong>Deprecated.</strong></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="#all_tls_tlssocketenabletrace"><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="#all_tls_session-resumption">Session Resumption</a> for more information. <strong>Default:</strong> <code>300</code>.</li>
<li><code>SNICallback(servername, callback)</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>callback</code>. <code>callback</code> is an
error-first callback that takes two optional arguments: <code>error</code> and <code>ctx</code>.
<code>ctx</code>, if provided, is a <code>SecureContext</code> instance.
<a href="#all_tls_tlscreatesecurecontextoptions"><code>tls.createSecureContext()</code></a> can be used to get a proper <code>SecureContext</code>.
If <code>callback</code> is called with a falsy <code>ctx</code> argument, the default secure
context of the server will be used. 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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> 48-bytes of cryptographically strong pseudorandom
data. See <a href="#all_tls_session-resumption">Session Resumption</a> for more information.</li>
<li><code>pskCallback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> For TLS-PSK negotiation, see <a href="#all_tls_pre-shared-keys">Pre-shared keys</a>.</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="#all_tls_tlscreatesecurecontextoptions"><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="#all_net_netcreateserveroptions-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="#all_tls_class-tlsserver" class="type">&#x3C;tls.Server></a></li>
</ul>
<p>Creates a new <a href="#all_tls_class-tlsserver"><code>tls.Server</code></a>. The <code>secureConnectionListener</code>, if provided, is
automatically set as a listener for the <a href="#all_tls_event-secureconnection"><code>'secureConnection'</code></a> event.</p>
<p>The <code>ticketKeys</code> options is automatically shared between <code>node:cluster</code> module
workers.</p>
<p>The following illustrates a simple echo server:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> tls = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:tls'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);

<span class="hljs-keyword">const</span> options = {
  <span class="hljs-attr">key</span>: fs.<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'server-key.pem'</span>),
  <span class="hljs-attr">cert</span>: fs.<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'server-cert.pem'</span>),

  <span class="hljs-comment">// This is necessary only if using client certificate authentication.</span>
  <span class="hljs-attr">requestCert</span>: <span class="hljs-literal">true</span>,

  <span class="hljs-comment">// This is necessary only if the client uses a self-signed certificate.</span>
  <span class="hljs-attr">ca</span>: [ fs.<span class="hljs-title function_">readFileSync</span>(<span class="hljs-string">'client-cert.pem'</span>) ],
};

<span class="hljs-keyword">const</span> server = tls.<span class="hljs-title function_">createServer</span>(options, <span class="hljs-function">(<span class="hljs-params">socket</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'server connected'</span>,
              socket.<span class="hljs-property">authorized</span> ? <span class="hljs-string">'authorized'</span> : <span class="hljs-string">'unauthorized'</span>);
  socket.<span class="hljs-title function_">write</span>(<span class="hljs-string">'welcome!\n'</span>);
  socket.<span class="hljs-title function_">setEncoding</span>(<span class="hljs-string">'utf8'</span>);
  socket.<span class="hljs-title function_">pipe</span>(socket);
});
server.<span class="hljs-title function_">listen</span>(<span class="hljs-number">8000</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'server bound'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>The server can be tested by connecting to it using the example client from
<a href="#all_tls_tlsconnectoptions-callback"><code>tls.connect()</code></a>.</p>
</section><section><h3><code>tls.getCiphers()</code><span><a class="mark" href="#all_tls_tlsgetciphers" id="all_tls_tlsgetciphers">#</a></span><a aria-hidden="true" class="legacy" id="tls_tls_getciphers"></a></h3>
<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="#all_tls_tlscreatesecurecontextoptions"><code>tls.createSecureContext()</code></a>.</p>
<p>Not all supported ciphers are enabled by default. See
<a href="#all_tls_modifying-the-default-tls-cipher-suite">Modifying the default TLS cipher suite</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"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(tls.<span class="hljs-title function_">getCiphers</span>()); <span class="hljs-comment">// ['aes128-gcm-sha256', 'aes128-sha', ...]</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>tls.rootCertificates</code><span><a class="mark" href="#all_tls_tlsrootcertificates" id="all_tls_tlsrootcertificates">#</a></span><a aria-hidden="true" class="legacy" id="tls_tls_rootcertificates"></a></h3>
<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 the 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>
</section><section><h3><code>tls.DEFAULT_ECDH_CURVE</code><span><a class="mark" href="#all_tls_tlsdefault_ecdh_curve" id="all_tls_tlsdefault_ecdh_curve">#</a></span><a aria-hidden="true" class="legacy" id="tls_tls_default_ecdh_curve"></a></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>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="#all_tls_tlscreatesecurecontextoptions"><code>tls.createSecureContext()</code></a> for further
information.</p>
</section><section><h3><code>tls.DEFAULT_MAX_VERSION</code><span><a class="mark" href="#all_tls_tlsdefault_max_version" id="all_tls_tlsdefault_max_version">#</a></span><a aria-hidden="true" class="legacy" id="tls_tls_default_max_version"></a></h3>
<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="#all_tls_tlscreatesecurecontextoptions"><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>
</section><section><h3><code>tls.DEFAULT_MIN_VERSION</code><span><a class="mark" href="#all_tls_tlsdefault_min_version" id="all_tls_tlsdefault_min_version">#</a></span><a aria-hidden="true" class="legacy" id="tls_tls_default_min_version"></a></h3>
<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="#all_tls_tlscreatesecurecontextoptions"><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>
</section><section><h3><code>tls.DEFAULT_CIPHERS</code><span><a class="mark" href="#all_tls_tlsdefault_ciphers" id="all_tls_tlsdefault_ciphers">#</a></span><a aria-hidden="true" class="legacy" id="tls_tls_default_ciphers"></a></h3>
<div class="api_metadata">
<span>Added in: v19.8.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>ciphers</code> option of
<a href="#all_tls_tlscreatesecurecontextoptions"><code>tls.createSecureContext()</code></a>. It can be assigned any of the supported
OpenSSL ciphers.  Defaults to the content of
<code>crypto.constants.defaultCoreCipherList</code>, unless changed using CLI options
using <code>--tls-default-ciphers</code>.</li>
</ul></section>
        </section>
<section><h2>Trace events<span><a class="mark" href="#all_tracing_trace-events" id="all_tracing_trace-events">#</a></span><a aria-hidden="true" class="legacy" id="tracing_trace_events"></a></h2>

<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/trace_events.js">lib/trace_events.js</a></p>
<p>The <code>node: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>node: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.threadpoolwork.sync</code>: Enables capture of trace data for threadpool
synchronous operations, such as <code>blob</code>, <code>zlib</code>, <code>crypto</code> and <code>node_api</code>.</li>
<li><code>node.threadpoolwork.async</code>: Enables capture of trace data for threadpool
asynchronous operations, such as <code>blob</code>, <code>zlib</code>, <code>crypto</code> and <code>node_api</code>.</li>
<li><code>node.dns.native</code>: Enables capture of trace data for DNS queries.</li>
<li><code>node.net.native</code>: Enables capture of trace data for network.</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><code>node.fs_dir.sync</code>: Enables capture of trace data for file system sync
directory methods.</li>
<li><code>node.fs.async</code>: Enables capture of trace data for file system async methods.</li>
<li><code>node.fs_dir.async</code>: Enables capture of trace data for file system async
directory methods.</li>
<li><code>node.perf</code>: Enables capture of <a href="perf_hooks.html">Performance API</a> measurements.
<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>node: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>
<li><code>node.http</code>: Enables capture of trace data for http request / response.</li>
<li><code>node.module_timer</code>: Enables capture of trace data for CJS Module loading.</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> <button class="copy-button">copy</button></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

<span class="hljs-comment"># is equivalent to</span>

node --trace-event-categories v8,node,node.async_hooks</code> <button class="copy-button">copy</button></pre>
<p>Alternatively, trace events may be enabled using the <code>node:trace_events</code> module:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> trace_events = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:trace_events'</span>);
<span class="hljs-keyword">const</span> tracing = trace_events.<span class="hljs-title function_">createTracing</span>({ <span class="hljs-attr">categories</span>: [<span class="hljs-string">'node.perf'</span>] });
tracing.<span class="hljs-title function_">enable</span>();  <span class="hljs-comment">// Enable trace event capture for the 'node.perf' category</span>

<span class="hljs-comment">// do work</span>

tracing.<span class="hljs-title function_">disable</span>();  <span class="hljs-comment">// Disable trace event capture for the 'node.perf' category</span></code> <button class="copy-button">copy</button></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 <span class="hljs-string">'${pid}-${rotation}.log'</span> server.js</code> <button class="copy-button">copy</button></pre>
<p>To guarantee that the log file is properly generated after signal events like
<code>SIGINT</code>, <code>SIGTERM</code>, or <code>SIGBREAK</code>, make sure to have the appropriate handlers
in your code, such as:</p>
<pre><code class="language-js">process.<span class="hljs-title function_">on</span>(<span class="hljs-string">'SIGINT'</span>, <span class="hljs-keyword">function</span> <span class="hljs-title function_">onSigint</span>(<span class="hljs-params"></span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">info</span>(<span class="hljs-string">'Received SIGINT.'</span>);
  process.<span class="hljs-title function_">exit</span>(<span class="hljs-number">130</span>);  <span class="hljs-comment">// Or applicable exit code depending on OS and signal</span>
});</code> <button class="copy-button">copy</button></pre>
<p>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="#all_worker_threads_class-worker"><code>Worker</code></a> threads.</p>
<section><h3>The <code>node:trace_events</code> module<span><a class="mark" href="#all_tracing_the-nodetrace_events-module" id="all_tracing_the-nodetrace_events-module">#</a></span><a aria-hidden="true" class="legacy" id="tracing_the_node_trace_events_module"></a></h3>
<div class="api_metadata">
<span>Added in: v10.0.0</span>
</div>
<h4><code>Tracing</code> object<span><a class="mark" href="#all_tracing_tracing-object" id="all_tracing_tracing-object">#</a></span><a aria-hidden="true" class="legacy" id="tracing_tracing_object"></a></h4>
<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>
<h5><code>tracing.categories</code><span><a class="mark" href="#all_tracing_tracingcategories" id="all_tracing_tracingcategories">#</a></span><a aria-hidden="true" class="legacy" id="tracing_tracing_categories"></a></h5>
<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>
<h5><code>tracing.disable()</code><span><a class="mark" href="#all_tracing_tracingdisable" id="all_tracing_tracingdisable">#</a></span><a aria-hidden="true" class="legacy" id="tracing_tracing_disable"></a></h5>
<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"><span class="hljs-keyword">const</span> trace_events = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:trace_events'</span>);
<span class="hljs-keyword">const</span> t1 = trace_events.<span class="hljs-title function_">createTracing</span>({ <span class="hljs-attr">categories</span>: [<span class="hljs-string">'node'</span>, <span class="hljs-string">'v8'</span>] });
<span class="hljs-keyword">const</span> t2 = trace_events.<span class="hljs-title function_">createTracing</span>({ <span class="hljs-attr">categories</span>: [<span class="hljs-string">'node.perf'</span>, <span class="hljs-string">'node'</span>] });
t1.<span class="hljs-title function_">enable</span>();
t2.<span class="hljs-title function_">enable</span>();

<span class="hljs-comment">// Prints 'node,node.perf,v8'</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(trace_events.<span class="hljs-title function_">getEnabledCategories</span>());

t2.<span class="hljs-title function_">disable</span>(); <span class="hljs-comment">// Will only disable emission of the 'node.perf' category</span>

<span class="hljs-comment">// Prints 'node,v8'</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(trace_events.<span class="hljs-title function_">getEnabledCategories</span>());</code> <button class="copy-button">copy</button></pre>
<h5><code>tracing.enable()</code><span><a class="mark" href="#all_tracing_tracingenable" id="all_tracing_tracingenable">#</a></span><a aria-hidden="true" class="legacy" id="tracing_tracing_enable"></a></h5>
<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>
<h5><code>tracing.enabled</code><span><a class="mark" href="#all_tracing_tracingenabled" id="all_tracing_tracingenabled">#</a></span><a aria-hidden="true" class="legacy" id="tracing_tracing_enabled"></a></h5>
<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>
<h4><code>trace_events.createTracing(options)</code><span><a class="mark" href="#all_tracing_trace_eventscreatetracingoptions" id="all_tracing_trace_eventscreatetracingoptions">#</a></span><a aria-hidden="true" class="legacy" id="tracing_trace_events_createtracing_options"></a></h4>
<div class="api_metadata">
<span>Added in: v10.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>
<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="#all_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"><span class="hljs-keyword">const</span> trace_events = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:trace_events'</span>);
<span class="hljs-keyword">const</span> categories = [<span class="hljs-string">'node.perf'</span>, <span class="hljs-string">'node.async_hooks'</span>];
<span class="hljs-keyword">const</span> tracing = trace_events.<span class="hljs-title function_">createTracing</span>({ categories });
tracing.<span class="hljs-title function_">enable</span>();
<span class="hljs-comment">// do stuff</span>
tracing.<span class="hljs-title function_">disable</span>();</code> <button class="copy-button">copy</button></pre>
<h4><code>trace_events.getEnabledCategories()</code><span><a class="mark" href="#all_tracing_trace_eventsgetenabledcategories" id="all_tracing_trace_eventsgetenabledcategories">#</a></span><a aria-hidden="true" class="legacy" id="tracing_trace_events_getenabledcategories"></a></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/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"><span class="hljs-keyword">const</span> trace_events = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:trace_events'</span>);
<span class="hljs-keyword">const</span> t1 = trace_events.<span class="hljs-title function_">createTracing</span>({ <span class="hljs-attr">categories</span>: [<span class="hljs-string">'node.async_hooks'</span>] });
<span class="hljs-keyword">const</span> t2 = trace_events.<span class="hljs-title function_">createTracing</span>({ <span class="hljs-attr">categories</span>: [<span class="hljs-string">'node.perf'</span>] });
<span class="hljs-keyword">const</span> t3 = trace_events.<span class="hljs-title function_">createTracing</span>({ <span class="hljs-attr">categories</span>: [<span class="hljs-string">'v8'</span>] });

t1.<span class="hljs-title function_">enable</span>();
t2.<span class="hljs-title function_">enable</span>();

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(trace_events.<span class="hljs-title function_">getEnabledCategories</span>());</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Examples<span><a class="mark" href="#all_tracing_examples" id="all_tracing_examples">#</a></span><a aria-hidden="true" class="legacy" id="tracing_examples"></a></h3>
<h4>Collect trace events data by inspector<span><a class="mark" href="#all_tracing_collect-trace-events-data-by-inspector" id="all_tracing_collect-trace-events-data-by-inspector">#</a></span><a aria-hidden="true" class="legacy" id="tracing_collect_trace_events_data_by_inspector"></a></h4>
<pre><code class="language-js"><span class="hljs-meta">'use strict'</span>;

<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Session</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'inspector'</span>);
<span class="hljs-keyword">const</span> session = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Session</span>();
session.<span class="hljs-title function_">connect</span>();

<span class="hljs-keyword">function</span> <span class="hljs-title function_">post</span>(<span class="hljs-params">message, data</span>) {
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =></span> {
    session.<span class="hljs-title function_">post</span>(message, data, <span class="hljs-function">(<span class="hljs-params">err, result</span>) =></span> {
      <span class="hljs-keyword">if</span> (err)
        <span class="hljs-title function_">reject</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(err)));
      <span class="hljs-keyword">else</span>
        <span class="hljs-title function_">resolve</span>(result);
    });
  });
}

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">collect</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">const</span> data = [];
  session.<span class="hljs-title function_">on</span>(<span class="hljs-string">'NodeTracing.dataCollected'</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> data.<span class="hljs-title function_">push</span>(chunk));
  session.<span class="hljs-title function_">on</span>(<span class="hljs-string">'NodeTracing.tracingComplete'</span>, <span class="hljs-function">() =></span> {
    <span class="hljs-comment">// done</span>
  });
  <span class="hljs-keyword">const</span> traceConfig = { <span class="hljs-attr">includedCategories</span>: [<span class="hljs-string">'v8'</span>] };
  <span class="hljs-keyword">await</span> <span class="hljs-title function_">post</span>(<span class="hljs-string">'NodeTracing.start'</span>, { traceConfig });
  <span class="hljs-comment">// do something</span>
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
    <span class="hljs-title function_">post</span>(<span class="hljs-string">'NodeTracing.stop'</span>).<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> {
      session.<span class="hljs-title function_">disconnect</span>();
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data);
    });
  }, <span class="hljs-number">1000</span>);
}

<span class="hljs-title function_">collect</span>();</code> <button class="copy-button">copy</button></pre></section>
        </section>
<section><h2>TTY<span><a class="mark" href="#all_tty_tty" id="all_tty_tty">#</a></span><a aria-hidden="true" class="legacy" id="tty_tty"></a></h2>

<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/tty.js">lib/tty.js</a></p>
<p>The <code>node: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"><span class="hljs-keyword">const</span> tty = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:tty'</span>);</code> <button class="copy-button">copy</button></pre>
<p>When Node.js detects that it is being run with a text terminal ("TTY")
attached, <a href="#all_process_processstdin"><code>process.stdin</code></a> will, by default, be initialized as an instance of
<code>tty.ReadStream</code> and both <a href="#all_process_processstdout"><code>process.stdout</code></a> and <a href="#all_process_processstderr"><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"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node -p -e <span class="hljs-string">"Boolean(process.stdout.isTTY)"</span></span>
true
<span class="hljs-meta prompt_">$ </span><span class="language-bash">node -p -e <span class="hljs-string">"Boolean(process.stdout.isTTY)"</span> | <span class="hljs-built_in">cat</span></span>
false</code> <button class="copy-button">copy</button></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>
<section><h3>Class: <code>tty.ReadStream</code><span><a class="mark" href="#all_tty_class-ttyreadstream" id="all_tty_class-ttyreadstream">#</a></span><a aria-hidden="true" class="legacy" id="tty_class_tty_readstream"></a></h3>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<ul>
<li>Extends: <a href="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a></li>
</ul>
<p>Represents the readable side of a TTY. In normal circumstances
<a href="#all_process_processstdin"><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>
<h4><code>readStream.isRaw</code><span><a class="mark" href="#all_tty_readstreamisraw" id="all_tty_readstreamisraw">#</a></span><a aria-hidden="true" class="legacy" id="tty_readstream_israw"></a></h4>
<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.</p>
<p>This flag is always <code>false</code> when a process starts, even if the terminal is
operating in raw mode. Its value will change with subsequent calls to
<code>setRawMode</code>.</p>
<h4><code>readStream.isTTY</code><span><a class="mark" href="#all_tty_readstreamistty" id="all_tty_readstreamistty">#</a></span><a aria-hidden="true" class="legacy" id="tty_readstream_istty"></a></h4>
<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>
<h4><code>readStream.setRawMode(mode)</code><span><a class="mark" href="#all_tty_readstreamsetrawmodemode" id="all_tty_readstreamsetrawmodemode">#</a></span><a aria-hidden="true" class="legacy" id="tty_readstream_setrawmode_mode"></a></h4>
<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. <kbd>Ctrl</kbd>+<kbd>C</kbd> will no longer cause a <code>SIGINT</code> when
in this mode.</p>
</section><section><h3>Class: <code>tty.WriteStream</code><span><a class="mark" href="#all_tty_class-ttywritestream" id="all_tty_class-ttywritestream">#</a></span><a aria-hidden="true" class="legacy" id="tty_class_tty_writestream"></a></h3>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<ul>
<li>Extends: <a href="#all_net_class-netsocket" class="type">&#x3C;net.Socket></a></li>
</ul>
<p>Represents the writable side of a TTY. In normal circumstances,
<a href="#all_process_processstdout"><code>process.stdout</code></a> and <a href="#all_process_processstderr"><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>
<h4><code>new tty.ReadStream(fd[, options])</code><span><a class="mark" href="#all_tty_new-ttyreadstreamfd-options" id="all_tty_new-ttyreadstreamfd-options">#</a></span><a aria-hidden="true" class="legacy" id="tty_new_tty_readstream_fd_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v0.9.4</td>
<td><p>The <code>options</code> argument is supported.</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>fd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> A file descriptor associated with a TTY.</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 passed to parent <code>net.Socket</code>,
see <code>options</code> of <a href="#all_net_new-netsocketoptions"><code>net.Socket</code> constructor</a>.</li>
<li>Returns <a href="#all_tty_class-ttyreadstream" class="type">&#x3C;tty.ReadStream></a></li>
</ul>
<p>Creates a <code>ReadStream</code> for <code>fd</code> associated with a TTY.</p>
<h4><code>new tty.WriteStream(fd)</code><span><a class="mark" href="#all_tty_new-ttywritestreamfd" id="all_tty_new-ttywritestreamfd">#</a></span><a aria-hidden="true" class="legacy" id="tty_new_tty_writestream_fd"></a></h4>
<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 file descriptor associated with a TTY.</li>
<li>Returns <a href="#all_tty_class-ttywritestream" class="type">&#x3C;tty.WriteStream></a></li>
</ul>
<p>Creates a <code>WriteStream</code> for <code>fd</code> associated with a TTY.</p>
<h4>Event: <code>'resize'</code><span><a class="mark" href="#all_tty_event-resize" id="all_tty_event-resize">#</a></span><a aria-hidden="true" class="legacy" id="tty_event_resize"></a></h4>
<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.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'resize'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'screen size has changed!'</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`<span class="hljs-subst">${process.stdout.columns}</span>x<span class="hljs-subst">${process.stdout.rows}</span>`</span>);
});</code> <button class="copy-button">copy</button></pre>
<h4><code>writeStream.clearLine(dir[, callback])</code><span><a class="mark" href="#all_tty_writestreamclearlinedir-callback" id="all_tty_writestreamclearlinedir-callback">#</a></span><a aria-hidden="true" class="legacy" id="tty_writestream_clearline_dir_callback"></a></h4>
<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>dir</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a>
<ul>
<li><code>-1</code>: to the left from cursor</li>
<li><code>1</code>: to the right from cursor</li>
<li><code>0</code>: the entire line</li>
</ul>
</li>
<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>
<h4><code>writeStream.clearScreenDown([callback])</code><span><a class="mark" href="#all_tty_writestreamclearscreendowncallback" id="all_tty_writestreamclearscreendowncallback">#</a></span><a aria-hidden="true" class="legacy" id="tty_writestream_clearscreendown_callback"></a></h4>
<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>
<h4><code>writeStream.columns</code><span><a class="mark" href="#all_tty_writestreamcolumns" id="all_tty_writestreamcolumns">#</a></span><a aria-hidden="true" class="legacy" id="tty_writestream_columns"></a></h4>
<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>
<h4><code>writeStream.cursorTo(x[, y][, callback])</code><span><a class="mark" href="#all_tty_writestreamcursortox-y-callback" id="all_tty_writestreamcursortox-y-callback">#</a></span><a aria-hidden="true" class="legacy" id="tty_writestream_cursorto_x_y_callback"></a></h4>
<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>
<h4><code>writeStream.getColorDepth([env])</code><span><a class="mark" href="#all_tty_writestreamgetcolordepthenv" id="all_tty_writestreamgetcolordepthenv">#</a></span><a aria-hidden="true" class="legacy" id="tty_writestream_getcolordepth_env"></a></h4>
<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>
<h4><code>writeStream.getWindowSize()</code><span><a class="mark" href="#all_tty_writestreamgetwindowsize" id="all_tty_writestreamgetwindowsize">#</a></span><a aria-hidden="true" class="legacy" id="tty_writestream_getwindowsize"></a></h4>
<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 TTY
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 TTY.</p>
<h4><code>writeStream.hasColors([count][, env])</code><span><a class="mark" href="#all_tty_writestreamhascolorscount-env" id="all_tty_writestreamhascolorscount-env">#</a></span><a aria-hidden="true" class="legacy" id="tty_writestream_hascolors_count_env"></a></h4>
<div class="api_metadata">
<span>Added in: v11.13.0, v10.16.0</span>
</div>
<ul>
<li><code>count</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#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="#all_tty_writestreamgetcolordepthenv"><code>writeStream.getColorDepth()</code></a>.</p>
<pre><code class="language-js">process.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">hasColors</span>();
<span class="hljs-comment">// Returns true or false depending on if `stdout` supports at least 16 colors.</span>
process.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">hasColors</span>(<span class="hljs-number">256</span>);
<span class="hljs-comment">// Returns true or false depending on if `stdout` supports at least 256 colors.</span>
process.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">hasColors</span>({ <span class="hljs-attr">TMUX</span>: <span class="hljs-string">'1'</span> });
<span class="hljs-comment">// Returns true.</span>
process.<span class="hljs-property">stdout</span>.<span class="hljs-title function_">hasColors</span>(<span class="hljs-number">2</span> ** <span class="hljs-number">24</span>, { <span class="hljs-attr">TMUX</span>: <span class="hljs-string">'1'</span> });
<span class="hljs-comment">// Returns false (the environment setting pretends to support 2 ** 8 colors).</span></code> <button class="copy-button">copy</button></pre>
<h4><code>writeStream.isTTY</code><span><a class="mark" href="#all_tty_writestreamistty" id="all_tty_writestreamistty">#</a></span><a aria-hidden="true" class="legacy" id="tty_writestream_istty"></a></h4>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<p>A <code>boolean</code> that is always <code>true</code>.</p>
<h4><code>writeStream.moveCursor(dx, dy[, callback])</code><span><a class="mark" href="#all_tty_writestreammovecursordx-dy-callback" id="all_tty_writestreammovecursordx-dy-callback">#</a></span><a aria-hidden="true" class="legacy" id="tty_writestream_movecursor_dx_dy_callback"></a></h4>
<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>
<h4><code>writeStream.rows</code><span><a class="mark" href="#all_tty_writestreamrows" id="all_tty_writestreamrows">#</a></span><a aria-hidden="true" class="legacy" id="tty_writestream_rows"></a></h4>
<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>
</section><section><h3><code>tty.isatty(fd)</code><span><a class="mark" href="#all_tty_ttyisattyfd" id="all_tty_ttyisattyfd">#</a></span><a aria-hidden="true" class="legacy" id="tty_tty_isatty_fd"></a></h3>
<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></section>
        </section>
<section><h2>UDP/datagram sockets<span><a class="mark" href="#all_dgram_udpdatagram-sockets" id="all_dgram_udpdatagram-sockets">#</a></span><a aria-hidden="true" class="legacy" id="dgram_udp_datagram_sockets"></a></h2>

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

<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/dgram.js">lib/dgram.js</a></p>
<p>The <code>node:dgram</code> module provides an implementation of UDP datagram sockets.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> dgram <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dgram'</span>;

<span class="hljs-keyword">const</span> server = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>);

server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`server error:\n<span class="hljs-subst">${err.stack}</span>`</span>);
  server.<span class="hljs-title function_">close</span>();
});

server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg, rinfo</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`server got: <span class="hljs-subst">${msg}</span> from <span class="hljs-subst">${rinfo.address}</span>:<span class="hljs-subst">${rinfo.port}</span>`</span>);
});

server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'listening'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-keyword">const</span> address = server.<span class="hljs-title function_">address</span>();
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`server listening <span class="hljs-subst">${address.address}</span>:<span class="hljs-subst">${address.port}</span>`</span>);
});

server.<span class="hljs-title function_">bind</span>(<span class="hljs-number">41234</span>);
<span class="hljs-comment">// Prints: server listening 0.0.0.0:41234</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> dgram = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:dgram'</span>);
<span class="hljs-keyword">const</span> server = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>);

server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`server error:\n<span class="hljs-subst">${err.stack}</span>`</span>);
  server.<span class="hljs-title function_">close</span>();
});

server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg, rinfo</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`server got: <span class="hljs-subst">${msg}</span> from <span class="hljs-subst">${rinfo.address}</span>:<span class="hljs-subst">${rinfo.port}</span>`</span>);
});

server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'listening'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-keyword">const</span> address = server.<span class="hljs-title function_">address</span>();
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`server listening <span class="hljs-subst">${address.address}</span>:<span class="hljs-subst">${address.port}</span>`</span>);
});

server.<span class="hljs-title function_">bind</span>(<span class="hljs-number">41234</span>);
<span class="hljs-comment">// Prints: server listening 0.0.0.0:41234</span></code><button class="copy-button">copy</button></pre>
<section><h3>Class: <code>dgram.Socket</code><span><a class="mark" href="#all_dgram_class-dgramsocket" id="all_dgram_class-dgramsocket">#</a></span><a aria-hidden="true" class="legacy" id="dgram_class_dgram_socket"></a></h3>
<div class="api_metadata">
<span>Added in: v0.1.99</span>
</div>
<ul>
<li>Extends: <a href="#all_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="#all_dgram_dgramcreatesocketoptions-callback"><code>dgram.createSocket()</code></a>.
The <code>new</code> keyword is not to be used to create <code>dgram.Socket</code> instances.</p>
<h4>Event: <code>'close'</code><span><a class="mark" href="#all_dgram_event-close" id="all_dgram_event-close">#</a></span><a aria-hidden="true" class="legacy" id="dgram_event_close"></a></h4>
<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="#all_dgram_socketclosecallback"><code>close()</code></a>.
Once triggered, no new <code>'message'</code> events will be emitted on this socket.</p>
<h4>Event: <code>'connect'</code><span><a class="mark" href="#all_dgram_event-connect" id="all_dgram_event-connect">#</a></span><a aria-hidden="true" class="legacy" id="dgram_event_connect"></a></h4>
<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="#all_dgram_socketconnectport-address-callback"><code>connect()</code></a> call.</p>
<h4>Event: <code>'error'</code><span><a class="mark" href="#all_dgram_event-error" id="all_dgram_event-error">#</a></span><a aria-hidden="true" class="legacy" id="dgram_event_error"></a></h4>
<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>
<h4>Event: <code>'listening'</code><span><a class="mark" href="#all_dgram_event-listening" id="all_dgram_event-listening">#</a></span><a aria-hidden="true" class="legacy" id="dgram_event_listening"></a></h4>
<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>
<h4>Event: <code>'message'</code><span><a class="mark" href="#all_dgram_event-message" id="all_dgram_event-message">#</a></span><a aria-hidden="true" class="legacy" id="dgram_event_message"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.4.0</td>
<td><p>The <code>family</code> property now returns a string instead of a number.</p></td></tr>
<tr><td>v18.0.0</td>
<td><p>The <code>family</code> property now returns a number instead of a string.</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>
<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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> The message.</li>
<li><code>rinfo</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Remote address information.
<ul>
<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#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>
<p>If the source address of the incoming packet is an IPv6 link-local
address, the interface name is added to the <code>address</code>. For
example, a packet received on the <code>en0</code> interface might have the
address field set to <code>'fe80::2618:1234:ab11:3b9c%en0'</code>, where <code>'%en0'</code>
is the interface name as a zone ID suffix.</p>
<h4><code>socket.addMembership(multicastAddress[, multicastInterface])</code><span><a class="mark" href="#all_dgram_socketaddmembershipmulticastaddress-multicastinterface" id="all_dgram_socketaddmembershipmulticastaddress-multicastinterface">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_addmembership_multicastaddress_multicastinterface"></a></h4>
<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 called on an unbound socket, this method will implicitly bind to a random
port, listening on all interfaces.</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 class="with-40-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> cluster <span class="hljs-keyword">from</span> <span class="hljs-string">'node:cluster'</span>;
<span class="hljs-keyword">import</span> dgram <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dgram'</span>;

<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) {
  cluster.<span class="hljs-title function_">fork</span>(); <span class="hljs-comment">// Works ok.</span>
  cluster.<span class="hljs-title function_">fork</span>(); <span class="hljs-comment">// Fails with EADDRINUSE.</span>
} <span class="hljs-keyword">else</span> {
  <span class="hljs-keyword">const</span> s = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>);
  s.<span class="hljs-title function_">bind</span>(<span class="hljs-number">1234</span>, <span class="hljs-function">() =></span> {
    s.<span class="hljs-title function_">addMembership</span>(<span class="hljs-string">'224.0.0.114'</span>);
  });
}</code><code class="language-js cjs"><span class="hljs-keyword">const</span> cluster = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:cluster'</span>);
<span class="hljs-keyword">const</span> dgram = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:dgram'</span>);

<span class="hljs-keyword">if</span> (cluster.<span class="hljs-property">isPrimary</span>) {
  cluster.<span class="hljs-title function_">fork</span>(); <span class="hljs-comment">// Works ok.</span>
  cluster.<span class="hljs-title function_">fork</span>(); <span class="hljs-comment">// Fails with EADDRINUSE.</span>
} <span class="hljs-keyword">else</span> {
  <span class="hljs-keyword">const</span> s = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>);
  s.<span class="hljs-title function_">bind</span>(<span class="hljs-number">1234</span>, <span class="hljs-function">() =></span> {
    s.<span class="hljs-title function_">addMembership</span>(<span class="hljs-string">'224.0.0.114'</span>);
  });
}</code><button class="copy-button">copy</button></pre>
<h4><code>socket.addSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])</code><span><a class="mark" href="#all_dgram_socketaddsourcespecificmembershipsourceaddress-groupaddress-multicastinterface" id="all_dgram_socketaddsourcespecificmembershipsourceaddress-groupaddress-multicastinterface">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_addsourcespecificmembership_sourceaddress_groupaddress_multicastinterface"></a></h4>
<div class="api_metadata">
<span>Added in: v13.1.0, 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>
<p>When called on an unbound socket, this method will implicitly bind to a random
port, listening on all interfaces.</p>
<h4><code>socket.address()</code><span><a class="mark" href="#all_dgram_socketaddress" id="all_dgram_socketaddress">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_address"></a></h4>
<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>
<p>This method throws <code>EBADF</code> if called on an unbound socket.</p>
<h4><code>socket.bind([port][, address][, callback])</code><span><a class="mark" href="#all_dgram_socketbindport-address-callback" id="all_dgram_socketbindport-address-callback">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_bind_port_address_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v0.9.1</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="#all_errors_class-error"><code>Error</code></a> may be thrown.</p>
<p>Example of a UDP server listening on port 41234:</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> dgram <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dgram'</span>;

<span class="hljs-keyword">const</span> server = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>);

server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`server error:\n<span class="hljs-subst">${err.stack}</span>`</span>);
  server.<span class="hljs-title function_">close</span>();
});

server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg, rinfo</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`server got: <span class="hljs-subst">${msg}</span> from <span class="hljs-subst">${rinfo.address}</span>:<span class="hljs-subst">${rinfo.port}</span>`</span>);
});

server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'listening'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-keyword">const</span> address = server.<span class="hljs-title function_">address</span>();
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`server listening <span class="hljs-subst">${address.address}</span>:<span class="hljs-subst">${address.port}</span>`</span>);
});

server.<span class="hljs-title function_">bind</span>(<span class="hljs-number">41234</span>);
<span class="hljs-comment">// Prints: server listening 0.0.0.0:41234</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> dgram = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:dgram'</span>);
<span class="hljs-keyword">const</span> server = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>);

server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">`server error:\n<span class="hljs-subst">${err.stack}</span>`</span>);
  server.<span class="hljs-title function_">close</span>();
});

server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg, rinfo</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`server got: <span class="hljs-subst">${msg}</span> from <span class="hljs-subst">${rinfo.address}</span>:<span class="hljs-subst">${rinfo.port}</span>`</span>);
});

server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'listening'</span>, <span class="hljs-function">() =></span> {
  <span class="hljs-keyword">const</span> address = server.<span class="hljs-title function_">address</span>();
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`server listening <span class="hljs-subst">${address.address}</span>:<span class="hljs-subst">${address.port}</span>`</span>);
});

server.<span class="hljs-title function_">bind</span>(<span class="hljs-number">41234</span>);
<span class="hljs-comment">// Prints: server listening 0.0.0.0:41234</span></code><button class="copy-button">copy</button></pre>
<h4><code>socket.bind(options[, callback])</code><span><a class="mark" href="#all_dgram_socketbindoptions-callback" id="all_dgram_socketbindoptions-callback">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_bind_options_callback"></a></h4>
<div class="api_metadata">
<span>Added in: v0.11.14</span>
</div>
<ul>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Required. Supports the following properties:
<ul>
<li><code>port</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#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="#all_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.<span class="hljs-title function_">bind</span>({
  <span class="hljs-attr">address</span>: <span class="hljs-string">'localhost'</span>,
  <span class="hljs-attr">port</span>: <span class="hljs-number">8000</span>,
  <span class="hljs-attr">exclusive</span>: <span class="hljs-literal">true</span>,
});</code> <button class="copy-button">copy</button></pre>
<h4><code>socket.close([callback])</code><span><a class="mark" href="#all_dgram_socketclosecallback" id="all_dgram_socketclosecallback">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_close_callback"></a></h4>
<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="#all_dgram_event-close"><code>'close'</code></a> event.</p>
<h4><code>socket[Symbol.asyncDispose]()</code><span><a class="mark" href="#all_dgram_socketsymbolasyncdispose" id="all_dgram_socketsymbolasyncdispose">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_symbol_asyncdispose"></a></h4>
<div class="api_metadata">
<span>Added in: v20.5.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Calls <a href="#all_dgram_socketclosecallback"><code>socket.close()</code></a> and returns a promise that fulfills when the
socket has closed.</p>
<h4><code>socket.connect(port[, address][, callback])</code><span><a class="mark" href="#all_dgram_socketconnectport-address-callback" id="all_dgram_socketconnectport-address-callback">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_connect_port_address_callback"></a></h4>
<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="#all_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>
<h4><code>socket.disconnect()</code><span><a class="mark" href="#all_dgram_socketdisconnect" id="all_dgram_socketdisconnect">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_disconnect"></a></h4>
<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 unbound or already
disconnected socket will result in an <a href="#all_errors_err_socket_dgram_not_connected"><code>ERR_SOCKET_DGRAM_NOT_CONNECTED</code></a>
exception.</p>
<h4><code>socket.dropMembership(multicastAddress[, multicastInterface])</code><span><a class="mark" href="#all_dgram_socketdropmembershipmulticastaddress-multicastinterface" id="all_dgram_socketdropmembershipmulticastaddress-multicastinterface">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_dropmembership_multicastaddress_multicastinterface"></a></h4>
<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>
<h4><code>socket.dropSourceSpecificMembership(sourceAddress, groupAddress[, multicastInterface])</code><span><a class="mark" href="#all_dgram_socketdropsourcespecificmembershipsourceaddress-groupaddress-multicastinterface" id="all_dgram_socketdropsourcespecificmembershipsourceaddress-groupaddress-multicastinterface">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_dropsourcespecificmembership_sourceaddress_groupaddress_multicastinterface"></a></h4>
<div class="api_metadata">
<span>Added in: v13.1.0, 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>
<h4><code>socket.getRecvBufferSize()</code><span><a class="mark" href="#all_dgram_socketgetrecvbuffersize" id="all_dgram_socketgetrecvbuffersize">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_getrecvbuffersize"></a></h4>
<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>
<p>This method throws <a href="#all_errors_err_socket_buffer_size"><code>ERR_SOCKET_BUFFER_SIZE</code></a> if called on an unbound socket.</p>
<h4><code>socket.getSendBufferSize()</code><span><a class="mark" href="#all_dgram_socketgetsendbuffersize" id="all_dgram_socketgetsendbuffersize">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_getsendbuffersize"></a></h4>
<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>
<p>This method throws <a href="#all_errors_err_socket_buffer_size"><code>ERR_SOCKET_BUFFER_SIZE</code></a> if called on an unbound socket.</p>
<h4><code>socket.getSendQueueSize()</code><span><a class="mark" href="#all_dgram_socketgetsendqueuesize" id="all_dgram_socketgetsendqueuesize">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_getsendqueuesize"></a></h4>
<div class="api_metadata">
<span>Added in: v18.8.0, v16.19.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> Number of bytes queued for sending.</li>
</ul>
<h4><code>socket.getSendQueueCount()</code><span><a class="mark" href="#all_dgram_socketgetsendqueuecount" id="all_dgram_socketgetsendqueuecount">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_getsendqueuecount"></a></h4>
<div class="api_metadata">
<span>Added in: v18.8.0, v16.19.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> Number of send requests currently in the queue awaiting
to be processed.</li>
</ul>
<h4><code>socket.ref()</code><span><a class="mark" href="#all_dgram_socketref" id="all_dgram_socketref">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_ref"></a></h4>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div>
<ul>
<li>Returns: <a href="#all_dgram_class-dgramsocket" 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>
<h4><code>socket.remoteAddress()</code><span><a class="mark" href="#all_dgram_socketremoteaddress" id="all_dgram_socketremoteaddress">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_remoteaddress"></a></h4>
<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. This method throws an <a href="#all_errors_err_socket_dgram_not_connected"><code>ERR_SOCKET_DGRAM_NOT_CONNECTED</code></a> exception
if the socket is not connected.</p>
<h4><code>socket.send(msg[, offset, length][, port][, address][, callback])</code><span><a class="mark" href="#all_dgram_socketsendmsg-offset-length-port-address-callback" id="all_dgram_socketsendmsg-offset-length-port-address-callback">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_send_msg_offset_length_port_address_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.0.0</td>
<td><p>The <code>address</code> parameter now only accepts a <code>string</code>, <code>null</code> or <code>undefined</code>.</p></td></tr>
<tr><td>v14.5.0, v12.19.0</td>
<td><p>The <code>msg</code> parameter can now be any <code>TypedArray</code> or <code>DataView</code>.</p></td></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="#all_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#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>,
any <code>TypedArray</code> or a <code>DataView</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="#all_buffer_static-method-bufferbytelengthstring-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 nullish, <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>, a <code>TypedArray</code>,
or a <code>DataView</code>.</p>
<p>This method throws <a href="#all_errors_err_socket_bad_port"><code>ERR_SOCKET_BAD_PORT</code></a> if called on an unbound socket.</p>
<p>Example of sending a UDP packet to a port on <code>localhost</code>;</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> dgram <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dgram'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> message = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'Some bytes'</span>);
<span class="hljs-keyword">const</span> client = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>);
client.<span class="hljs-title function_">send</span>(message, <span class="hljs-number">41234</span>, <span class="hljs-string">'localhost'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  client.<span class="hljs-title function_">close</span>();
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> dgram = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:dgram'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> message = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'Some bytes'</span>);
<span class="hljs-keyword">const</span> client = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>);
client.<span class="hljs-title function_">send</span>(message, <span class="hljs-number">41234</span>, <span class="hljs-string">'localhost'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  client.<span class="hljs-title function_">close</span>();
});</code><button class="copy-button">copy</button></pre>
<p>Example of sending a UDP packet composed of multiple buffers to a port on
<code>127.0.0.1</code>;</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> dgram <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dgram'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'Some '</span>);
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'bytes'</span>);
<span class="hljs-keyword">const</span> client = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>);
client.<span class="hljs-title function_">send</span>([buf1, buf2], <span class="hljs-number">41234</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  client.<span class="hljs-title function_">close</span>();
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> dgram = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:dgram'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> buf1 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'Some '</span>);
<span class="hljs-keyword">const</span> buf2 = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'bytes'</span>);
<span class="hljs-keyword">const</span> client = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>);
client.<span class="hljs-title function_">send</span>([buf1, buf2], <span class="hljs-number">41234</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  client.<span class="hljs-title function_">close</span>();
});</code><button class="copy-button">copy</button></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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> dgram <span class="hljs-keyword">from</span> <span class="hljs-string">'node:dgram'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> message = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'Some bytes'</span>);
<span class="hljs-keyword">const</span> client = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>);
client.<span class="hljs-title function_">connect</span>(<span class="hljs-number">41234</span>, <span class="hljs-string">'localhost'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  client.<span class="hljs-title function_">send</span>(message, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
    client.<span class="hljs-title function_">close</span>();
  });
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> dgram = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:dgram'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> message = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'Some bytes'</span>);
<span class="hljs-keyword">const</span> client = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>);
client.<span class="hljs-title function_">connect</span>(<span class="hljs-number">41234</span>, <span class="hljs-string">'localhost'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  client.<span class="hljs-title function_">send</span>(message, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
    client.<span class="hljs-title function_">close</span>();
  });
});</code><button class="copy-button">copy</button></pre>
<h5>Note about UDP datagram size<span><a class="mark" href="#all_dgram_note-about-udp-datagram-size" id="all_dgram_note-about-udp-datagram-size">#</a></span><a aria-hidden="true" class="legacy" id="dgram_note_about_udp_datagram_size"></a></h5>
<p>The maximum size of an IPv4/v6 datagram depends on the <code>MTU</code>
(Maximum Transmission Unit) and on the <code>Payload Length</code> field size.</p>
<ul>
<li>
<p>The <code>Payload Length</code> field is 16 bits wide, which means that a normal
payload cannot exceed 64K octets including 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, IPv4 mandates a minimum <code>MTU</code> of 68
octets, while the recommended <code>MTU</code> for IPv4 is 576 (typically recommended
as the <code>MTU</code> for dial-up type applications), whether they arrive whole or in
fragments.</p>
<p>For IPv6, the minimum <code>MTU</code> is 1280 octets. However, the mandatory minimum
fragment reassembly buffer size is 1500 octets. The value of 68 octets is
very small, since most current link layer technologies, like Ethernet, have a
minimum <code>MTU</code> of 1500.</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>
<h4><code>socket.setBroadcast(flag)</code><span><a class="mark" href="#all_dgram_socketsetbroadcastflag" id="all_dgram_socketsetbroadcastflag">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_setbroadcast_flag"></a></h4>
<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>
<p>This method throws <code>EBADF</code> if called on an unbound socket.</p>
<h4><code>socket.setMulticastInterface(multicastInterface)</code><span><a class="mark" href="#all_dgram_socketsetmulticastinterfacemulticastinterface" id="all_dgram_socketsetmulticastinterfacemulticastinterface">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_setmulticastinterface_multicastinterface"></a></h4>
<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 Indexes</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>
<p>This method throws <code>EBADF</code> if called on an unbound socket.</p>
<h5>Example: IPv6 outgoing multicast interface<span><a class="mark" href="#all_dgram_example-ipv6-outgoing-multicast-interface" id="all_dgram_example-ipv6-outgoing-multicast-interface">#</a></span><a aria-hidden="true" class="legacy" id="dgram_example_ipv6_outgoing_multicast_interface"></a></h5>
<p>On most systems, where scope format uses the interface name:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> socket = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp6'</span>);

socket.<span class="hljs-title function_">bind</span>(<span class="hljs-number">1234</span>, <span class="hljs-function">() =></span> {
  socket.<span class="hljs-title function_">setMulticastInterface</span>(<span class="hljs-string">'::%eth1'</span>);
});</code> <button class="copy-button">copy</button></pre>
<p>On Windows, where scope format uses an interface number:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> socket = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp6'</span>);

socket.<span class="hljs-title function_">bind</span>(<span class="hljs-number">1234</span>, <span class="hljs-function">() =></span> {
  socket.<span class="hljs-title function_">setMulticastInterface</span>(<span class="hljs-string">'::%2'</span>);
});</code> <button class="copy-button">copy</button></pre>
<h5>Example: IPv4 outgoing multicast interface<span><a class="mark" href="#all_dgram_example-ipv4-outgoing-multicast-interface" id="all_dgram_example-ipv4-outgoing-multicast-interface">#</a></span><a aria-hidden="true" class="legacy" id="dgram_example_ipv4_outgoing_multicast_interface"></a></h5>
<p>All systems use an IP of the host on the desired physical interface:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> socket = dgram.<span class="hljs-title function_">createSocket</span>(<span class="hljs-string">'udp4'</span>);

socket.<span class="hljs-title function_">bind</span>(<span class="hljs-number">1234</span>, <span class="hljs-function">() =></span> {
  socket.<span class="hljs-title function_">setMulticastInterface</span>(<span class="hljs-string">'10.0.0.2'</span>);
});</code> <button class="copy-button">copy</button></pre>
<h5>Call results<span><a class="mark" href="#all_dgram_call-results" id="all_dgram_call-results">#</a></span><a aria-hidden="true" class="legacy" id="dgram_call_results"></a></h5>
<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="#all_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="#all_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="#all_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>
<h4><code>socket.setMulticastLoopback(flag)</code><span><a class="mark" href="#all_dgram_socketsetmulticastloopbackflag" id="all_dgram_socketsetmulticastloopbackflag">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_setmulticastloopback_flag"></a></h4>
<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>
<p>This method throws <code>EBADF</code> if called on an unbound socket.</p>
<h4><code>socket.setMulticastTTL(ttl)</code><span><a class="mark" href="#all_dgram_socketsetmulticastttlttl" id="all_dgram_socketsetmulticastttlttl">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_setmulticastttl_ttl"></a></h4>
<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>
<p>This method throws <code>EBADF</code> if called on an unbound socket.</p>
<h4><code>socket.setRecvBufferSize(size)</code><span><a class="mark" href="#all_dgram_socketsetrecvbuffersizesize" id="all_dgram_socketsetrecvbuffersizesize">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_setrecvbuffersize_size"></a></h4>
<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>
<p>This method throws <a href="#all_errors_err_socket_buffer_size"><code>ERR_SOCKET_BUFFER_SIZE</code></a> if called on an unbound socket.</p>
<h4><code>socket.setSendBufferSize(size)</code><span><a class="mark" href="#all_dgram_socketsetsendbuffersizesize" id="all_dgram_socketsetsendbuffersizesize">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_setsendbuffersize_size"></a></h4>
<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>
<p>This method throws <a href="#all_errors_err_socket_buffer_size"><code>ERR_SOCKET_BUFFER_SIZE</code></a> if called on an unbound socket.</p>
<h4><code>socket.setTTL(ttl)</code><span><a class="mark" href="#all_dgram_socketsetttlttl" id="all_dgram_socketsetttlttl">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_setttl_ttl"></a></h4>
<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 1 and 255. The default on most systems
is 64.</p>
<p>This method throws <code>EBADF</code> if called on an unbound socket.</p>
<h4><code>socket.unref()</code><span><a class="mark" href="#all_dgram_socketunref" id="all_dgram_socketunref">#</a></span><a aria-hidden="true" class="legacy" id="dgram_socket_unref"></a></h4>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div>
<ul>
<li>Returns: <a href="#all_dgram_class-dgramsocket" 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 additional effect.</p>
<p>The <code>socket.unref()</code> method returns a reference to the socket so calls can be
chained.</p>
</section><section><h3><code>node:dgram</code> module functions<span><a class="mark" href="#all_dgram_nodedgram-module-functions" id="all_dgram_nodedgram-module-functions">#</a></span><a aria-hidden="true" class="legacy" id="dgram_node_dgram_module_functions"></a></h3>
<h4><code>dgram.createSocket(options[, callback])</code><span><a class="mark" href="#all_dgram_dgramcreatesocketoptions-callback" id="all_dgram_dgramcreatesocketoptions-callback">#</a></span><a aria-hidden="true" class="legacy" id="dgram_dgram_createsocket_options_callback"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.8.0</td>
<td><p>AbortSignal support was added.</p></td></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><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:
<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="#all_dgram_socketbindport-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="#all_dns_dnslookuphostname-options-callback"><code>dns.lookup()</code></a>.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> An AbortSignal that may be used to close a socket.</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="#all_dgram_class-dgramsocket" class="type">&#x3C;dgram.Socket></a></li>
</ul>
<p>Creates a <code>dgram.Socket</code> object. Once the socket is created, calling
<a href="#all_dgram_socketbindport-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="#all_dgram_socketbindport-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="#all_dgram_socketaddress"><code>socket.address().address</code></a> and
<a href="#all_dgram_socketaddress"><code>socket.address().port</code></a>.</p>
<p>If the <code>signal</code> option is enabled, calling <code>.abort()</code> on the corresponding
<code>AbortController</code> is similar to calling <code>.close()</code> on the socket:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> controller = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AbortController</span>();
<span class="hljs-keyword">const</span> { signal } = controller;
<span class="hljs-keyword">const</span> server = dgram.<span class="hljs-title function_">createSocket</span>({ <span class="hljs-attr">type</span>: <span class="hljs-string">'udp4'</span>, signal });
server.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg, rinfo</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`server got: <span class="hljs-subst">${msg}</span> from <span class="hljs-subst">${rinfo.address}</span>:<span class="hljs-subst">${rinfo.port}</span>`</span>);
});
<span class="hljs-comment">// Later, when you want to close the server.</span>
controller.<span class="hljs-title function_">abort</span>();</code> <button class="copy-button">copy</button></pre>
<h4><code>dgram.createSocket(type[, callback])</code><span><a class="mark" href="#all_dgram_dgramcreatesockettype-callback" id="all_dgram_dgramcreatesockettype-callback">#</a></span><a aria-hidden="true" class="legacy" id="dgram_dgram_createsocket_type_callback"></a></h4>
<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="#all_dgram_class-dgramsocket" 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="#all_dgram_socketbindport-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="#all_dgram_socketbindport-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="#all_dgram_socketaddress"><code>socket.address().address</code></a> and <a href="#all_dgram_socketaddress"><code>socket.address().port</code></a>.</p></section>
        </section>
<section><h2>URL<span><a class="mark" href="#all_url_url" id="all_url_url">#</a></span><a aria-hidden="true" class="legacy" id="url_url"></a></h2>

<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/url.js">lib/url.js</a></p>
<p>The <code>node:url</code> module provides utilities for URL resolution and parsing. It can
be accessed using:</p>

<pre class="with-32-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> url <span class="hljs-keyword">from</span> <span class="hljs-string">'node:url'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> url = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);</code><button class="copy-button">copy</button></pre>
<section><h3>URL strings and URL objects<span><a class="mark" href="#all_url_url-strings-and-url-objects" id="all_url_url-strings-and-url-objects">#</a></span><a aria-hidden="true" class="legacy" id="url_url_strings_and_url_objects"></a></h3>
<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>node: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>'https://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> <button class="copy-button">copy</button></pre>
<p>Parsing the URL string using the WHATWG API:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> myURL =
  <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash'</span>);</code> <button class="copy-button">copy</button></pre>
<p>Parsing the URL string using the legacy API:</p>

<pre class="with-32-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> url <span class="hljs-keyword">from</span> <span class="hljs-string">'node:url'</span>;
<span class="hljs-keyword">const</span> myURL =
  url.<span class="hljs-title function_">parse</span>(<span class="hljs-string">'https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash'</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> url = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);
<span class="hljs-keyword">const</span> myURL =
  url.<span class="hljs-title function_">parse</span>(<span class="hljs-string">'https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash'</span>);</code><button class="copy-button">copy</button></pre>
<h4>Constructing a URL from component parts and getting the constructed string<span><a class="mark" href="#all_url_constructing-a-url-from-component-parts-and-getting-the-constructed-string" id="all_url_constructing-a-url-from-component-parts-and-getting-the-constructed-string">#</a></span><a aria-hidden="true" class="legacy" id="url_constructing_a_url_from_component_parts_and_getting_the_constructed_string"></a></h4>
<p>It is possible to construct a WHATWG URL from component parts using either the
property setters or a template literal string:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://example.org'</span>);
myURL.<span class="hljs-property">pathname</span> = <span class="hljs-string">'/a/b/c'</span>;
myURL.<span class="hljs-property">search</span> = <span class="hljs-string">'?d=e'</span>;
myURL.<span class="hljs-property">hash</span> = <span class="hljs-string">'#fgh'</span>;</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-js"><span class="hljs-keyword">const</span> pathname = <span class="hljs-string">'/a/b/c'</span>;
<span class="hljs-keyword">const</span> search = <span class="hljs-string">'?d=e'</span>;
<span class="hljs-keyword">const</span> hash = <span class="hljs-string">'#fgh'</span>;
<span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">`https://example.org<span class="hljs-subst">${pathname}</span><span class="hljs-subst">${search}</span><span class="hljs-subst">${hash}</span>`</span>);</code> <button class="copy-button">copy</button></pre>
<p>To get the constructed URL string, use the <code>href</code> property accessor:</p>
<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);</code> <button class="copy-button">copy</button></pre>
</section><section><h3>The WHATWG URL API<span><a class="mark" href="#all_url_the-whatwg-url-api" id="all_url_the-whatwg-url-api">#</a></span><a aria-hidden="true" class="legacy" id="url_the_whatwg_url_api"></a></h3>
<h4>Class: <code>URL</code><span><a class="mark" href="#all_url_class-url" id="all_url_class-url">#</a></span><a aria-hidden="true" class="legacy" id="url_class_url"></a></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>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="#all_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>
<h5><code>new URL(input[, base])</code><span><a class="mark" href="#all_url_new-urlinput-base" id="all_url_new-urlinput-base">#</a></span><a aria-hidden="true" class="legacy" id="url_new_url_input_base"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>ICU requirement is removed.</p></td></tr>
</tbody></table>
</details>
</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> 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. If <code>input</code> is not a string, it is <a href="https://tc39.es/ecma262/#sec-tostring">converted to a string</a> first.</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> The base URL to resolve against if the <code>input</code> is not
absolute. If <code>base</code> is not a string, it is <a href="https://tc39.es/ecma262/#sec-tostring">converted to a string</a> first.</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"><span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'/foo'</span>, <span class="hljs-string">'https://example.org/'</span>);
<span class="hljs-comment">// https://example.org/foo</span></code> <button class="copy-button">copy</button></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 class="with-63-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-variable constant_">URL</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:url'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-variable constant_">URL</span> === globalThis.<span class="hljs-property">URL</span>); <span class="hljs-comment">// Prints 'true'.</span></code><code class="language-js cjs"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-variable constant_">URL</span> === <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>).<span class="hljs-property">URL</span>); <span class="hljs-comment">// Prints 'true'.</span></code><button class="copy-button">copy</button></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"><span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>({ <span class="hljs-attr">toString</span>: <span class="hljs-function">() =></span> <span class="hljs-string">'https://example.org/'</span> });
<span class="hljs-comment">// https://example.org/</span></code> <button class="copy-button">copy</button></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"><span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://測試'</span>);
<span class="hljs-comment">// https://xn--g6w251d/</span></code> <button class="copy-button">copy</button></pre>
<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"><span class="hljs-keyword">let</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'http://Example.com/'</span>, <span class="hljs-string">'https://example.org/'</span>);
<span class="hljs-comment">// http://example.com/</span>

myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://Example.com/'</span>, <span class="hljs-string">'https://example.org/'</span>);
<span class="hljs-comment">// https://example.com/</span>

myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'foo://Example.com/'</span>, <span class="hljs-string">'https://example.org/'</span>);
<span class="hljs-comment">// foo://Example.com/</span>

myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'http:Example.com/'</span>, <span class="hljs-string">'https://example.org/'</span>);
<span class="hljs-comment">// http://example.com/</span>

myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https:Example.com/'</span>, <span class="hljs-string">'https://example.org/'</span>);
<span class="hljs-comment">// https://example.org/Example.com/</span>

myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'foo:Example.com/'</span>, <span class="hljs-string">'https://example.org/'</span>);
<span class="hljs-comment">// foo:Example.com/</span></code> <button class="copy-button">copy</button></pre>
<h5><code>url.hash</code><span><a class="mark" href="#all_url_urlhash" id="all_url_urlhash">#</a></span><a aria-hidden="true" class="legacy" id="url_url_hash"></a></h5>
<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"><span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://example.org/foo#bar'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">hash</span>);
<span class="hljs-comment">// Prints #bar</span>

myURL.<span class="hljs-property">hash</span> = <span class="hljs-string">'baz'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints https://example.org/foo#baz</span></code> <button class="copy-button">copy</button></pre>
<p>Invalid URL characters included in the value assigned to the <code>hash</code> property
are <a href="#all_url_percent-encoding-in-urls">percent-encoded</a>. The selection of which characters to
percent-encode may vary somewhat from what the <a href="#all_url_urlparseurlstring-parsequerystring-slashesdenotehost"><code>url.parse()</code></a> and
<a href="#all_url_urlformaturlobject"><code>url.format()</code></a> methods would produce.</p>
<h5><code>url.host</code><span><a class="mark" href="#all_url_urlhost" id="all_url_urlhost">#</a></span><a aria-hidden="true" class="legacy" id="url_url_host"></a></h5>
<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"><span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://example.org:81/foo'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">host</span>);
<span class="hljs-comment">// Prints example.org:81</span>

myURL.<span class="hljs-property">host</span> = <span class="hljs-string">'example.com:82'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints https://example.com:82/foo</span></code> <button class="copy-button">copy</button></pre>
<p>Invalid host values assigned to the <code>host</code> property are ignored.</p>
<h5><code>url.hostname</code><span><a class="mark" href="#all_url_urlhostname" id="all_url_urlhostname">#</a></span><a aria-hidden="true" class="legacy" id="url_url_hostname"></a></h5>
<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"><span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://example.org:81/foo'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">hostname</span>);
<span class="hljs-comment">// Prints example.org</span>

<span class="hljs-comment">// Setting the hostname does not change the port</span>
myURL.<span class="hljs-property">hostname</span> = <span class="hljs-string">'example.com'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints https://example.com:81/foo</span>

<span class="hljs-comment">// Use myURL.host to change the hostname and port</span>
myURL.<span class="hljs-property">host</span> = <span class="hljs-string">'example.org:82'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints https://example.org:82/foo</span></code> <button class="copy-button">copy</button></pre>
<p>Invalid host name values assigned to the <code>hostname</code> property are ignored.</p>
<h5><code>url.href</code><span><a class="mark" href="#all_url_urlhref" id="all_url_urlhref">#</a></span><a aria-hidden="true" class="legacy" id="url_url_href"></a></h5>
<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"><span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://example.org/foo'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints https://example.org/foo</span>

myURL.<span class="hljs-property">href</span> = <span class="hljs-string">'https://example.com/bar'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints https://example.com/bar</span></code> <button class="copy-button">copy</button></pre>
<p>Getting the value of the <code>href</code> property is equivalent to calling
<a href="#all_url_urltostring"><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="#all_url_new-urlinput-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>
<h5><code>url.origin</code><span><a class="mark" href="#all_url_urlorigin" id="all_url_urlorigin">#</a></span><a aria-hidden="true" class="legacy" id="url_url_origin"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>The scheme "gopher" is no longer special and <code>url.origin</code> now returns <code>'null'</code> for it.</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>Gets the read-only serialization of the URL's origin.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://example.org/foo/bar?baz'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">origin</span>);
<span class="hljs-comment">// Prints https://example.org</span></code> <button class="copy-button">copy</button></pre>
<pre><code class="language-js"><span class="hljs-keyword">const</span> idnURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://測試'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(idnURL.<span class="hljs-property">origin</span>);
<span class="hljs-comment">// Prints https://xn--g6w251d</span>

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(idnURL.<span class="hljs-property">hostname</span>);
<span class="hljs-comment">// Prints xn--g6w251d</span></code> <button class="copy-button">copy</button></pre>
<h5><code>url.password</code><span><a class="mark" href="#all_url_urlpassword" id="all_url_urlpassword">#</a></span><a aria-hidden="true" class="legacy" id="url_url_password"></a></h5>
<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"><span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://abc:xyz@example.com'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">password</span>);
<span class="hljs-comment">// Prints xyz</span>

myURL.<span class="hljs-property">password</span> = <span class="hljs-string">'123'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints https://abc:123@example.com/</span></code> <button class="copy-button">copy</button></pre>
<p>Invalid URL characters included in the value assigned to the <code>password</code> property
are <a href="#all_url_percent-encoding-in-urls">percent-encoded</a>. The selection of which characters to
percent-encode may vary somewhat from what the <a href="#all_url_urlparseurlstring-parsequerystring-slashesdenotehost"><code>url.parse()</code></a> and
<a href="#all_url_urlformaturlobject"><code>url.format()</code></a> methods would produce.</p>
<h5><code>url.pathname</code><span><a class="mark" href="#all_url_urlpathname" id="all_url_urlpathname">#</a></span><a aria-hidden="true" class="legacy" id="url_url_pathname"></a></h5>
<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"><span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://example.org/abc/xyz?123'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">pathname</span>);
<span class="hljs-comment">// Prints /abc/xyz</span>

myURL.<span class="hljs-property">pathname</span> = <span class="hljs-string">'/abcdef'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints https://example.org/abcdef?123</span></code> <button class="copy-button">copy</button></pre>
<p>Invalid URL characters included in the value assigned to the <code>pathname</code>
property are <a href="#all_url_percent-encoding-in-urls">percent-encoded</a>. The selection of which characters
to percent-encode may vary somewhat from what the <a href="#all_url_urlparseurlstring-parsequerystring-slashesdenotehost"><code>url.parse()</code></a> and
<a href="#all_url_urlformaturlobject"><code>url.format()</code></a> methods would produce.</p>
<h5><code>url.port</code><span><a class="mark" href="#all_url_urlport" id="all_url_urlport">#</a></span><a aria-hidden="true" class="legacy" id="url_url_port"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>The scheme "gopher" is no longer special.</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>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>"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"><span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://example.org:8888'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">port</span>);
<span class="hljs-comment">// Prints 8888</span>

<span class="hljs-comment">// Default ports are automatically transformed to the empty string</span>
<span class="hljs-comment">// (HTTPS protocol's default port is 443)</span>
myURL.<span class="hljs-property">port</span> = <span class="hljs-string">'443'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">port</span>);
<span class="hljs-comment">// Prints the empty string</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints https://example.org/</span>

myURL.<span class="hljs-property">port</span> = <span class="hljs-number">1234</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">port</span>);
<span class="hljs-comment">// Prints 1234</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints https://example.org:1234/</span>

<span class="hljs-comment">// Completely invalid port strings are ignored</span>
myURL.<span class="hljs-property">port</span> = <span class="hljs-string">'abcd'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">port</span>);
<span class="hljs-comment">// Prints 1234</span>

<span class="hljs-comment">// Leading numbers are treated as a port number</span>
myURL.<span class="hljs-property">port</span> = <span class="hljs-string">'5678abcd'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">port</span>);
<span class="hljs-comment">// Prints 5678</span>

<span class="hljs-comment">// Non-integers are truncated</span>
myURL.<span class="hljs-property">port</span> = <span class="hljs-number">1234.5678</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">port</span>);
<span class="hljs-comment">// Prints 1234</span>

<span class="hljs-comment">// Out-of-range numbers which are not represented in scientific notation</span>
<span class="hljs-comment">// will be ignored.</span>
myURL.<span class="hljs-property">port</span> = <span class="hljs-number">1e10</span>; <span class="hljs-comment">// 10000000000, will be range-checked as described below</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">port</span>);
<span class="hljs-comment">// Prints 1234</span></code> <button class="copy-button">copy</button></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.<span class="hljs-property">port</span> = <span class="hljs-number">4.567e21</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">port</span>);
<span class="hljs-comment">// Prints 4 (because it is the leading number in the string '4.567e21')</span></code> <button class="copy-button">copy</button></pre>
<h5><code>url.protocol</code><span><a class="mark" href="#all_url_urlprotocol" id="all_url_urlprotocol">#</a></span><a aria-hidden="true" class="legacy" id="url_url_protocol"></a></h5>
<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"><span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://example.org'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">protocol</span>);
<span class="hljs-comment">// Prints https:</span>

myURL.<span class="hljs-property">protocol</span> = <span class="hljs-string">'ftp'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints ftp://example.org/</span></code> <button class="copy-button">copy</button></pre>
<p>Invalid URL protocol values assigned to the <code>protocol</code> property are ignored.</p>
<h6>Special schemes<span><a class="mark" href="#all_url_special-schemes" id="all_url_special-schemes">#</a></span><a aria-hidden="true" class="legacy" id="url_special_schemes"></a></h6>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.0.0</td>
<td><p>The scheme "gopher" is no longer special.</p></td></tr>
</tbody></table>
</details>
</div>
<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"><span class="hljs-keyword">const</span> u = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'http://example.org'</span>);
u.<span class="hljs-property">protocol</span> = <span class="hljs-string">'https'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(u.<span class="hljs-property">href</span>);
<span class="hljs-comment">// https://example.org/</span></code> <button class="copy-button">copy</button></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"><span class="hljs-keyword">const</span> u = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'http://example.org'</span>);
u.<span class="hljs-property">protocol</span> = <span class="hljs-string">'fish'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(u.<span class="hljs-property">href</span>);
<span class="hljs-comment">// http://example.org/</span></code> <button class="copy-button">copy</button></pre>
<p>Likewise, changing from a non-special protocol to a special protocol is also
not permitted:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> u = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'fish://example.org'</span>);
u.<span class="hljs-property">protocol</span> = <span class="hljs-string">'http'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(u.<span class="hljs-property">href</span>);
<span class="hljs-comment">// fish://example.org</span></code> <button class="copy-button">copy</button></pre>
<p>According to the WHATWG URL Standard, special protocol schemes are <code>ftp</code>,
<code>file</code>, <code>http</code>, <code>https</code>, <code>ws</code>, and <code>wss</code>.</p>
<h5><code>url.search</code><span><a class="mark" href="#all_url_urlsearch" id="all_url_urlsearch">#</a></span><a aria-hidden="true" class="legacy" id="url_url_search"></a></h5>
<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"><span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://example.org/abc?123'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">search</span>);
<span class="hljs-comment">// Prints ?123</span>

myURL.<span class="hljs-property">search</span> = <span class="hljs-string">'abc=xyz'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints https://example.org/abc?abc=xyz</span></code> <button class="copy-button">copy</button></pre>
<p>Any invalid URL characters appearing in the value assigned the <code>search</code>
property will be <a href="#all_url_percent-encoding-in-urls">percent-encoded</a>. The selection of which
characters to percent-encode may vary somewhat from what the <a href="#all_url_urlparseurlstring-parsequerystring-slashesdenotehost"><code>url.parse()</code></a>
and <a href="#all_url_urlformaturlobject"><code>url.format()</code></a> methods would produce.</p>
<h5><code>url.searchParams</code><span><a class="mark" href="#all_url_urlsearchparams" id="all_url_urlsearchparams">#</a></span><a aria-hidden="true" class="legacy" id="url_url_searchparams"></a></h5>
<ul>
<li><a href="#all_url_class-urlsearchparams" class="type">&#x3C;URLSearchParams></a></li>
</ul>
<p>Gets the <a href="#all_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="#all_url_urlsearch"><code>url.search</code></a> setter. See
<a href="#all_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"><span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://example.org/abc?foo=~bar'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">search</span>);  <span class="hljs-comment">// prints ?foo=~bar</span>

<span class="hljs-comment">// Modify the URL via searchParams...</span>
myURL.<span class="hljs-property">searchParams</span>.<span class="hljs-title function_">sort</span>();

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">search</span>);  <span class="hljs-comment">// prints ?foo=%7Ebar</span></code> <button class="copy-button">copy</button></pre>
<h5><code>url.username</code><span><a class="mark" href="#all_url_urlusername" id="all_url_urlusername">#</a></span><a aria-hidden="true" class="legacy" id="url_url_username"></a></h5>
<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"><span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://abc:xyz@example.com'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">username</span>);
<span class="hljs-comment">// Prints abc</span>

myURL.<span class="hljs-property">username</span> = <span class="hljs-string">'123'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints https://123:xyz@example.com/</span></code> <button class="copy-button">copy</button></pre>
<p>Any invalid URL characters appearing in the value assigned the <code>username</code>
property will be <a href="#all_url_percent-encoding-in-urls">percent-encoded</a>. The selection of which
characters to percent-encode may vary somewhat from what the <a href="#all_url_urlparseurlstring-parsequerystring-slashesdenotehost"><code>url.parse()</code></a>
and <a href="#all_url_urlformaturlobject"><code>url.format()</code></a> methods would produce.</p>
<h5><code>url.toString()</code><span><a class="mark" href="#all_url_urltostring" id="all_url_urltostring">#</a></span><a aria-hidden="true" class="legacy" id="url_url_tostring"></a></h5>
<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="#all_url_urlhref"><code>url.href</code></a> and <a href="#all_url_urltojson"><code>url.toJSON()</code></a>.</p>
<h5><code>url.toJSON()</code><span><a class="mark" href="#all_url_urltojson" id="all_url_urltojson">#</a></span><a aria-hidden="true" class="legacy" id="url_url_tojson"></a></h5>
<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="#all_url_urlhref"><code>url.href</code></a> and
<a href="#all_url_urltostring"><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"><span class="hljs-keyword">const</span> myURLs = [
  <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://www.example.com'</span>),
  <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://test.example.org'</span>),
];
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(myURLs));
<span class="hljs-comment">// Prints ["https://www.example.com/","https://test.example.org/"]</span></code> <button class="copy-button">copy</button></pre>
<h5><code>URL.createObjectURL(blob)</code><span><a class="mark" href="#all_url_urlcreateobjecturlblob" id="all_url_urlcreateobjecturlblob">#</a></span><a aria-hidden="true" class="legacy" id="url_url_createobjecturl_blob"></a></h5>
<div class="api_metadata">
<span>Added in: v16.7.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>blob</code> <a href="#all_buffer_class-blob" class="type">&#x3C;Blob></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>Creates a <code>'blob:nodedata:...'</code> URL string that represents the given <a href="#all_buffer_class-blob" class="type">&#x3C;Blob></a>
object and can be used to retrieve the <code>Blob</code> later.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> {
  <span class="hljs-title class_">Blob</span>,
  resolveObjectURL,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> blob = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Blob</span>([<span class="hljs-string">'hello'</span>]);
<span class="hljs-keyword">const</span> id = <span class="hljs-variable constant_">URL</span>.<span class="hljs-title function_">createObjectURL</span>(blob);

<span class="hljs-comment">// later...</span>

<span class="hljs-keyword">const</span> otherBlob = <span class="hljs-title function_">resolveObjectURL</span>(id);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(otherBlob.<span class="hljs-property">size</span>);</code> <button class="copy-button">copy</button></pre>
<p>The data stored by the registered <a href="#all_buffer_class-blob" class="type">&#x3C;Blob></a> will be retained in memory until
<code>URL.revokeObjectURL()</code> is called to remove it.</p>
<p><code>Blob</code> objects are registered within the current thread. If using Worker
Threads, <code>Blob</code> objects registered within one Worker will not be available
to other workers or the main thread.</p>
<h5><code>URL.revokeObjectURL(id)</code><span><a class="mark" href="#all_url_urlrevokeobjecturlid" id="all_url_urlrevokeobjecturlid">#</a></span><a aria-hidden="true" class="legacy" id="url_url_revokeobjecturl_id"></a></h5>
<div class="api_metadata">
<span>Added in: v16.7.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<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 <code>'blob:nodedata:...</code> URL string returned by a prior call to
<code>URL.createObjectURL()</code>.</li>
</ul>
<p>Removes the stored <a href="#all_buffer_class-blob" class="type">&#x3C;Blob></a> identified by the given ID. Attempting to revoke a
ID that isn't registered will silently fail.</p>
<h5><code>URL.canParse(input[, base])</code><span><a class="mark" href="#all_url_urlcanparseinput-base" id="all_url_urlcanparseinput-base">#</a></span><a aria-hidden="true" class="legacy" id="url_url_canparse_input_base"></a></h5>
<div class="api_metadata">
<span>Added in: v19.9.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> 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. If <code>input</code> is not a string, it is <a href="https://tc39.es/ecma262/#sec-tostring">converted to a string</a> first.</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> The base URL to resolve against if the <code>input</code> is not
absolute. If <code>base</code> is not a string, it is <a href="https://tc39.es/ecma262/#sec-tostring">converted to a string</a> first.</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>Checks if an <code>input</code> relative to the <code>base</code> can be parsed to a <code>URL</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> isValid = <span class="hljs-variable constant_">URL</span>.<span class="hljs-title function_">canParse</span>(<span class="hljs-string">'/foo'</span>, <span class="hljs-string">'https://example.org/'</span>); <span class="hljs-comment">// true</span>

<span class="hljs-keyword">const</span> isNotValid = <span class="hljs-variable constant_">URL</span>.<span class="hljs-title function_">canParse</span>(<span class="hljs-string">'/foo'</span>); <span class="hljs-comment">// false</span></code> <button class="copy-button">copy</button></pre>
<h5><code>URL.parse(input[, base])</code><span><a class="mark" href="#all_url_urlparseinput-base" id="all_url_urlparseinput-base">#</a></span><a aria-hidden="true" class="legacy" id="url_url_parse_input_base"></a></h5>
<div class="api_metadata">
<span>Added in: v22.1.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> 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. If <code>input</code> is not a string, it is <a href="https://tc39.es/ecma262/#sec-tostring">converted to a string</a> first.</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> The base URL to resolve against if the <code>input</code> is not
absolute. If <code>base</code> is not a string, it is <a href="https://tc39.es/ecma262/#sec-tostring">converted to a string</a> first.</li>
<li>Returns: <a href="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a></li>
</ul>
<p>Parses a string as a URL. If <code>base</code> is provided, it will be used as the base
URL for the purpose of resolving non-absolute <code>input</code> URLs. Returns <code>null</code>
if <code>input</code> is not a valid.</p>
<h4>Class: <code>URLSearchParams</code><span><a class="mark" href="#all_url_class-urlsearchparams" id="all_url_class-urlsearchparams">#</a></span><a aria-hidden="true" class="legacy" id="url_class_urlsearchparams"></a></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>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"><span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://example.org/?abc=123'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">searchParams</span>.<span class="hljs-title function_">get</span>(<span class="hljs-string">'abc'</span>));
<span class="hljs-comment">// Prints 123</span>

myURL.<span class="hljs-property">searchParams</span>.<span class="hljs-title function_">append</span>(<span class="hljs-string">'abc'</span>, <span class="hljs-string">'xyz'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints https://example.org/?abc=123&#x26;abc=xyz</span>

myURL.<span class="hljs-property">searchParams</span>.<span class="hljs-title function_">delete</span>(<span class="hljs-string">'abc'</span>);
myURL.<span class="hljs-property">searchParams</span>.<span class="hljs-title function_">set</span>(<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints https://example.org/?a=b</span>

<span class="hljs-keyword">const</span> newSearchParams = <span class="hljs-keyword">new</span> <span class="hljs-title class_">URLSearchParams</span>(myURL.<span class="hljs-property">searchParams</span>);
<span class="hljs-comment">// The above is equivalent to</span>
<span class="hljs-comment">// const newSearchParams = new URLSearchParams(myURL.search);</span>

newSearchParams.<span class="hljs-title function_">append</span>(<span class="hljs-string">'a'</span>, <span class="hljs-string">'c'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints https://example.org/?a=b</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(newSearchParams.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints a=b&#x26;a=c</span>

<span class="hljs-comment">// newSearchParams.toString() is implicitly called</span>
myURL.<span class="hljs-property">search</span> = newSearchParams;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints https://example.org/?a=b&#x26;a=c</span>
newSearchParams.<span class="hljs-title function_">delete</span>(<span class="hljs-string">'a'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints https://example.org/?a=b&#x26;a=c</span></code> <button class="copy-button">copy</button></pre>
<h5><code>new URLSearchParams()</code><span><a class="mark" href="#all_url_new-urlsearchparams" id="all_url_new-urlsearchparams">#</a></span><a aria-hidden="true" class="legacy" id="url_new_urlsearchparams"></a></h5>
<p>Instantiate a new empty <code>URLSearchParams</code> object.</p>
<h5><code>new URLSearchParams(string)</code><span><a class="mark" href="#all_url_new-urlsearchparamsstring" id="all_url_new-urlsearchparamsstring">#</a></span><a aria-hidden="true" class="legacy" id="url_new_urlsearchparams_string"></a></h5>
<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"><span class="hljs-keyword">let</span> params;

params = <span class="hljs-keyword">new</span> <span class="hljs-title class_">URLSearchParams</span>(<span class="hljs-string">'user=abc&#x26;query=xyz'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(params.<span class="hljs-title function_">get</span>(<span class="hljs-string">'user'</span>));
<span class="hljs-comment">// Prints 'abc'</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(params.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints 'user=abc&#x26;query=xyz'</span>

params = <span class="hljs-keyword">new</span> <span class="hljs-title class_">URLSearchParams</span>(<span class="hljs-string">'?user=abc&#x26;query=xyz'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(params.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints 'user=abc&#x26;query=xyz'</span></code> <button class="copy-button">copy</button></pre>
<h5><code>new URLSearchParams(obj)</code><span><a class="mark" href="#all_url_new-urlsearchparamsobj" id="all_url_new-urlsearchparamsobj">#</a></span><a aria-hidden="true" class="legacy" id="url_new_urlsearchparams_obj"></a></h5>
<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"><span class="hljs-keyword">const</span> params = <span class="hljs-keyword">new</span> <span class="hljs-title class_">URLSearchParams</span>({
  <span class="hljs-attr">user</span>: <span class="hljs-string">'abc'</span>,
  <span class="hljs-attr">query</span>: [<span class="hljs-string">'first'</span>, <span class="hljs-string">'second'</span>],
});
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(params.<span class="hljs-title function_">getAll</span>(<span class="hljs-string">'query'</span>));
<span class="hljs-comment">// Prints [ 'first,second' ]</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(params.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints 'user=abc&#x26;query=first%2Csecond'</span></code> <button class="copy-button">copy</button></pre>
<h5><code>new URLSearchParams(iterable)</code><span><a class="mark" href="#all_url_new-urlsearchparamsiterable" id="all_url_new-urlsearchparamsiterable">#</a></span><a aria-hidden="true" class="legacy" id="url_new_urlsearchparams_iterable"></a></h5>
<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"><span class="hljs-keyword">let</span> params;

<span class="hljs-comment">// Using an array</span>
params = <span class="hljs-keyword">new</span> <span class="hljs-title class_">URLSearchParams</span>([
  [<span class="hljs-string">'user'</span>, <span class="hljs-string">'abc'</span>],
  [<span class="hljs-string">'query'</span>, <span class="hljs-string">'first'</span>],
  [<span class="hljs-string">'query'</span>, <span class="hljs-string">'second'</span>],
]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(params.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints 'user=abc&#x26;query=first&#x26;query=second'</span>

<span class="hljs-comment">// Using a Map object</span>
<span class="hljs-keyword">const</span> map = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Map</span>();
map.<span class="hljs-title function_">set</span>(<span class="hljs-string">'user'</span>, <span class="hljs-string">'abc'</span>);
map.<span class="hljs-title function_">set</span>(<span class="hljs-string">'query'</span>, <span class="hljs-string">'xyz'</span>);
params = <span class="hljs-keyword">new</span> <span class="hljs-title class_">URLSearchParams</span>(map);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(params.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints 'user=abc&#x26;query=xyz'</span>

<span class="hljs-comment">// Using a generator function</span>
<span class="hljs-keyword">function</span>* <span class="hljs-title function_">getQueryPairs</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">yield</span> [<span class="hljs-string">'user'</span>, <span class="hljs-string">'abc'</span>];
  <span class="hljs-keyword">yield</span> [<span class="hljs-string">'query'</span>, <span class="hljs-string">'first'</span>];
  <span class="hljs-keyword">yield</span> [<span class="hljs-string">'query'</span>, <span class="hljs-string">'second'</span>];
}
params = <span class="hljs-keyword">new</span> <span class="hljs-title class_">URLSearchParams</span>(<span class="hljs-title function_">getQueryPairs</span>());
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(params.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints 'user=abc&#x26;query=first&#x26;query=second'</span>

<span class="hljs-comment">// Each key-value pair must have exactly two elements</span>
<span class="hljs-keyword">new</span> <span class="hljs-title class_">URLSearchParams</span>([
  [<span class="hljs-string">'user'</span>, <span class="hljs-string">'abc'</span>, <span class="hljs-string">'error'</span>],
]);
<span class="hljs-comment">// Throws TypeError [ERR_INVALID_TUPLE]:</span>
<span class="hljs-comment">//        Each query pair must be an iterable [name, value] tuple</span></code> <button class="copy-button">copy</button></pre>
<h5><code>urlSearchParams.append(name, value)</code><span><a class="mark" href="#all_url_urlsearchparamsappendname-value" id="all_url_urlsearchparamsappendname-value">#</a></span><a aria-hidden="true" class="legacy" id="url_urlsearchparams_append_name_value"></a></h5>
<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>
<h5><code>urlSearchParams.delete(name[, value])</code><span><a class="mark" href="#all_url_urlsearchparamsdeletename-value" id="all_url_urlsearchparamsdeletename-value">#</a></span><a aria-hidden="true" class="legacy" id="url_urlsearchparams_delete_name_value"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.2.0</td>
<td><p>Add support for optional <code>value</code> argument.</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>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>If <code>value</code> is provided, removes all name-value pairs
where name is <code>name</code> and value is <code>value</code>..</p>
<p>If <code>value</code> is not provided, removes all name-value pairs whose name is <code>name</code>.</p>
<h5><code>urlSearchParams.entries()</code><span><a class="mark" href="#all_url_urlsearchparamsentries" id="all_url_urlsearchparamsentries">#</a></span><a aria-hidden="true" class="legacy" id="url_urlsearchparams_entries"></a></h5>
<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="#all_url_urlsearchparamssymboliterator"><code>urlSearchParams[@@iterator]()</code></a>.</p>
<h5><code>urlSearchParams.forEach(fn[, thisArg])</code><span><a class="mark" href="#all_url_urlsearchparamsforeachfn-thisarg" id="all_url_urlsearchparamsforeachfn-thisarg">#</a></span><a aria-hidden="true" class="legacy" id="url_urlsearchparams_foreach_fn_thisarg"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Passing an invalid callback to the <code>fn</code> argument now throws <code>ERR_INVALID_ARG_TYPE</code> instead of <code>ERR_INVALID_CALLBACK</code>.</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> 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"><span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://example.org/?a=b&#x26;c=d'</span>);
myURL.<span class="hljs-property">searchParams</span>.<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">value, name, searchParams</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(name, value, myURL.<span class="hljs-property">searchParams</span> === searchParams);
});
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   a b true</span>
<span class="hljs-comment">//   c d true</span></code> <button class="copy-button">copy</button></pre>
<h5><code>urlSearchParams.get(name)</code><span><a class="mark" href="#all_url_urlsearchparamsgetname" id="all_url_urlsearchparamsgetname">#</a></span><a aria-hidden="true" class="legacy" id="url_urlsearchparams_get_name"></a></h5>
<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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a> A string 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>
<h5><code>urlSearchParams.getAll(name)</code><span><a class="mark" href="#all_url_urlsearchparamsgetallname" id="all_url_urlsearchparamsgetallname">#</a></span><a aria-hidden="true" class="legacy" id="url_urlsearchparams_getall_name"></a></h5>
<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>
<h5><code>urlSearchParams.has(name[, value])</code><span><a class="mark" href="#all_url_urlsearchparamshasname-value" id="all_url_urlsearchparamshasname-value">#</a></span><a aria-hidden="true" class="legacy" id="url_urlsearchparams_has_name_value"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.2.0</td>
<td><p>Add support for optional <code>value</code> argument.</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>value</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>Checks if the <code>URLSearchParams</code> object contains key-value pair(s) based on
<code>name</code> and an optional <code>value</code> argument.</p>
<p>If <code>value</code> is provided, returns <code>true</code> when name-value pair with
same <code>name</code> and <code>value</code> exists.</p>
<p>If <code>value</code> is not provided, returns <code>true</code> if there is at least one name-value
pair whose name is <code>name</code>.</p>
<h5><code>urlSearchParams.keys()</code><span><a class="mark" href="#all_url_urlsearchparamskeys" id="all_url_urlsearchparamskeys">#</a></span><a aria-hidden="true" class="legacy" id="url_urlsearchparams_keys"></a></h5>
<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"><span class="hljs-keyword">const</span> params = <span class="hljs-keyword">new</span> <span class="hljs-title class_">URLSearchParams</span>(<span class="hljs-string">'foo=bar&#x26;foo=baz'</span>);
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> name <span class="hljs-keyword">of</span> params.<span class="hljs-title function_">keys</span>()) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(name);
}
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   foo</span>
<span class="hljs-comment">//   foo</span></code> <button class="copy-button">copy</button></pre>
<h5><code>urlSearchParams.set(name, value)</code><span><a class="mark" href="#all_url_urlsearchparamssetname-value" id="all_url_urlsearchparamssetname-value">#</a></span><a aria-hidden="true" class="legacy" id="url_urlsearchparams_set_name_value"></a></h5>
<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"><span class="hljs-keyword">const</span> params = <span class="hljs-keyword">new</span> <span class="hljs-title class_">URLSearchParams</span>();
params.<span class="hljs-title function_">append</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-string">'bar'</span>);
params.<span class="hljs-title function_">append</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-string">'baz'</span>);
params.<span class="hljs-title function_">append</span>(<span class="hljs-string">'abc'</span>, <span class="hljs-string">'def'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(params.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints foo=bar&#x26;foo=baz&#x26;abc=def</span>

params.<span class="hljs-title function_">set</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-string">'def'</span>);
params.<span class="hljs-title function_">set</span>(<span class="hljs-string">'xyz'</span>, <span class="hljs-string">'opq'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(params.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints foo=def&#x26;abc=def&#x26;xyz=opq</span></code> <button class="copy-button">copy</button></pre>
<h5><code>urlSearchParams.size</code><span><a class="mark" href="#all_url_urlsearchparamssize" id="all_url_urlsearchparamssize">#</a></span><a aria-hidden="true" class="legacy" id="url_urlsearchparams_size"></a></h5>
<div class="api_metadata">
<span>Added in: v19.8.0</span>
</div>
<p>The total number of parameter entries.</p>
<h5><code>urlSearchParams.sort()</code><span><a class="mark" href="#all_url_urlsearchparamssort" id="all_url_urlsearchparamssort">#</a></span><a aria-hidden="true" class="legacy" id="url_urlsearchparams_sort"></a></h5>
<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"><span class="hljs-keyword">const</span> params = <span class="hljs-keyword">new</span> <span class="hljs-title class_">URLSearchParams</span>(<span class="hljs-string">'query[]=abc&#x26;type=search&#x26;query[]=123'</span>);
params.<span class="hljs-title function_">sort</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(params.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints query%5B%5D=abc&#x26;query%5B%5D=123&#x26;type=search</span></code> <button class="copy-button">copy</button></pre>
<h5><code>urlSearchParams.toString()</code><span><a class="mark" href="#all_url_urlsearchparamstostring" id="all_url_urlsearchparamstostring">#</a></span><a aria-hidden="true" class="legacy" id="url_urlsearchparams_tostring"></a></h5>
<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>
<h5><code>urlSearchParams.values()</code><span><a class="mark" href="#all_url_urlsearchparamsvalues" id="all_url_urlsearchparamsvalues">#</a></span><a aria-hidden="true" class="legacy" id="url_urlsearchparams_values"></a></h5>
<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>
<h5><code>urlSearchParams[Symbol.iterator]()</code><span><a class="mark" href="#all_url_urlsearchparamssymboliterator" id="all_url_urlsearchparamssymboliterator">#</a></span><a aria-hidden="true" class="legacy" id="url_urlsearchparams_symbol_iterator"></a></h5>
<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="#all_url_urlsearchparamsentries"><code>urlSearchParams.entries()</code></a>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> params = <span class="hljs-keyword">new</span> <span class="hljs-title class_">URLSearchParams</span>(<span class="hljs-string">'foo=bar&#x26;xyz=baz'</span>);
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> [name, value] <span class="hljs-keyword">of</span> params) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(name, value);
}
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   foo bar</span>
<span class="hljs-comment">//   xyz baz</span></code> <button class="copy-button">copy</button></pre>
<h4><code>url.domainToASCII(domain)</code><span><a class="mark" href="#all_url_urldomaintoasciidomain" id="all_url_urldomaintoasciidomain">#</a></span><a aria-hidden="true" class="legacy" id="url_url_domaintoascii_domain"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>ICU requirement is removed.</p></td></tr>
<tr><td>v7.4.0, v6.13.0</td>
<td><p><span>Added in: v7.4.0, v6.13.0</span></p></td></tr>
</tbody></table>
</details>
</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="#all_url_urldomaintounicodedomain"><code>url.domainToUnicode()</code></a>.</p>

<pre class="with-32-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> url <span class="hljs-keyword">from</span> <span class="hljs-string">'node:url'</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(url.<span class="hljs-title function_">domainToASCII</span>(<span class="hljs-string">'español.com'</span>));
<span class="hljs-comment">// Prints xn--espaol-zwa.com</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(url.<span class="hljs-title function_">domainToASCII</span>(<span class="hljs-string">'中文.com'</span>));
<span class="hljs-comment">// Prints xn--fiq228c.com</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(url.<span class="hljs-title function_">domainToASCII</span>(<span class="hljs-string">'xn--iñvalid.com'</span>));
<span class="hljs-comment">// Prints an empty string</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> url = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(url.<span class="hljs-title function_">domainToASCII</span>(<span class="hljs-string">'español.com'</span>));
<span class="hljs-comment">// Prints xn--espaol-zwa.com</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(url.<span class="hljs-title function_">domainToASCII</span>(<span class="hljs-string">'中文.com'</span>));
<span class="hljs-comment">// Prints xn--fiq228c.com</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(url.<span class="hljs-title function_">domainToASCII</span>(<span class="hljs-string">'xn--iñvalid.com'</span>));
<span class="hljs-comment">// Prints an empty string</span></code><button class="copy-button">copy</button></pre>
<h4><code>url.domainToUnicode(domain)</code><span><a class="mark" href="#all_url_urldomaintounicodedomain" id="all_url_urldomaintounicodedomain">#</a></span><a aria-hidden="true" class="legacy" id="url_url_domaintounicode_domain"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>ICU requirement is removed.</p></td></tr>
<tr><td>v7.4.0, v6.13.0</td>
<td><p><span>Added in: v7.4.0, v6.13.0</span></p></td></tr>
</tbody></table>
</details>
</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="#all_url_urldomaintoasciidomain"><code>url.domainToASCII()</code></a>.</p>

<pre class="with-32-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> url <span class="hljs-keyword">from</span> <span class="hljs-string">'node:url'</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(url.<span class="hljs-title function_">domainToUnicode</span>(<span class="hljs-string">'xn--espaol-zwa.com'</span>));
<span class="hljs-comment">// Prints español.com</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(url.<span class="hljs-title function_">domainToUnicode</span>(<span class="hljs-string">'xn--fiq228c.com'</span>));
<span class="hljs-comment">// Prints 中文.com</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(url.<span class="hljs-title function_">domainToUnicode</span>(<span class="hljs-string">'xn--iñvalid.com'</span>));
<span class="hljs-comment">// Prints an empty string</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> url = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(url.<span class="hljs-title function_">domainToUnicode</span>(<span class="hljs-string">'xn--espaol-zwa.com'</span>));
<span class="hljs-comment">// Prints español.com</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(url.<span class="hljs-title function_">domainToUnicode</span>(<span class="hljs-string">'xn--fiq228c.com'</span>));
<span class="hljs-comment">// Prints 中文.com</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(url.<span class="hljs-title function_">domainToUnicode</span>(<span class="hljs-string">'xn--iñvalid.com'</span>));
<span class="hljs-comment">// Prints an empty string</span></code><button class="copy-button">copy</button></pre>
<h4><code>url.fileURLToPath(url[, options])</code><span><a class="mark" href="#all_url_urlfileurltopathurl-options" id="all_url_urlfileurltopathurl-options">#</a></span><a aria-hidden="true" class="legacy" id="url_url_fileurltopath_url_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.13.0</td>
<td><p>The <code>options</code> argument can now be used to determine how to parse the <code>path</code> argument.</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>url</code> <a href="#all_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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>windows</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#Undefined_type" class="type">&#x3C;undefined></a> <code>true</code> if the <code>path</code> should be
return as a windows filepath, <code>false</code> for posix, and
<code>undefined</code> for the system default.
<strong>Default:</strong> <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> 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 class="with-66-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { fileURLToPath } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:url'</span>;

<span class="hljs-keyword">const</span> __filename = <span class="hljs-title function_">fileURLToPath</span>(<span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>);

<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file:///C:/path/'</span>).<span class="hljs-property">pathname</span>;      <span class="hljs-comment">// Incorrect: /C:/path/</span>
<span class="hljs-title function_">fileURLToPath</span>(<span class="hljs-string">'file:///C:/path/'</span>);         <span class="hljs-comment">// Correct:   C:\path\ (Windows)</span>

<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file://nas/foo.txt'</span>).<span class="hljs-property">pathname</span>;    <span class="hljs-comment">// Incorrect: /foo.txt</span>
<span class="hljs-title function_">fileURLToPath</span>(<span class="hljs-string">'file://nas/foo.txt'</span>);       <span class="hljs-comment">// Correct:   \\nas\foo.txt (Windows)</span>

<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file:///你好.txt'</span>).<span class="hljs-property">pathname</span>;      <span class="hljs-comment">// Incorrect: /%E4%BD%A0%E5%A5%BD.txt</span>
<span class="hljs-title function_">fileURLToPath</span>(<span class="hljs-string">'file:///你好.txt'</span>);         <span class="hljs-comment">// Correct:   /你好.txt (POSIX)</span>

<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file:///hello world'</span>).<span class="hljs-property">pathname</span>;   <span class="hljs-comment">// Incorrect: /hello%20world</span>
<span class="hljs-title function_">fileURLToPath</span>(<span class="hljs-string">'file:///hello world'</span>);      <span class="hljs-comment">// Correct:   /hello world (POSIX)</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { fileURLToPath } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);
<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file:///C:/path/'</span>).<span class="hljs-property">pathname</span>;      <span class="hljs-comment">// Incorrect: /C:/path/</span>
<span class="hljs-title function_">fileURLToPath</span>(<span class="hljs-string">'file:///C:/path/'</span>);         <span class="hljs-comment">// Correct:   C:\path\ (Windows)</span>

<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file://nas/foo.txt'</span>).<span class="hljs-property">pathname</span>;    <span class="hljs-comment">// Incorrect: /foo.txt</span>
<span class="hljs-title function_">fileURLToPath</span>(<span class="hljs-string">'file://nas/foo.txt'</span>);       <span class="hljs-comment">// Correct:   \\nas\foo.txt (Windows)</span>

<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file:///你好.txt'</span>).<span class="hljs-property">pathname</span>;      <span class="hljs-comment">// Incorrect: /%E4%BD%A0%E5%A5%BD.txt</span>
<span class="hljs-title function_">fileURLToPath</span>(<span class="hljs-string">'file:///你好.txt'</span>);         <span class="hljs-comment">// Correct:   /你好.txt (POSIX)</span>

<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'file:///hello world'</span>).<span class="hljs-property">pathname</span>;   <span class="hljs-comment">// Incorrect: /hello%20world</span>
<span class="hljs-title function_">fileURLToPath</span>(<span class="hljs-string">'file:///hello world'</span>);      <span class="hljs-comment">// Correct:   /hello world (POSIX)</span></code><button class="copy-button">copy</button></pre>
<h4><code>url.format(URL[, options])</code><span><a class="mark" href="#all_url_urlformaturl-options" id="all_url_urlformaturl-options">#</a></span><a aria-hidden="true" class="legacy" id="url_url_format_url_options"></a></h4>
<div class="api_metadata">
<span>Added in: v7.6.0</span>
</div>
<ul>
<li><code>URL</code> <a href="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></a> A <a href="#all_url_the-whatwg-url-api">WHATWG URL</a> object</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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="#all_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 class="with-48-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> url <span class="hljs-keyword">from</span> <span class="hljs-string">'node:url'</span>;
<span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://a:b@測試?abc#foo'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints https://a:b@xn--g6w251d/?abc#foo</span>

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints https://a:b@xn--g6w251d/?abc#foo</span>

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(url.<span class="hljs-title function_">format</span>(myURL, { <span class="hljs-attr">fragment</span>: <span class="hljs-literal">false</span>, <span class="hljs-attr">unicode</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">auth</span>: <span class="hljs-literal">false</span> }));
<span class="hljs-comment">// Prints 'https://測試/?abc'</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> url = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);
<span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://a:b@測試?abc#foo'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints https://a:b@xn--g6w251d/?abc#foo</span>

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints https://a:b@xn--g6w251d/?abc#foo</span>

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(url.<span class="hljs-title function_">format</span>(myURL, { <span class="hljs-attr">fragment</span>: <span class="hljs-literal">false</span>, <span class="hljs-attr">unicode</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">auth</span>: <span class="hljs-literal">false</span> }));
<span class="hljs-comment">// Prints 'https://測試/?abc'</span></code><button class="copy-button">copy</button></pre>
<h4><code>url.pathToFileURL(path[, options])</code><span><a class="mark" href="#all_url_urlpathtofileurlpath-options" id="all_url_urlpathtofileurlpath-options">#</a></span><a aria-hidden="true" class="legacy" id="url_url_pathtofileurl_path_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.13.0</td>
<td><p>The <code>options</code> argument can now be used to determine how to return the <code>path</code> value.</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>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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>windows</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#Undefined_type" class="type">&#x3C;undefined></a> <code>true</code> if the <code>path</code> should be
treated as a windows filepath, <code>false</code> for posix, and
<code>undefined</code> for the system default.
<strong>Default:</strong> <code>undefined</code>.</li>
</ul>
</li>
<li>Returns: <a href="#all_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 class="with-66-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { pathToFileURL } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:url'</span>;

<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'/foo#1'</span>, <span class="hljs-string">'file:'</span>);           <span class="hljs-comment">// Incorrect: file:///foo#1</span>
<span class="hljs-title function_">pathToFileURL</span>(<span class="hljs-string">'/foo#1'</span>);              <span class="hljs-comment">// Correct:   file:///foo%231 (POSIX)</span>

<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'/some/path%.c'</span>, <span class="hljs-string">'file:'</span>);    <span class="hljs-comment">// Incorrect: file:///some/path%.c</span>
<span class="hljs-title function_">pathToFileURL</span>(<span class="hljs-string">'/some/path%.c'</span>);       <span class="hljs-comment">// Correct:   file:///some/path%25.c (POSIX)</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { pathToFileURL } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);
<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(__filename);                  <span class="hljs-comment">// Incorrect: throws (POSIX)</span>
<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(__filename);                  <span class="hljs-comment">// Incorrect: C:\... (Windows)</span>
<span class="hljs-title function_">pathToFileURL</span>(__filename);            <span class="hljs-comment">// Correct:   file:///... (POSIX)</span>
<span class="hljs-title function_">pathToFileURL</span>(__filename);            <span class="hljs-comment">// Correct:   file:///C:/... (Windows)</span>

<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'/foo#1'</span>, <span class="hljs-string">'file:'</span>);           <span class="hljs-comment">// Incorrect: file:///foo#1</span>
<span class="hljs-title function_">pathToFileURL</span>(<span class="hljs-string">'/foo#1'</span>);              <span class="hljs-comment">// Correct:   file:///foo%231 (POSIX)</span>

<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'/some/path%.c'</span>, <span class="hljs-string">'file:'</span>);    <span class="hljs-comment">// Incorrect: file:///some/path%.c</span>
<span class="hljs-title function_">pathToFileURL</span>(<span class="hljs-string">'/some/path%.c'</span>);       <span class="hljs-comment">// Correct:   file:///some/path%25.c (POSIX)</span></code><button class="copy-button">copy</button></pre>
<h4><code>url.urlToHttpOptions(url)</code><span><a class="mark" href="#all_url_urlurltohttpoptionsurl" id="all_url_urlurltohttpoptionsurl">#</a></span><a aria-hidden="true" class="legacy" id="url_url_urltohttpoptions_url"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.9.0</td>
<td><p>The returned object will also contain all the own enumerable properties of the <code>url</code> argument.</p></td></tr>
<tr><td>v15.7.0, v14.18.0</td>
<td><p><span>Added in: v15.7.0, v14.18.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>url</code> <a href="#all_url_the-whatwg-url-api" class="type">&#x3C;URL></a> The <a href="#all_url_the-whatwg-url-api">WHATWG URL</a> object to convert to an options object.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Options object
<ul>
<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.</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> A domain name or IP address of the server to issue the
request to.</li>
<li><code>hash</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The fragment portion of the URL.</li>
<li><code>search</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The serialized query portion of the URL.</li>
<li><code>pathname</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The path portion of the URL.</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.</li>
<li><code>href</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The serialized URL.</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>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>
</ul>
</li>
</ul>
<p>This utility function converts a URL object into an ordinary options object as
expected by the <a href="#all_http_httprequestoptions-callback"><code>http.request()</code></a> and <a href="#all_https_httpsrequestoptions-callback"><code>https.request()</code></a> APIs.</p>

<pre class="with-49-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { urlToHttpOptions } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:url'</span>;
<span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://a:b@測試?abc#foo'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">urlToHttpOptions</span>(myURL));
<span class="hljs-comment">/*
{
  protocol: 'https:',
  hostname: 'xn--g6w251d',
  hash: '#foo',
  search: '?abc',
  pathname: '/',
  path: '/?abc',
  href: 'https://a:b@xn--g6w251d/?abc#foo',
  auth: 'a:b'
}
*/</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { urlToHttpOptions } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);
<span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://a:b@測試?abc#foo'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">urlToHttpOptions</span>(myURL));
<span class="hljs-comment">/*
{
  protocol: 'https:',
  hostname: 'xn--g6w251d',
  hash: '#foo',
  search: '?abc',
  pathname: '/',
  path: '/?abc',
  href: 'https://a:b@xn--g6w251d/?abc#foo',
  auth: 'a:b'
}
*/</span></code><button class="copy-button">copy</button></pre>
</section><section><h3>Legacy URL API<span><a class="mark" href="#all_url_legacy-url-api" id="all_url_legacy-url-api">#</a></span><a aria-hidden="true" class="legacy" id="url_legacy_url_api"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.13.0, v14.17.0</td>
<td><p>Deprecation revoked. Status changed to "Legacy".</p></td></tr>
<tr><td>v11.0.0</td>
<td><p>This API is deprecated.</p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy: Use the WHATWG URL API instead.</div><p></p>
<h4>Legacy <code>urlObject</code><span><a class="mark" href="#all_url_legacy-urlobject" id="all_url_legacy-urlobject">#</a></span><a aria-hidden="true" class="legacy" id="url_legacy_urlobject"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.13.0, v14.17.0</td>
<td><p>Deprecation revoked. Status changed to "Legacy".</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>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy: Use the WHATWG URL API instead.</div><p></p>
<p>The legacy <code>urlObject</code> (<code>require('node:url').Url</code> or
<code>import { Url } from 'node:url'</code>) is
created and returned by the <code>url.parse()</code> function.</p>
<h5><code>urlObject.auth</code><span><a class="mark" href="#all_url_urlobjectauth" id="all_url_urlobjectauth">#</a></span><a aria-hidden="true" class="legacy" id="url_urlobject_auth"></a></h5>
<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>
<h5><code>urlObject.hash</code><span><a class="mark" href="#all_url_urlobjecthash" id="all_url_urlobjecthash">#</a></span><a aria-hidden="true" class="legacy" id="url_urlobject_hash"></a></h5>
<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>
<h5><code>urlObject.host</code><span><a class="mark" href="#all_url_urlobjecthost" id="all_url_urlobjecthost">#</a></span><a aria-hidden="true" class="legacy" id="url_urlobject_host"></a></h5>
<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>
<h5><code>urlObject.hostname</code><span><a class="mark" href="#all_url_urlobjecthostname" id="all_url_urlobjecthostname">#</a></span><a aria-hidden="true" class="legacy" id="url_urlobject_hostname"></a></h5>
<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>
<h5><code>urlObject.href</code><span><a class="mark" href="#all_url_urlobjecthref" id="all_url_urlobjecthref">#</a></span><a aria-hidden="true" class="legacy" id="url_urlobject_href"></a></h5>
<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>
<h5><code>urlObject.path</code><span><a class="mark" href="#all_url_urlobjectpath" id="all_url_urlobjectpath">#</a></span><a aria-hidden="true" class="legacy" id="url_urlobject_path"></a></h5>
<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>
<h5><code>urlObject.pathname</code><span><a class="mark" href="#all_url_urlobjectpathname" id="all_url_urlobjectpathname">#</a></span><a aria-hidden="true" class="legacy" id="url_urlobject_pathname"></a></h5>
<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>
<h5><code>urlObject.port</code><span><a class="mark" href="#all_url_urlobjectport" id="all_url_urlobjectport">#</a></span><a aria-hidden="true" class="legacy" id="url_urlobject_port"></a></h5>
<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>
<h5><code>urlObject.protocol</code><span><a class="mark" href="#all_url_urlobjectprotocol" id="all_url_urlobjectprotocol">#</a></span><a aria-hidden="true" class="legacy" id="url_urlobject_protocol"></a></h5>
<p>The <code>protocol</code> property identifies the URL's lower-cased protocol scheme.</p>
<p>For example: <code>'http:'</code>.</p>
<h5><code>urlObject.query</code><span><a class="mark" href="#all_url_urlobjectquery" id="all_url_urlobjectquery">#</a></span><a aria-hidden="true" class="legacy" id="url_urlobject_query"></a></h5>
<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>
<h5><code>urlObject.search</code><span><a class="mark" href="#all_url_urlobjectsearch" id="all_url_urlobjectsearch">#</a></span><a aria-hidden="true" class="legacy" id="url_urlobject_search"></a></h5>
<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>
<h5><code>urlObject.slashes</code><span><a class="mark" href="#all_url_urlobjectslashes" id="all_url_urlobjectslashes">#</a></span><a aria-hidden="true" class="legacy" id="url_urlobject_slashes"></a></h5>
<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>
<h4><code>url.format(urlObject)</code><span><a class="mark" href="#all_url_urlformaturlobject" id="all_url_urlformaturlobject">#</a></span><a aria-hidden="true" class="legacy" id="url_url_format_urlobject"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.0.0</td>
<td><p>Now throws an <code>ERR_INVALID_URL</code> exception when Punycode conversion of a hostname introduces changes that could cause the URL to be re-parsed differently.</p></td></tr>
<tr><td>v15.13.0, v14.17.0</td>
<td><p>Deprecation revoked. Status changed to "Legacy".</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>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 falsy <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>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy: Use the WHATWG URL API instead.</div><p></p>
<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"><span class="hljs-keyword">const</span> url = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);
url.<span class="hljs-title function_">format</span>({
  <span class="hljs-attr">protocol</span>: <span class="hljs-string">'https'</span>,
  <span class="hljs-attr">hostname</span>: <span class="hljs-string">'example.com'</span>,
  <span class="hljs-attr">pathname</span>: <span class="hljs-string">'/some/path'</span>,
  <span class="hljs-attr">query</span>: {
    <span class="hljs-attr">page</span>: <span class="hljs-number">1</span>,
    <span class="hljs-attr">format</span>: <span class="hljs-string">'json'</span>,
  },
});

<span class="hljs-comment">// => 'https://example.com/some/path?page=1&#x26;format=json'</span></code> <button class="copy-button">copy</button></pre>
<p>If <code>urlObject</code> is not an object or a string, <code>url.format()</code> will throw a
<a href="#all_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="#all_errors_class-error"><code>Error</code></a> is thrown.</li>
<li>For all string values of <code>urlObject.protocol</code> that <em>do not end</em> with an ASCII
colon (<code>:</code>) character, the literal string <code>:</code> will be appended to <code>result</code>.</li>
<li>If either of the following conditions is true, then the literal string <code>//</code>
will be appended to <code>result</code>:
<ul>
<li><code>urlObject.slashes</code> property is true;</li>
<li><code>urlObject.protocol</code> begins with <code>http</code>, <code>https</code>, <code>ftp</code>, <code>gopher</code>, or
<code>file</code>;</li>
</ul>
</li>
<li>If the value of the <code>urlObject.auth</code> property is truthy, and either
<code>urlObject.host</code> or <code>urlObject.hostname</code> are not <code>undefined</code>, the value of
<code>urlObject.auth</code> will be coerced into a string and appended to <code>result</code>
followed by the literal string <code>@</code>.</li>
<li>If the <code>urlObject.host</code> property is <code>undefined</code> then:
<ul>
<li>If the <code>urlObject.hostname</code> is a string, it is appended to <code>result</code>.</li>
<li>Otherwise, if <code>urlObject.hostname</code> is not <code>undefined</code> and is not a string,
an <a href="#all_errors_class-error"><code>Error</code></a> is thrown.</li>
<li>If the <code>urlObject.port</code> property value is truthy, and <code>urlObject.hostname</code>
is not <code>undefined</code>:
<ul>
<li>The literal string <code>:</code> is appended to <code>result</code>, and</li>
<li>The value of <code>urlObject.port</code> is coerced to a string and appended to
<code>result</code>.</li>
</ul>
</li>
</ul>
</li>
<li>Otherwise, if the <code>urlObject.host</code> property value is truthy, the value of
<code>urlObject.host</code> is coerced to a string and appended to <code>result</code>.</li>
<li>If the <code>urlObject.pathname</code> property is a string that is not an empty string:
<ul>
<li>If the <code>urlObject.pathname</code> <em>does not start</em> with an ASCII forward slash
(<code>/</code>), then the literal string <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="#all_errors_class-error"><code>Error</code></a> is thrown.</li>
<li>If the <code>urlObject.search</code> property is <code>undefined</code> and if the <code>urlObject.query</code>
property is an <code>Object</code>, the literal string <code>?</code> is appended to <code>result</code>
followed by the output of calling the <a href="querystring.html"><code>querystring</code></a> module's <code>stringify()</code>
method passing the value of <code>urlObject.query</code>.</li>
<li>Otherwise, if <code>urlObject.search</code> is a string:
<ul>
<li>If the value of <code>urlObject.search</code> <em>does not start</em> with the ASCII question
mark (<code>?</code>) character, the literal string <code>?</code> is appended to <code>result</code>.</li>
<li>The value of <code>urlObject.search</code> is appended to <code>result</code>.</li>
</ul>
</li>
<li>Otherwise, if <code>urlObject.search</code> is not <code>undefined</code> and is not a string, an
<a href="#all_errors_class-error"><code>Error</code></a> is thrown.</li>
<li>If the <code>urlObject.hash</code> property is a string:
<ul>
<li>If the value of <code>urlObject.hash</code> <em>does not start</em> with the ASCII hash (<code>#</code>)
character, the literal string <code>#</code> is appended to <code>result</code>.</li>
<li>The value of <code>urlObject.hash</code> is appended to <code>result</code>.</li>
</ul>
</li>
<li>Otherwise, if the <code>urlObject.hash</code> property is not <code>undefined</code> and is not a
string, an <a href="#all_errors_class-error"><code>Error</code></a> is thrown.</li>
<li><code>result</code> is returned.</li>
</ul>
<h4><code>url.parse(urlString[, parseQueryString[, slashesDenoteHost]])</code><span><a class="mark" href="#all_url_urlparseurlstring-parsequerystring-slashesdenotehost" id="all_url_urlparseurlstring-parsequerystring-slashesdenotehost">#</a></span><a aria-hidden="true" class="legacy" id="url_url_parse_urlstring_parsequerystring_slashesdenotehost"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.0.0, v18.13.0</td>
<td><p>Documentation-only deprecation.</p></td></tr>
<tr><td>v15.13.0, v14.17.0</td>
<td><p>Deprecation revoked. Status changed to "Legacy".</p></td></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>
<p></p><div class="api_stability api_stability_0"><a href="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use the WHATWG URL API instead.</div><p></p>
<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>
<p><code>url.parse()</code> uses a lenient, non-standard algorithm for parsing URL
strings. It is prone to security issues such as <a href="https://hackerone.com/reports/678487">host name spoofing</a>
and incorrect handling of usernames and passwords. Do not use with untrusted
input. CVEs are not issued for <code>url.parse()</code> vulnerabilities. Use the
<a href="#all_url_the-whatwg-url-api">WHATWG URL</a> API instead.</p>
<h4><code>url.resolve(from, to)</code><span><a class="mark" href="#all_url_urlresolvefrom-to" id="all_url_urlresolvefrom-to">#</a></span><a aria-hidden="true" class="legacy" id="url_url_resolve_from_to"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.13.0, v14.17.0</td>
<td><p>Deprecation revoked. Status changed to "Legacy".</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>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.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>v6.5.0, v4.6.2</td>
<td><p>The <code>port</code> field is copied correctly 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>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy: Use the WHATWG URL API instead.</div><p></p>
<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 to use if <code>to</code> is a relative URL.</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 target URL to resolve.</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.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> url = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:url'</span>);
url.<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'/one/two/three'</span>, <span class="hljs-string">'four'</span>);         <span class="hljs-comment">// '/one/two/four'</span>
url.<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'http://example.com/'</span>, <span class="hljs-string">'/one'</span>);    <span class="hljs-comment">// 'http://example.com/one'</span>
url.<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'http://example.com/one'</span>, <span class="hljs-string">'/two'</span>); <span class="hljs-comment">// 'http://example.com/two'</span></code> <button class="copy-button">copy</button></pre>
<p>To achieve the same result using the WHATWG URL API:</p>
<pre><code class="language-js"><span class="hljs-keyword">function</span> <span class="hljs-title function_">resolve</span>(<span class="hljs-params"><span class="hljs-keyword">from</span>, to</span>) {
  <span class="hljs-keyword">const</span> resolvedUrl = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(to, <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-keyword">from</span>, <span class="hljs-string">'resolve://'</span>));
  <span class="hljs-keyword">if</span> (resolvedUrl.<span class="hljs-property">protocol</span> === <span class="hljs-string">'resolve:'</span>) {
    <span class="hljs-comment">// `from` is a relative URL.</span>
    <span class="hljs-keyword">const</span> { pathname, search, hash } = resolvedUrl;
    <span class="hljs-keyword">return</span> pathname + search + hash;
  }
  <span class="hljs-keyword">return</span> resolvedUrl.<span class="hljs-title function_">toString</span>();
}

<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'/one/two/three'</span>, <span class="hljs-string">'four'</span>);         <span class="hljs-comment">// '/one/two/four'</span>
<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'http://example.com/'</span>, <span class="hljs-string">'/one'</span>);    <span class="hljs-comment">// 'http://example.com/one'</span>
<span class="hljs-title function_">resolve</span>(<span class="hljs-string">'http://example.com/one'</span>, <span class="hljs-string">'/two'</span>); <span class="hljs-comment">// 'http://example.com/two'</span></code> <button class="copy-button">copy</button></pre>
<p><a id="whatwg-percent-encoding"></a></p>
</section><section><h3>Percent-encoding in URLs<span><a class="mark" href="#all_url_percent-encoding-in-urls" id="all_url_percent-encoding-in-urls">#</a></span><a aria-hidden="true" class="legacy" id="url_percent_encoding_in_urls"></a></h3>
<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>
<h4>Legacy API<span><a class="mark" href="#all_url_legacy-api" id="all_url_legacy-api">#</a></span><a aria-hidden="true" class="legacy" id="url_legacy_api"></a></h4>
<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> <button class="copy-button">copy</button></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>
<h4>WHATWG API<span><a class="mark" href="#all_url_whatwg-api" id="all_url_whatwg-api">#</a></span><a aria-hidden="true" class="legacy" id="url_whatwg_api"></a></h4>
<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 SPACE, U+0022 ("), U+003C (&#x3C;), 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 SPACE, U+0022 ("), U+0023 (#), U+003C (&#x3C;), 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 ([) to 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"><span class="hljs-keyword">const</span> myURL = <span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://%CF%80.example.com/foo'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">href</span>);
<span class="hljs-comment">// Prints https://xn--1xa.example.com/foo</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myURL.<span class="hljs-property">origin</span>);
<span class="hljs-comment">// Prints https://xn--1xa.example.com</span></code> <button class="copy-button">copy</button></pre></section>
        </section>
<section><h2>Util<span><a class="mark" href="#all_util_util" id="all_util_util">#</a></span><a aria-hidden="true" class="legacy" id="util_util"></a></h2>

<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/util.js">lib/util.js</a></p>
<p>The <code>node: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"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);</code> <button class="copy-button">copy</button></pre>
<section><h3><code>util.callbackify(original)</code><span><a class="mark" href="#all_util_utilcallbackifyoriginal" id="all_util_utilcallbackifyoriginal">#</a></span><a aria-hidden="true" class="legacy" id="util_util_callbackify_original"></a></h3>
<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"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">fn</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">return</span> <span class="hljs-string">'hello world'</span>;
}
<span class="hljs-keyword">const</span> callbackFunction = util.<span class="hljs-title function_">callbackify</span>(fn);

<span class="hljs-title function_">callbackFunction</span>(<span class="hljs-function">(<span class="hljs-params">err, ret</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(ret);
});</code> <button class="copy-button">copy</button></pre>
<p>Will print:</p>
<pre><code class="language-text">hello world</code> <button class="copy-button">copy</button></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="#all_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"><span class="hljs-keyword">function</span> <span class="hljs-title function_">fn</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">return</span> <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">reject</span>(<span class="hljs-literal">null</span>);
}
<span class="hljs-keyword">const</span> callbackFunction = util.<span class="hljs-title function_">callbackify</span>(fn);

<span class="hljs-title function_">callbackFunction</span>(<span class="hljs-function">(<span class="hljs-params">err, ret</span>) =></span> {
  <span class="hljs-comment">// When the Promise was rejected with `null` it is wrapped with an Error and</span>
  <span class="hljs-comment">// the original value is stored in `reason`.</span>
  err &#x26;&#x26; <span class="hljs-title class_">Object</span>.<span class="hljs-title function_">hasOwn</span>(err, <span class="hljs-string">'reason'</span>) &#x26;&#x26; err.<span class="hljs-property">reason</span> === <span class="hljs-literal">null</span>;  <span class="hljs-comment">// true</span>
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>util.debuglog(section[, callback])</code><span><a class="mark" href="#all_util_utildebuglogsection-callback" id="all_util_utildebuglogsection-callback">#</a></span><a aria-hidden="true" class="legacy" id="util_util_debuglog_section_callback"></a></h3>
<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><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 invoked the first time the logging function
is called with a function argument that is a more optimized logging 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 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="#all_console_consoleerrordata-args"><code>console.error()</code></a>. If not, then the returned function is a no-op.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">const</span> debuglog = util.<span class="hljs-title function_">debuglog</span>(<span class="hljs-string">'foo'</span>);

<span class="hljs-title function_">debuglog</span>(<span class="hljs-string">'hello from foo [%d]'</span>, <span class="hljs-number">123</span>);</code> <button class="copy-button">copy</button></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> <button class="copy-button">copy</button></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"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">const</span> debuglog = util.<span class="hljs-title function_">debuglog</span>(<span class="hljs-string">'foo-bar'</span>);

<span class="hljs-title function_">debuglog</span>(<span class="hljs-string">'hi there, it\'s foo-bar [%d]'</span>, <span class="hljs-number">2333</span>);</code> <button class="copy-button">copy</button></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> <button class="copy-button">copy</button></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>
<p>The optional <code>callback</code> argument can be used to replace the logging function
with a different function that doesn't have any initialization or
unnecessary wrapping.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">let</span> debuglog = util.<span class="hljs-title function_">debuglog</span>(<span class="hljs-string">'internals'</span>, <span class="hljs-function">(<span class="hljs-params">debug</span>) =></span> {
  <span class="hljs-comment">// Replace with a logging function that optimizes out</span>
  <span class="hljs-comment">// testing if the section is enabled</span>
  debuglog = debug;
});</code> <button class="copy-button">copy</button></pre>
<h4><code>debuglog().enabled</code><span><a class="mark" href="#all_util_debuglogenabled" id="all_util_debuglogenabled">#</a></span><a aria-hidden="true" class="legacy" id="util_debuglog_enabled"></a></h4>
<div class="api_metadata">
<span>Added in: v14.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>The <code>util.debuglog().enabled</code> getter is used to create a test that can be used
in conditionals 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 value will be <code>true</code>. If not, then the returned value will be
<code>false</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">const</span> enabled = util.<span class="hljs-title function_">debuglog</span>(<span class="hljs-string">'foo'</span>).<span class="hljs-property">enabled</span>;
<span class="hljs-keyword">if</span> (enabled) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'hello from foo [%d]'</span>, <span class="hljs-number">123</span>);
}</code> <button class="copy-button">copy</button></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">hello from foo [123]</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>util.debug(section)</code><span><a class="mark" href="#all_util_utildebugsection" id="all_util_utildebugsection">#</a></span><a aria-hidden="true" class="legacy" id="util_util_debug_section"></a></h3>
<div class="api_metadata">
<span>Added in: v14.9.0</span>
</div>
<p>Alias for <code>util.debuglog</code>. Usage allows for readability of that doesn't imply
logging when only using <code>util.debuglog().enabled</code>.</p>
</section><section><h3><code>util.deprecate(fn, msg[, code])</code><span><a class="mark" href="#all_util_utildeprecatefn-msg-code" id="all_util_utildeprecatefn-msg-code">#</a></span><a aria-hidden="true" class="legacy" id="util_util_deprecate_fn_msg_code"></a></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>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="#all_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"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

<span class="hljs-built_in">exports</span>.<span class="hljs-property">obsoleteFunction</span> = util.<span class="hljs-title function_">deprecate</span>(<span class="hljs-function">() =></span> {
  <span class="hljs-comment">// Do something here.</span>
}, <span class="hljs-string">'obsoleteFunction() is deprecated. Use newShinyFunction() instead.'</span>);</code> <button class="copy-button">copy</button></pre>
<p>When called, <code>util.deprecate()</code> will return a function that will emit a
<code>DeprecationWarning</code> using the <a href="#all_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"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

<span class="hljs-keyword">const</span> fn1 = util.<span class="hljs-title function_">deprecate</span>(someFunction, someMessage, <span class="hljs-string">'DEP0001'</span>);
<span class="hljs-keyword">const</span> fn2 = util.<span class="hljs-title function_">deprecate</span>(someOtherFunction, someOtherMessage, <span class="hljs-string">'DEP0001'</span>);
<span class="hljs-title function_">fn1</span>(); <span class="hljs-comment">// Emits a deprecation warning with code DEP0001</span>
<span class="hljs-title function_">fn2</span>(); <span class="hljs-comment">// Does not emit a deprecation warning because it has the same code</span></code> <button class="copy-button">copy</button></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>
</section><section><h3><code>util.format(format[, ...args])</code><span><a class="mark" href="#all_util_utilformatformat-args" id="all_util_utilformatformat-args">#</a></span><a aria-hidden="true" class="legacy" id="util_util_format_format_args"></a></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>%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.<span class="hljs-title function_">format</span>(<span class="hljs-string">'%s:%s'</span>, <span class="hljs-string">'foo'</span>);
<span class="hljs-comment">// Returns: 'foo:%s'</span></code> <button class="copy-button">copy</button></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.<span class="hljs-title function_">format</span>(<span class="hljs-string">'%s:%s'</span>, <span class="hljs-string">'foo'</span>, <span class="hljs-string">'bar'</span>, <span class="hljs-string">'baz'</span>);
<span class="hljs-comment">// Returns: 'foo:bar baz'</span></code> <button class="copy-button">copy</button></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.<span class="hljs-title function_">format</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>);
<span class="hljs-comment">// Returns: '1 2 3'</span></code> <button class="copy-button">copy</button></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.<span class="hljs-title function_">format</span>(<span class="hljs-string">'%% %s'</span>);
<span class="hljs-comment">// Returns: '%% %s'</span></code> <button class="copy-button">copy</button></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>
</section><section><h3><code>util.formatWithOptions(inspectOptions, format[, ...args])</code><span><a class="mark" href="#all_util_utilformatwithoptionsinspectoptions-format-args" id="all_util_utilformatwithoptionsinspectoptions-format-args">#</a></span><a aria-hidden="true" class="legacy" id="util_util_formatwithoptions_inspectoptions_format_args"></a></h3>
<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="#all_util_utilformatformat-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="#all_util_utilinspectobject-options"><code>util.inspect()</code></a>.</p>
<pre><code class="language-js">util.<span class="hljs-title function_">formatWithOptions</span>({ <span class="hljs-attr">colors</span>: <span class="hljs-literal">true</span> }, <span class="hljs-string">'See object %O'</span>, { <span class="hljs-attr">foo</span>: <span class="hljs-number">42</span> });
<span class="hljs-comment">// Returns 'See object { foo: 42 }', where `42` is colored as a number</span>
<span class="hljs-comment">// when printed to a terminal.</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>util.getSystemErrorName(err)</code><span><a class="mark" href="#all_util_utilgetsystemerrornameerr" id="all_util_utilgetsystemerrornameerr">#</a></span><a aria-hidden="true" class="legacy" id="util_util_getsystemerrorname_err"></a></h3>
<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="#all_errors_common-system-errors">Common System Errors</a> for the names of common errors.</p>
<pre><code class="language-js">fs.<span class="hljs-title function_">access</span>(<span class="hljs-string">'file/that/does/not/exist'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-keyword">const</span> name = util.<span class="hljs-title function_">getSystemErrorName</span>(err.<span class="hljs-property">errno</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(name);  <span class="hljs-comment">// ENOENT</span>
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>util.getSystemErrorMap()</code><span><a class="mark" href="#all_util_utilgetsystemerrormap" id="all_util_utilgetsystemerrormap">#</a></span><a aria-hidden="true" class="legacy" id="util_util_getsystemerrormap"></a></h3>
<div class="api_metadata">
<span>Added in: v16.0.0, v14.17.0</span>
</div>
<ul>
<li>Returns: <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 Map of all system error codes available from the Node.js API.
The mapping between error codes and error names is platform-dependent.
See <a href="#all_errors_common-system-errors">Common System Errors</a> for the names of common errors.</p>
<pre><code class="language-js">fs.<span class="hljs-title function_">access</span>(<span class="hljs-string">'file/that/does/not/exist'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-keyword">const</span> errorMap = util.<span class="hljs-title function_">getSystemErrorMap</span>();
  <span class="hljs-keyword">const</span> name = errorMap.<span class="hljs-title function_">get</span>(err.<span class="hljs-property">errno</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(name);  <span class="hljs-comment">// ENOENT</span>
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>util.inherits(constructor, superConstructor)</code><span><a class="mark" href="#all_util_utilinheritsconstructor-superconstructor" id="all_util_utilinheritsconstructor-superconstructor">#</a></span><a aria-hidden="true" class="legacy" id="util_util_inherits_constructor_superconstructor"></a></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>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>
<p></p><div class="api_stability api_stability_3"><a href="#all_documentation_stability-index">Stability: 3</a> - Legacy: Use ES2015 class syntax and <code>extends</code> keyword instead.</div><p></p>
<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"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);

<span class="hljs-keyword">function</span> <span class="hljs-title function_">MyStream</span>(<span class="hljs-params"></span>) {
  <span class="hljs-title class_">EventEmitter</span>.<span class="hljs-title function_">call</span>(<span class="hljs-variable language_">this</span>);
}

util.<span class="hljs-title function_">inherits</span>(<span class="hljs-title class_">MyStream</span>, <span class="hljs-title class_">EventEmitter</span>);

<span class="hljs-title class_">MyStream</span>.<span class="hljs-property"><span class="hljs-keyword">prototype</span></span>.<span class="hljs-property">write</span> = <span class="hljs-keyword">function</span>(<span class="hljs-params">data</span>) {
  <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'data'</span>, data);
};

<span class="hljs-keyword">const</span> stream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyStream</span>();

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(stream <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">EventEmitter</span>); <span class="hljs-comment">// true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">MyStream</span>.<span class="hljs-property">super_</span> === <span class="hljs-title class_">EventEmitter</span>); <span class="hljs-comment">// true</span>

stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Received data: "<span class="hljs-subst">${data}</span>"`</span>);
});
stream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'It works!'</span>); <span class="hljs-comment">// Received data: "It works!"</span></code> <button class="copy-button">copy</button></pre>
<p>ES6 example using <code>class</code> and <code>extends</code>:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> <span class="hljs-title class_">EventEmitter</span> = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:events'</span>);

<span class="hljs-keyword">class</span> <span class="hljs-title class_">MyStream</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">EventEmitter</span> {
  <span class="hljs-title function_">write</span>(<span class="hljs-params">data</span>) {
    <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">emit</span>(<span class="hljs-string">'data'</span>, data);
  }
}

<span class="hljs-keyword">const</span> stream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MyStream</span>();

stream.<span class="hljs-title function_">on</span>(<span class="hljs-string">'data'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`Received data: "<span class="hljs-subst">${data}</span>"`</span>);
});
stream.<span class="hljs-title function_">write</span>(<span class="hljs-string">'With ES6'</span>);</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>util.inspect(object[, options])</code><span><a class="mark" href="#all_util_utilinspectobject-options" id="all_util_utilinspectobject-options">#</a></span><a aria-hidden="true" class="legacy" id="util_util_inspect_object_options"></a></h3>
</section><section><h3><code>util.inspect(object[, showHidden[, depth[, colors]]])</code><span><a class="mark" href="#all_util_utilinspectobject-showhidden-depth-colors" id="all_util_utilinspectobject-showhidden-depth-colors">#</a></span><a aria-hidden="true" class="legacy" id="util_util_inspect_object_showhidden_depth_colors"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v16.18.0</td>
<td><p>add support for <code>maxArrayLength</code> when inspecting <code>Set</code> and <code>Map</code>.</p></td></tr>
<tr><td>v17.3.0, v16.14.0</td>
<td><p>The <code>numericSeparator</code> option is supported now.</p></td></tr>
<tr><td>v13.0.0</td>
<td><p>Circular references now include a marker to the reference.</p></td></tr>
<tr><td>v14.6.0, v12.19.0</td>
<td><p>If <code>object</code> is from a different <code>vm.Context</code> now, a custom inspection function on it will not receive context-specific arguments anymore.</p></td></tr>
<tr><td>v13.13.0, v12.17.0</td>
<td><p>The <code>maxStringLength</code> option is supported now.</p></td></tr>
<tr><td>v13.5.0, 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 MiB. 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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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="#all_util_customizing-utilinspect-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, inspect)</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/Map"><code>Map</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set"><code>Set</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>10000</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 break on new lines in 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. 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>
<li><code>numericSeparator</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>, an underscore is used to
separate every three digits in all bigints and numbers.
<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"><span class="hljs-keyword">class</span> <span class="hljs-title class_">Foo</span> {
  get [<span class="hljs-title class_">Symbol</span>.<span class="hljs-property">toStringTag</span>]() {
    <span class="hljs-keyword">return</span> <span class="hljs-string">'bar'</span>;
  }
}

<span class="hljs-keyword">class</span> <span class="hljs-title class_">Bar</span> {}

<span class="hljs-keyword">const</span> baz = <span class="hljs-title class_">Object</span>.<span class="hljs-title function_">create</span>(<span class="hljs-literal">null</span>, { [<span class="hljs-title class_">Symbol</span>.<span class="hljs-property">toStringTag</span>]: { <span class="hljs-attr">value</span>: <span class="hljs-string">'foo'</span> } });

util.<span class="hljs-title function_">inspect</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Foo</span>()); <span class="hljs-comment">// 'Foo [bar] {}'</span>
util.<span class="hljs-title function_">inspect</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Bar</span>()); <span class="hljs-comment">// 'Bar {}'</span>
util.<span class="hljs-title function_">inspect</span>(baz);       <span class="hljs-comment">// '[foo] {}'</span></code> <button class="copy-button">copy</button></pre>
<p>Circular references point to their anchor by using a reference index:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { inspect } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

<span class="hljs-keyword">const</span> obj = {};
obj.<span class="hljs-property">a</span> = [obj];
obj.<span class="hljs-property">b</span> = {};
obj.<span class="hljs-property">b</span>.<span class="hljs-property">inner</span> = obj.<span class="hljs-property">b</span>;
obj.<span class="hljs-property">b</span>.<span class="hljs-property">obj</span> = obj;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">inspect</span>(obj));
<span class="hljs-comment">// &#x3C;ref *1> {</span>
<span class="hljs-comment">//   a: [ [Circular *1] ],</span>
<span class="hljs-comment">//   b: &#x3C;ref *2> { inner: [Circular *2], obj: [Circular *1] }</span>
<span class="hljs-comment">// }</span></code> <button class="copy-button">copy</button></pre>
<p>The following example inspects all properties of the <code>util</code> object:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(util.<span class="hljs-title function_">inspect</span>(util, { <span class="hljs-attr">showHidden</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">depth</span>: <span class="hljs-literal">null</span> }));</code> <button class="copy-button">copy</button></pre>
<p>The following example highlights the effect of the <code>compact</code> option:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

<span class="hljs-keyword">const</span> o = {
  <span class="hljs-attr">a</span>: [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, [[
    <span class="hljs-string">'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit, sed do '</span> +
      <span class="hljs-string">'eiusmod \ntempor incididunt ut labore et dolore magna aliqua.'</span>,
    <span class="hljs-string">'test'</span>,
    <span class="hljs-string">'foo'</span>]], <span class="hljs-number">4</span>],
  <span class="hljs-attr">b</span>: <span class="hljs-keyword">new</span> <span class="hljs-title class_">Map</span>([[<span class="hljs-string">'za'</span>, <span class="hljs-number">1</span>], [<span class="hljs-string">'zb'</span>, <span class="hljs-string">'test'</span>]]),
};
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(util.<span class="hljs-title function_">inspect</span>(o, { <span class="hljs-attr">compact</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">depth</span>: <span class="hljs-number">5</span>, <span class="hljs-attr">breakLength</span>: <span class="hljs-number">80</span> }));

<span class="hljs-comment">// { a:</span>
<span class="hljs-comment">//   [ 1,</span>
<span class="hljs-comment">//     2,</span>
<span class="hljs-comment">//     [ [ 'Lorem ipsum dolor sit amet,\nconsectetur [...]', // A long line</span>
<span class="hljs-comment">//           'test',</span>
<span class="hljs-comment">//           'foo' ] ],</span>
<span class="hljs-comment">//     4 ],</span>
<span class="hljs-comment">//   b: Map(2) { 'za' => 1, 'zb' => 'test' } }</span>

<span class="hljs-comment">// Setting `compact` to false or an integer creates more reader friendly output.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(util.<span class="hljs-title function_">inspect</span>(o, { <span class="hljs-attr">compact</span>: <span class="hljs-literal">false</span>, <span class="hljs-attr">depth</span>: <span class="hljs-number">5</span>, <span class="hljs-attr">breakLength</span>: <span class="hljs-number">80</span> }));

<span class="hljs-comment">// {</span>
<span class="hljs-comment">//   a: [</span>
<span class="hljs-comment">//     1,</span>
<span class="hljs-comment">//     2,</span>
<span class="hljs-comment">//     [</span>
<span class="hljs-comment">//       [</span>
<span class="hljs-comment">//         'Lorem ipsum dolor sit amet,\n' +</span>
<span class="hljs-comment">//           'consectetur adipiscing elit, sed do eiusmod \n' +</span>
<span class="hljs-comment">//           'tempor incididunt ut labore et dolore magna aliqua.',</span>
<span class="hljs-comment">//         'test',</span>
<span class="hljs-comment">//         'foo'</span>
<span class="hljs-comment">//       ]</span>
<span class="hljs-comment">//     ],</span>
<span class="hljs-comment">//     4</span>
<span class="hljs-comment">//   ],</span>
<span class="hljs-comment">//   b: Map(2) {</span>
<span class="hljs-comment">//     'za' => 1,</span>
<span class="hljs-comment">//     'zb' => 'test'</span>
<span class="hljs-comment">//   }</span>
<span class="hljs-comment">// }</span>

<span class="hljs-comment">// Setting `breakLength` to e.g. 150 will print the "Lorem ipsum" text in a</span>
<span class="hljs-comment">// single line.</span></code> <button class="copy-button">copy</button></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"><span class="hljs-keyword">const</span> { inspect } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

<span class="hljs-keyword">const</span> obj = { <span class="hljs-attr">a</span>: <span class="hljs-number">1</span> };
<span class="hljs-keyword">const</span> obj2 = { <span class="hljs-attr">b</span>: <span class="hljs-number">2</span> };
<span class="hljs-keyword">const</span> weakSet = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WeakSet</span>([obj, obj2]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">inspect</span>(weakSet, { <span class="hljs-attr">showHidden</span>: <span class="hljs-literal">true</span> }));
<span class="hljs-comment">// WeakSet { { a: 1 }, { b: 2 } }</span></code> <button class="copy-button">copy</button></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"><span class="hljs-keyword">const</span> { inspect } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);

<span class="hljs-keyword">const</span> o1 = {
  <span class="hljs-attr">b</span>: [<span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">1</span>],
  <span class="hljs-attr">a</span>: <span class="hljs-string">'`a` comes before `b`'</span>,
  <span class="hljs-attr">c</span>: <span class="hljs-keyword">new</span> <span class="hljs-title class_">Set</span>([<span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">1</span>]),
};
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">inspect</span>(o1, { <span class="hljs-attr">sorted</span>: <span class="hljs-literal">true</span> }));
<span class="hljs-comment">// { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } }</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">inspect</span>(o1, { <span class="hljs-attr">sorted</span>: <span class="hljs-function">(<span class="hljs-params">a, b</span>) =></span> b.<span class="hljs-title function_">localeCompare</span>(a) }));
<span class="hljs-comment">// { c: Set(3) { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' }</span>

<span class="hljs-keyword">const</span> o2 = {
  <span class="hljs-attr">c</span>: <span class="hljs-keyword">new</span> <span class="hljs-title class_">Set</span>([<span class="hljs-number">2</span>, <span class="hljs-number">1</span>, <span class="hljs-number">3</span>]),
  <span class="hljs-attr">a</span>: <span class="hljs-string">'`a` comes before `b`'</span>,
  <span class="hljs-attr">b</span>: [<span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">1</span>],
};
assert.<span class="hljs-property">strict</span>.<span class="hljs-title function_">equal</span>(
  <span class="hljs-title function_">inspect</span>(o1, { <span class="hljs-attr">sorted</span>: <span class="hljs-literal">true</span> }),
  <span class="hljs-title function_">inspect</span>(o2, { <span class="hljs-attr">sorted</span>: <span class="hljs-literal">true</span> }),
);</code> <button class="copy-button">copy</button></pre>
<p>The <code>numericSeparator</code> option adds an underscore every three digits to all
numbers.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { inspect } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

<span class="hljs-keyword">const</span> thousand = <span class="hljs-number">1_000</span>;
<span class="hljs-keyword">const</span> million = <span class="hljs-number">1_000_000</span>;
<span class="hljs-keyword">const</span> bigNumber = <span class="hljs-number">123_456_789n</span>;
<span class="hljs-keyword">const</span> bigDecimal = <span class="hljs-number">1_234.123_45</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">inspect</span>(thousand, { <span class="hljs-attr">numericSeparator</span>: <span class="hljs-literal">true</span> }));
<span class="hljs-comment">// 1_000</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">inspect</span>(million, { <span class="hljs-attr">numericSeparator</span>: <span class="hljs-literal">true</span> }));
<span class="hljs-comment">// 1_000_000</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">inspect</span>(bigNumber, { <span class="hljs-attr">numericSeparator</span>: <span class="hljs-literal">true</span> }));
<span class="hljs-comment">// 123_456_789n</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">inspect</span>(bigDecimal, { <span class="hljs-attr">numericSeparator</span>: <span class="hljs-literal">true</span> }));
<span class="hljs-comment">// 1_234.123_45</span></code> <button class="copy-button">copy</button></pre>
<p><code>util.inspect()</code> is a synchronous method intended for debugging. Its maximum
output length is approximately 128 MiB. Inputs that result in longer output will
be truncated.</p>
<h4>Customizing <code>util.inspect</code> colors<span><a class="mark" href="#all_util_customizing-utilinspect-colors" id="all_util_customizing-utilinspect-colors">#</a></span><a aria-hidden="true" class="legacy" id="util_customizing_util_inspect_colors"></a></h4>

<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="#all_tty_writestreamhascolorscount-env"><code>tty.hasColors()</code></a>.</p>
<p>Predefined control codes are listed below (grouped as "Modifiers", "Foreground
colors", and "Background colors").</p>
<h5>Modifiers<span><a class="mark" href="#all_util_modifiers" id="all_util_modifiers">#</a></span><a aria-hidden="true" class="legacy" id="util_modifiers"></a></h5>
<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>
<h5>Foreground colors<span><a class="mark" href="#all_util_foreground-colors" id="all_util_foreground-colors">#</a></span><a aria-hidden="true" class="legacy" id="util_foreground_colors"></a></h5>
<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>
<h5>Background colors<span><a class="mark" href="#all_util_background-colors" id="all_util_background-colors">#</a></span><a aria-hidden="true" class="legacy" id="util_background_colors"></a></h5>
<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>
<h4>Custom inspection functions on objects<span><a class="mark" href="#all_util_custom-inspection-functions-on-objects" id="all_util_custom-inspection-functions-on-objects">#</a></span><a aria-hidden="true" class="legacy" id="util_custom_inspection_functions_on_objects"></a></h4>

<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.3.0, v16.14.0</td>
<td><p>The inspect argument is added for more interoperability.</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>
<p>Objects may also define their own
<a href="#all_util_utilinspectcustom"><code>[util.inspect.custom](depth, opts, inspect)</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"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

<span class="hljs-keyword">class</span> <span class="hljs-title class_">Box</span> {
  <span class="hljs-title function_">constructor</span>(<span class="hljs-params">value</span>) {
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">value</span> = value;
  }

  [util.<span class="hljs-property">inspect</span>.<span class="hljs-property">custom</span>](depth, options, inspect) {
    <span class="hljs-keyword">if</span> (depth &#x3C; <span class="hljs-number">0</span>) {
      <span class="hljs-keyword">return</span> options.<span class="hljs-title function_">stylize</span>(<span class="hljs-string">'[Box]'</span>, <span class="hljs-string">'special'</span>);
    }

    <span class="hljs-keyword">const</span> newOptions = <span class="hljs-title class_">Object</span>.<span class="hljs-title function_">assign</span>({}, options, {
      <span class="hljs-attr">depth</span>: options.<span class="hljs-property">depth</span> === <span class="hljs-literal">null</span> ? <span class="hljs-literal">null</span> : options.<span class="hljs-property">depth</span> - <span class="hljs-number">1</span>,
    });

    <span class="hljs-comment">// Five space padding because that's the size of "Box&#x3C; ".</span>
    <span class="hljs-keyword">const</span> padding = <span class="hljs-string">' '</span>.<span class="hljs-title function_">repeat</span>(<span class="hljs-number">5</span>);
    <span class="hljs-keyword">const</span> inner = <span class="hljs-title function_">inspect</span>(<span class="hljs-variable language_">this</span>.<span class="hljs-property">value</span>, newOptions)
                  .<span class="hljs-title function_">replace</span>(<span class="hljs-regexp">/\n/g</span>, <span class="hljs-string">`\n<span class="hljs-subst">${padding}</span>`</span>);
    <span class="hljs-keyword">return</span> <span class="hljs-string">`<span class="hljs-subst">${options.stylize(<span class="hljs-string">'Box'</span>, <span class="hljs-string">'special'</span>)}</span>&#x3C; <span class="hljs-subst">${inner}</span> >`</span>;
  }
}

<span class="hljs-keyword">const</span> box = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Box</span>(<span class="hljs-literal">true</span>);

util.<span class="hljs-title function_">inspect</span>(box);
<span class="hljs-comment">// Returns: "Box&#x3C; true >"</span></code> <button class="copy-button">copy</button></pre>
<p>Custom <code>[util.inspect.custom](depth, opts, inspect)</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"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

<span class="hljs-keyword">const</span> obj = { <span class="hljs-attr">foo</span>: <span class="hljs-string">'this will not show up in the inspect() output'</span> };
obj[util.<span class="hljs-property">inspect</span>.<span class="hljs-property">custom</span>] = <span class="hljs-function">(<span class="hljs-params">depth</span>) =></span> {
  <span class="hljs-keyword">return</span> { <span class="hljs-attr">bar</span>: <span class="hljs-string">'baz'</span> };
};

util.<span class="hljs-title function_">inspect</span>(obj);
<span class="hljs-comment">// Returns: "{ bar: 'baz' }"</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.inspect.custom</code><span><a class="mark" href="#all_util_utilinspectcustom" id="all_util_utilinspectcustom">#</a></span><a aria-hidden="true" class="legacy" id="util_util_inspect_custom"></a></h4>
<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>
<p>Using this allows code to be written in a portable fashion, so that the custom
inspect function is used in an Node.js environment and ignored in the browser.
The <code>util.inspect()</code> function itself is passed as third argument to the custom
inspect function to allow further portability.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> customInspectSymbol = <span class="hljs-title class_">Symbol</span>.<span class="hljs-title function_">for</span>(<span class="hljs-string">'nodejs.util.inspect.custom'</span>);

<span class="hljs-keyword">class</span> <span class="hljs-title class_">Password</span> {
  <span class="hljs-title function_">constructor</span>(<span class="hljs-params">value</span>) {
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">value</span> = value;
  }

  <span class="hljs-title function_">toString</span>(<span class="hljs-params"></span>) {
    <span class="hljs-keyword">return</span> <span class="hljs-string">'xxxxxxxx'</span>;
  }

  [customInspectSymbol](depth, inspectOptions, inspect) {
    <span class="hljs-keyword">return</span> <span class="hljs-string">`Password &#x3C;<span class="hljs-subst">${<span class="hljs-variable language_">this</span>.toString()}</span>>`</span>;
  }
}

<span class="hljs-keyword">const</span> password = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Password</span>(<span class="hljs-string">'r0sebud'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(password);
<span class="hljs-comment">// Prints Password &#x3C;xxxxxxxx></span></code> <button class="copy-button">copy</button></pre>
<p>See <a href="#all_util_custom-inspection-functions-on-objects">Custom inspection functions on Objects</a> for more details.</p>
<h4><code>util.inspect.defaultOptions</code><span><a class="mark" href="#all_util_utilinspectdefaultoptions" id="all_util_utilinspectdefaultoptions">#</a></span><a aria-hidden="true" class="legacy" id="util_util_inspect_defaultoptions"></a></h4>
<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="#all_util_utilinspectobject-options"><code>util.inspect()</code></a> options. Setting
option properties directly is also supported.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">const</span> arr = <span class="hljs-title class_">Array</span>(<span class="hljs-number">101</span>).<span class="hljs-title function_">fill</span>(<span class="hljs-number">0</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(arr); <span class="hljs-comment">// Logs the truncated array</span>
util.<span class="hljs-property">inspect</span>.<span class="hljs-property">defaultOptions</span>.<span class="hljs-property">maxArrayLength</span> = <span class="hljs-literal">null</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(arr); <span class="hljs-comment">// logs the full array</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>util.isDeepStrictEqual(val1, val2)</code><span><a class="mark" href="#all_util_utilisdeepstrictequalval1-val2" id="all_util_utilisdeepstrictequalval1-val2">#</a></span><a aria-hidden="true" class="legacy" id="util_util_isdeepstrictequal_val1_val2"></a></h3>
<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="#all_assert_assertdeepstrictequalactual-expected-message"><code>assert.deepStrictEqual()</code></a> for more information about deep strict
equality.</p>
</section><section><h3>Class: <code>util.MIMEType</code><span><a class="mark" href="#all_util_class-utilmimetype" id="all_util_class-utilmimetype">#</a></span><a aria-hidden="true" class="legacy" id="util_class_util_mimetype"></a></h3>
<div class="api_metadata">
<span>Added in: v19.1.0, v18.13.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>An implementation of <a href="https://bmeck.github.io/node-proposal-mime-api/">the MIMEType class</a>.</p>
<p>In accordance with browser conventions, all properties of <code>MIMEType</code> objects
are implemented as getters and setters on the class prototype, rather than as
data properties on the object itself.</p>
<p>A MIME string is a structured string containing multiple meaningful
components. When parsed, a <code>MIMEType</code> object is returned containing
properties for each of these components.</p>
<h4>Constructor: <code>new MIMEType(input)</code><span><a class="mark" href="#all_util_constructor-new-mimetypeinput" id="all_util_constructor-new-mimetypeinput">#</a></span><a aria-hidden="true" class="legacy" id="util_constructor_new_mimetype_input"></a></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 input MIME to parse</li>
</ul>
<p>Creates a new <code>MIMEType</code> object by parsing the <code>input</code>.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">MIMEType</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;

<span class="hljs-keyword">const</span> myMIME = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEType</span>(<span class="hljs-string">'text/plain'</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MIMEType</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

<span class="hljs-keyword">const</span> myMIME = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEType</span>(<span class="hljs-string">'text/plain'</span>);</code><button class="copy-button">copy</button></pre>
<p>A <code>TypeError</code> will be thrown if the <code>input</code> is not a valid MIME. Note
that an effort will be made to coerce the given values into strings. For
instance:</p>

<pre class="with-62-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">MIMEType</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;
<span class="hljs-keyword">const</span> myMIME = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEType</span>({ <span class="hljs-attr">toString</span>: <span class="hljs-function">() =></span> <span class="hljs-string">'text/plain'</span> });
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">String</span>(myMIME));
<span class="hljs-comment">// Prints: text/plain</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MIMEType</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">const</span> myMIME = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEType</span>({ <span class="hljs-attr">toString</span>: <span class="hljs-function">() =></span> <span class="hljs-string">'text/plain'</span> });
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">String</span>(myMIME));
<span class="hljs-comment">// Prints: text/plain</span></code><button class="copy-button">copy</button></pre>
<h4><code>mime.type</code><span><a class="mark" href="#all_util_mimetype" id="all_util_mimetype">#</a></span><a aria-hidden="true" class="legacy" id="util_mime_type"></a></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 type portion of the MIME.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">MIMEType</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;

<span class="hljs-keyword">const</span> myMIME = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEType</span>(<span class="hljs-string">'text/javascript'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myMIME.<span class="hljs-property">type</span>);
<span class="hljs-comment">// Prints: text</span>
myMIME.<span class="hljs-property">type</span> = <span class="hljs-string">'application'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myMIME.<span class="hljs-property">type</span>);
<span class="hljs-comment">// Prints: application</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">String</span>(myMIME));
<span class="hljs-comment">// Prints: application/javascript</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MIMEType</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

<span class="hljs-keyword">const</span> myMIME = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEType</span>(<span class="hljs-string">'text/javascript'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myMIME.<span class="hljs-property">type</span>);
<span class="hljs-comment">// Prints: text</span>
myMIME.<span class="hljs-property">type</span> = <span class="hljs-string">'application'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myMIME.<span class="hljs-property">type</span>);
<span class="hljs-comment">// Prints: application</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">String</span>(myMIME));
<span class="hljs-comment">// Prints: application/javascript</span></code><button class="copy-button">copy</button></pre>
<h4><code>mime.subtype</code><span><a class="mark" href="#all_util_mimesubtype" id="all_util_mimesubtype">#</a></span><a aria-hidden="true" class="legacy" id="util_mime_subtype"></a></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 subtype portion of the MIME.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">MIMEType</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;

<span class="hljs-keyword">const</span> myMIME = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEType</span>(<span class="hljs-string">'text/ecmascript'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myMIME.<span class="hljs-property">subtype</span>);
<span class="hljs-comment">// Prints: ecmascript</span>
myMIME.<span class="hljs-property">subtype</span> = <span class="hljs-string">'javascript'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myMIME.<span class="hljs-property">subtype</span>);
<span class="hljs-comment">// Prints: javascript</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">String</span>(myMIME));
<span class="hljs-comment">// Prints: text/javascript</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MIMEType</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

<span class="hljs-keyword">const</span> myMIME = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEType</span>(<span class="hljs-string">'text/ecmascript'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myMIME.<span class="hljs-property">subtype</span>);
<span class="hljs-comment">// Prints: ecmascript</span>
myMIME.<span class="hljs-property">subtype</span> = <span class="hljs-string">'javascript'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myMIME.<span class="hljs-property">subtype</span>);
<span class="hljs-comment">// Prints: javascript</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">String</span>(myMIME));
<span class="hljs-comment">// Prints: text/javascript</span></code><button class="copy-button">copy</button></pre>
<h4><code>mime.essence</code><span><a class="mark" href="#all_util_mimeessence" id="all_util_mimeessence">#</a></span><a aria-hidden="true" class="legacy" id="util_mime_essence"></a></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 essence of the MIME. This property is read only.
Use <code>mime.type</code> or <code>mime.subtype</code> to alter the MIME.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">MIMEType</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;

<span class="hljs-keyword">const</span> myMIME = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEType</span>(<span class="hljs-string">'text/javascript;key=value'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myMIME.<span class="hljs-property">essence</span>);
<span class="hljs-comment">// Prints: text/javascript</span>
myMIME.<span class="hljs-property">type</span> = <span class="hljs-string">'application'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myMIME.<span class="hljs-property">essence</span>);
<span class="hljs-comment">// Prints: application/javascript</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">String</span>(myMIME));
<span class="hljs-comment">// Prints: application/javascript;key=value</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MIMEType</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

<span class="hljs-keyword">const</span> myMIME = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEType</span>(<span class="hljs-string">'text/javascript;key=value'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myMIME.<span class="hljs-property">essence</span>);
<span class="hljs-comment">// Prints: text/javascript</span>
myMIME.<span class="hljs-property">type</span> = <span class="hljs-string">'application'</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myMIME.<span class="hljs-property">essence</span>);
<span class="hljs-comment">// Prints: application/javascript</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">String</span>(myMIME));
<span class="hljs-comment">// Prints: application/javascript;key=value</span></code><button class="copy-button">copy</button></pre>
<h4><code>mime.params</code><span><a class="mark" href="#all_util_mimeparams" id="all_util_mimeparams">#</a></span><a aria-hidden="true" class="legacy" id="util_mime_params"></a></h4>
<ul>
<li><a href="#all_util_class-utilmimeparams" class="type">&#x3C;MIMEParams></a></li>
</ul>
<p>Gets the <a href="#all_util_class-utilmimeparams"><code>MIMEParams</code></a> object representing the
parameters of the MIME. This property is read-only. See
<a href="#all_util_class-utilmimeparams"><code>MIMEParams</code></a> documentation for details.</p>
<h4><code>mime.toString()</code><span><a class="mark" href="#all_util_mimetostring" id="all_util_mimetostring">#</a></span><a aria-hidden="true" class="legacy" id="util_mime_tostring"></a></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>MIMEType</code> object returns the serialized MIME.</p>
<p>Because of the need for standard compliance, this method does not allow users
to customize the serialization process of the MIME.</p>
<h4><code>mime.toJSON()</code><span><a class="mark" href="#all_util_mimetojson" id="all_util_mimetojson">#</a></span><a aria-hidden="true" class="legacy" id="util_mime_tojson"></a></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>Alias for <a href="#all_util_mimetostring"><code>mime.toString()</code></a>.</p>
<p>This method is automatically called when an <code>MIMEType</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 class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">MIMEType</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;

<span class="hljs-keyword">const</span> myMIMES = [
  <span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEType</span>(<span class="hljs-string">'image/png'</span>),
  <span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEType</span>(<span class="hljs-string">'image/gif'</span>),
];
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(myMIMES));
<span class="hljs-comment">// Prints: ["image/png", "image/gif"]</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MIMEType</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

<span class="hljs-keyword">const</span> myMIMES = [
  <span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEType</span>(<span class="hljs-string">'image/png'</span>),
  <span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEType</span>(<span class="hljs-string">'image/gif'</span>),
];
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(myMIMES));
<span class="hljs-comment">// Prints: ["image/png", "image/gif"]</span></code><button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>util.MIMEParams</code><span><a class="mark" href="#all_util_class-utilmimeparams" id="all_util_class-utilmimeparams">#</a></span><a aria-hidden="true" class="legacy" id="util_class_util_mimeparams"></a></h3>
<div class="api_metadata">
<span>Added in: v19.1.0, v18.13.0</span>
</div>
<p>The <code>MIMEParams</code> API provides read and write access to the parameters of a
<code>MIMEType</code>.</p>
<h4>Constructor: <code>new MIMEParams()</code><span><a class="mark" href="#all_util_constructor-new-mimeparams" id="all_util_constructor-new-mimeparams">#</a></span><a aria-hidden="true" class="legacy" id="util_constructor_new_mimeparams"></a></h4>
<p>Creates a new <code>MIMEParams</code> object by with empty parameters</p>

<pre class="with-44-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">MIMEParams</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;

<span class="hljs-keyword">const</span> myParams = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEParams</span>();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MIMEParams</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

<span class="hljs-keyword">const</span> myParams = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEParams</span>();</code><button class="copy-button">copy</button></pre>
<h4><code>mimeParams.delete(name)</code><span><a class="mark" href="#all_util_mimeparamsdeletename" id="all_util_mimeparamsdeletename">#</a></span><a aria-hidden="true" class="legacy" id="util_mimeparams_delete_name"></a></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>mimeParams.entries()</code><span><a class="mark" href="#all_util_mimeparamsentries" id="all_util_mimeparamsentries">#</a></span><a aria-hidden="true" class="legacy" id="util_mimeparams_entries"></a></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 iterator over each of the name-value pairs in the parameters.
Each item of the iterator is a JavaScript <code>Array</code>. The first item of the array
is the <code>name</code>, the second item of the array is the <code>value</code>.</p>
<h4><code>mimeParams.get(name)</code><span><a class="mark" href="#all_util_mimeparamsgetname" id="all_util_mimeparamsgetname">#</a></span><a aria-hidden="true" class="legacy" id="util_mimeparams_get_name"></a></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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Null_type" class="type">&#x3C;null></a> A string 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>mimeParams.has(name)</code><span><a class="mark" href="#all_util_mimeparamshasname" id="all_util_mimeparamshasname">#</a></span><a aria-hidden="true" class="legacy" id="util_mimeparams_has_name"></a></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>mimeParams.keys()</code><span><a class="mark" href="#all_util_mimeparamskeys" id="all_util_mimeparamskeys">#</a></span><a aria-hidden="true" class="legacy" id="util_mimeparams_keys"></a></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 iterator over the names of each name-value pair.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">MIMEType</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;

<span class="hljs-keyword">const</span> { params } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEType</span>(<span class="hljs-string">'text/plain;foo=0;bar=1'</span>);
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> name <span class="hljs-keyword">of</span> params.<span class="hljs-title function_">keys</span>()) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(name);
}
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   foo</span>
<span class="hljs-comment">//   bar</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MIMEType</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

<span class="hljs-keyword">const</span> { params } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEType</span>(<span class="hljs-string">'text/plain;foo=0;bar=1'</span>);
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> name <span class="hljs-keyword">of</span> params.<span class="hljs-title function_">keys</span>()) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(name);
}
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   foo</span>
<span class="hljs-comment">//   bar</span></code><button class="copy-button">copy</button></pre>
<h4><code>mimeParams.set(name, value)</code><span><a class="mark" href="#all_util_mimeparamssetname-value" id="all_util_mimeparamssetname-value">#</a></span><a aria-hidden="true" class="legacy" id="util_mimeparams_set_name_value"></a></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>MIMEParams</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>.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">MIMEType</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;

<span class="hljs-keyword">const</span> { params } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEType</span>(<span class="hljs-string">'text/plain;foo=0;bar=1'</span>);
params.<span class="hljs-title function_">set</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-string">'def'</span>);
params.<span class="hljs-title function_">set</span>(<span class="hljs-string">'baz'</span>, <span class="hljs-string">'xyz'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(params.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: foo=def;bar=1;baz=xyz</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MIMEType</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

<span class="hljs-keyword">const</span> { params } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEType</span>(<span class="hljs-string">'text/plain;foo=0;bar=1'</span>);
params.<span class="hljs-title function_">set</span>(<span class="hljs-string">'foo'</span>, <span class="hljs-string">'def'</span>);
params.<span class="hljs-title function_">set</span>(<span class="hljs-string">'baz'</span>, <span class="hljs-string">'xyz'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(params.<span class="hljs-title function_">toString</span>());
<span class="hljs-comment">// Prints: foo=def;bar=1;baz=xyz</span></code><button class="copy-button">copy</button></pre>
<h4><code>mimeParams.values()</code><span><a class="mark" href="#all_util_mimeparamsvalues" id="all_util_mimeparamsvalues">#</a></span><a aria-hidden="true" class="legacy" id="util_mimeparams_values"></a></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 iterator over the values of each name-value pair.</p>
<h4><code>mimeParams[@@iterator]()</code><span><a class="mark" href="#all_util_mimeparamsiterator" id="all_util_mimeparamsiterator">#</a></span><a aria-hidden="true" class="legacy" id="util_mimeparams_iterator"></a></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>Alias for <a href="#all_util_mimeparamsentries"><code>mimeParams.entries()</code></a>.</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">MIMEType</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;

<span class="hljs-keyword">const</span> { params } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEType</span>(<span class="hljs-string">'text/plain;foo=bar;xyz=baz'</span>);
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> [name, value] <span class="hljs-keyword">of</span> params) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(name, value);
}
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   foo bar</span>
<span class="hljs-comment">//   xyz baz</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MIMEType</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

<span class="hljs-keyword">const</span> { params } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MIMEType</span>(<span class="hljs-string">'text/plain;foo=bar;xyz=baz'</span>);
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> [name, value] <span class="hljs-keyword">of</span> params) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(name, value);
}
<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   foo bar</span>
<span class="hljs-comment">//   xyz baz</span></code><button class="copy-button">copy</button></pre>
</section><section><h3><code>util.parseArgs([config])</code><span><a class="mark" href="#all_util_utilparseargsconfig" id="all_util_utilparseargsconfig">#</a></span><a aria-hidden="true" class="legacy" id="util_util_parseargs_config"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.16.0</td>
<td><p>add support for allowing negative options in input <code>config</code>.</p></td></tr>
<tr><td>v20.0.0</td>
<td><p>The API is no longer experimental.</p></td></tr>
<tr><td>v18.11.0, v16.19.0</td>
<td><p>Add support for default values in input <code>config</code>.</p></td></tr>
<tr><td>v18.7.0, v16.17.0</td>
<td><p>add support for returning detailed parse information using <code>tokens</code> in input <code>config</code> and returned properties.</p></td></tr>
<tr><td>v18.3.0, v16.17.0</td>
<td><p><span>Added in: v18.3.0, v16.17.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>
<p><code>config</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Used to provide arguments for parsing and to configure
the parser. <code>config</code> supports the following properties:</p>
<ul>
<li><code>args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> array of argument strings. <strong>Default:</strong> <code>process.argv</code>
with <code>execPath</code> and <code>filename</code> removed.</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> Used to describe arguments known to the parser.
Keys of <code>options</code> are the long names of options and values are an
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> accepting the following properties:
<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> Type of argument, which must be either <code>boolean</code> or <code>string</code>.</li>
<li><code>multiple</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Whether this option can be provided multiple
times. If <code>true</code>, all values will be collected in an array. If
<code>false</code>, values for the option are last-wins. <strong>Default:</strong> <code>false</code>.</li>
<li><code>short</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> A single character alias for the option.</li>
<li><code>default</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#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#Boolean_type" class="type">&#x3C;boolean[]></a> The default option
value when it is not set by args. It must be of the same type as the
<code>type</code> property. When <code>multiple</code> is <code>true</code>, it must be an array.</li>
</ul>
</li>
<li><code>strict</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Should an error be thrown when unknown arguments
are encountered, or when arguments are passed that do not match the
<code>type</code> configured in <code>options</code>.
<strong>Default:</strong> <code>true</code>.</li>
<li><code>allowPositionals</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Whether this command accepts positional
arguments.
<strong>Default:</strong> <code>false</code> if <code>strict</code> is <code>true</code>, otherwise <code>true</code>.</li>
<li><code>allowNegative</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>, allows explicitly setting boolean
options to <code>false</code> by prefixing the option name with <code>--no-</code>.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>tokens</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> Return the parsed tokens. This is useful for extending
the built-in behavior, from adding additional checks through to reprocessing
the tokens in different ways.
<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> The parsed command line arguments:</p>
<ul>
<li><code>values</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> A mapping of parsed option names with their <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a>
or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> values.</li>
<li><code>positionals</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> Positional arguments.</li>
<li><code>tokens</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#Undefined_type" class="type">&#x3C;undefined></a> See <a href="#all_util_parseargs-tokens">parseArgs tokens</a>
section. Only returned if <code>config</code> includes <code>tokens: true</code>.</li>
</ul>
</li>
</ul>
<p>Provides a higher level API for command-line argument parsing than interacting
with <code>process.argv</code> directly. Takes a specification for the expected arguments
and returns a structured object with the parsed options and positionals.</p>

<pre class="with-43-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { parseArgs } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;
<span class="hljs-keyword">const</span> args = [<span class="hljs-string">'-f'</span>, <span class="hljs-string">'--bar'</span>, <span class="hljs-string">'b'</span>];
<span class="hljs-keyword">const</span> options = {
  <span class="hljs-attr">foo</span>: {
    <span class="hljs-attr">type</span>: <span class="hljs-string">'boolean'</span>,
    <span class="hljs-attr">short</span>: <span class="hljs-string">'f'</span>,
  },
  <span class="hljs-attr">bar</span>: {
    <span class="hljs-attr">type</span>: <span class="hljs-string">'string'</span>,
  },
};
<span class="hljs-keyword">const</span> {
  values,
  positionals,
} = <span class="hljs-title function_">parseArgs</span>({ args, options });
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(values, positionals);
<span class="hljs-comment">// Prints: [Object: null prototype] { foo: true, bar: 'b' } []</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { parseArgs } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">const</span> args = [<span class="hljs-string">'-f'</span>, <span class="hljs-string">'--bar'</span>, <span class="hljs-string">'b'</span>];
<span class="hljs-keyword">const</span> options = {
  <span class="hljs-attr">foo</span>: {
    <span class="hljs-attr">type</span>: <span class="hljs-string">'boolean'</span>,
    <span class="hljs-attr">short</span>: <span class="hljs-string">'f'</span>,
  },
  <span class="hljs-attr">bar</span>: {
    <span class="hljs-attr">type</span>: <span class="hljs-string">'string'</span>,
  },
};
<span class="hljs-keyword">const</span> {
  values,
  positionals,
} = <span class="hljs-title function_">parseArgs</span>({ args, options });
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(values, positionals);
<span class="hljs-comment">// Prints: [Object: null prototype] { foo: true, bar: 'b' } []</span></code><button class="copy-button">copy</button></pre>
<h4><code>parseArgs</code> <code>tokens</code><span><a class="mark" href="#all_util_parseargs-tokens" id="all_util_parseargs-tokens">#</a></span><a aria-hidden="true" class="legacy" id="util_parseargs_tokens"></a></h4>
<p>Detailed parse information is available for adding custom behaviors by
specifying <code>tokens: true</code> in the configuration.
The returned tokens have properties describing:</p>
<ul>
<li>all tokens
<ul>
<li><code>kind</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> One of 'option', 'positional', or 'option-terminator'.</li>
<li><code>index</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Index of element in <code>args</code> containing token. So the
source argument for a token is <code>args[token.index]</code>.</li>
</ul>
</li>
<li>option tokens
<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> Long name of option.</li>
<li><code>rawName</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> How option used in args, like <code>-f</code> of <code>--foo</code>.</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#Undefined_type" class="type">&#x3C;undefined></a> Option value specified in args.
Undefined for boolean options.</li>
<li><code>inlineValue</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#Undefined_type" class="type">&#x3C;undefined></a> Whether option value specified inline,
like <code>--foo=bar</code>.</li>
</ul>
</li>
<li>positional tokens
<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> The value of the positional argument in args (i.e. <code>args[index]</code>).</li>
</ul>
</li>
<li>option-terminator token</li>
</ul>
<p>The returned tokens are in the order encountered in the input args. Options
that appear more than once in args produce a token for each use. Short option
groups like <code>-xy</code> expand to a token for each option. So <code>-xxx</code> produces
three tokens.</p>
<p>For example, to add support for a negated option like <code>--no-color</code> (which
<code>allowNegative</code> supports when the option is of <code>boolean</code> type), the returned
tokens can be reprocessed to change the value stored for the negated option.</p>

<pre class="with-43-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { parseArgs } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;

<span class="hljs-keyword">const</span> options = {
  <span class="hljs-string">'color'</span>: { <span class="hljs-attr">type</span>: <span class="hljs-string">'boolean'</span> },
  <span class="hljs-string">'no-color'</span>: { <span class="hljs-attr">type</span>: <span class="hljs-string">'boolean'</span> },
  <span class="hljs-string">'logfile'</span>: { <span class="hljs-attr">type</span>: <span class="hljs-string">'string'</span> },
  <span class="hljs-string">'no-logfile'</span>: { <span class="hljs-attr">type</span>: <span class="hljs-string">'boolean'</span> },
};
<span class="hljs-keyword">const</span> { values, tokens } = <span class="hljs-title function_">parseArgs</span>({ options, <span class="hljs-attr">tokens</span>: <span class="hljs-literal">true</span> });

<span class="hljs-comment">// Reprocess the option tokens and overwrite the returned values.</span>
tokens
  .<span class="hljs-title function_">filter</span>(<span class="hljs-function">(<span class="hljs-params">token</span>) =></span> token.<span class="hljs-property">kind</span> === <span class="hljs-string">'option'</span>)
  .<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">token</span>) =></span> {
    <span class="hljs-keyword">if</span> (token.<span class="hljs-property">name</span>.<span class="hljs-title function_">startsWith</span>(<span class="hljs-string">'no-'</span>)) {
      <span class="hljs-comment">// Store foo:false for --no-foo</span>
      <span class="hljs-keyword">const</span> positiveName = token.<span class="hljs-property">name</span>.<span class="hljs-title function_">slice</span>(<span class="hljs-number">3</span>);
      values[positiveName] = <span class="hljs-literal">false</span>;
      <span class="hljs-keyword">delete</span> values[token.<span class="hljs-property">name</span>];
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-comment">// Resave value so last one wins if both --foo and --no-foo.</span>
      values[token.<span class="hljs-property">name</span>] = token.<span class="hljs-property">value</span> ?? <span class="hljs-literal">true</span>;
    }
  });

<span class="hljs-keyword">const</span> color = values.<span class="hljs-property">color</span>;
<span class="hljs-keyword">const</span> logfile = values.<span class="hljs-property">logfile</span> ?? <span class="hljs-string">'default.log'</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>({ logfile, color });</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { parseArgs } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

<span class="hljs-keyword">const</span> options = {
  <span class="hljs-string">'color'</span>: { <span class="hljs-attr">type</span>: <span class="hljs-string">'boolean'</span> },
  <span class="hljs-string">'no-color'</span>: { <span class="hljs-attr">type</span>: <span class="hljs-string">'boolean'</span> },
  <span class="hljs-string">'logfile'</span>: { <span class="hljs-attr">type</span>: <span class="hljs-string">'string'</span> },
  <span class="hljs-string">'no-logfile'</span>: { <span class="hljs-attr">type</span>: <span class="hljs-string">'boolean'</span> },
};
<span class="hljs-keyword">const</span> { values, tokens } = <span class="hljs-title function_">parseArgs</span>({ options, <span class="hljs-attr">tokens</span>: <span class="hljs-literal">true</span> });

<span class="hljs-comment">// Reprocess the option tokens and overwrite the returned values.</span>
tokens
  .<span class="hljs-title function_">filter</span>(<span class="hljs-function">(<span class="hljs-params">token</span>) =></span> token.<span class="hljs-property">kind</span> === <span class="hljs-string">'option'</span>)
  .<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">token</span>) =></span> {
    <span class="hljs-keyword">if</span> (token.<span class="hljs-property">name</span>.<span class="hljs-title function_">startsWith</span>(<span class="hljs-string">'no-'</span>)) {
      <span class="hljs-comment">// Store foo:false for --no-foo</span>
      <span class="hljs-keyword">const</span> positiveName = token.<span class="hljs-property">name</span>.<span class="hljs-title function_">slice</span>(<span class="hljs-number">3</span>);
      values[positiveName] = <span class="hljs-literal">false</span>;
      <span class="hljs-keyword">delete</span> values[token.<span class="hljs-property">name</span>];
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-comment">// Resave value so last one wins if both --foo and --no-foo.</span>
      values[token.<span class="hljs-property">name</span>] = token.<span class="hljs-property">value</span> ?? <span class="hljs-literal">true</span>;
    }
  });

<span class="hljs-keyword">const</span> color = values.<span class="hljs-property">color</span>;
<span class="hljs-keyword">const</span> logfile = values.<span class="hljs-property">logfile</span> ?? <span class="hljs-string">'default.log'</span>;

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>({ logfile, color });</code><button class="copy-button">copy</button></pre>
<p>Example usage showing negated options, and when an option is used
multiple ways then last one wins.</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node negate.js</span>
{ logfile: 'default.log', color: undefined }
<span class="hljs-meta prompt_">$ </span><span class="language-bash">node negate.js --no-logfile --no-color</span>
{ logfile: false, color: false }
<span class="hljs-meta prompt_">$ </span><span class="language-bash">node negate.js --logfile=test.log --color</span>
{ logfile: 'test.log', color: true }
<span class="hljs-meta prompt_">$ </span><span class="language-bash">node negate.js --no-logfile --logfile=test.log --color --no-color</span>
{ logfile: 'test.log', color: false }</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>util.parseEnv(content)</code><span><a class="mark" href="#all_util_utilparseenvcontent" id="all_util_utilparseenvcontent">#</a></span><a aria-hidden="true" class="legacy" id="util_util_parseenv_content"></a></h3>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active development</div><p></p>
<div class="api_metadata">
<span>Added in: v20.12.0</span>
</div>
<ul>
<li><code>content</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 raw contents of a <code>.env</code> file.</p>
<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>Given an example <code>.env</code> file:</p>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { parseEnv } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

<span class="hljs-title function_">parseEnv</span>(<span class="hljs-string">'HELLO=world\nHELLO=oh my\n'</span>);
<span class="hljs-comment">// Returns: { HELLO: 'oh my' }</span></code><code class="language-js mjs"><span class="hljs-keyword">import</span> { parseEnv } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;

<span class="hljs-title function_">parseEnv</span>(<span class="hljs-string">'HELLO=world\nHELLO=oh my\n'</span>);
<span class="hljs-comment">// Returns: { HELLO: 'oh my' }</span></code><button class="copy-button">copy</button></pre>
</section><section><h3><code>util.promisify(original)</code><span><a class="mark" href="#all_util_utilpromisifyoriginal" id="all_util_utilpromisifyoriginal">#</a></span><a aria-hidden="true" class="legacy" id="util_util_promisify_original"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.8.0</td>
<td><p>Calling <code>promisify</code> on a function that returns a <code>Promise</code> is deprecated.</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>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"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);

<span class="hljs-keyword">const</span> stat = util.<span class="hljs-title function_">promisify</span>(fs.<span class="hljs-property">stat</span>);
<span class="hljs-title function_">stat</span>(<span class="hljs-string">'.'</span>).<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">stats</span>) =></span> {
  <span class="hljs-comment">// Do something with `stats`</span>
}).<span class="hljs-title function_">catch</span>(<span class="hljs-function">(<span class="hljs-params">error</span>) =></span> {
  <span class="hljs-comment">// Handle the error.</span>
});</code> <button class="copy-button">copy</button></pre>
<p>Or, equivalently using <code>async function</code>s:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);

<span class="hljs-keyword">const</span> stat = util.<span class="hljs-title function_">promisify</span>(fs.<span class="hljs-property">stat</span>);

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">callStat</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">const</span> stats = <span class="hljs-keyword">await</span> <span class="hljs-title function_">stat</span>(<span class="hljs-string">'.'</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`This directory is owned by <span class="hljs-subst">${stats.uid}</span>`</span>);
}

<span class="hljs-title function_">callStat</span>();</code> <button class="copy-button">copy</button></pre>
<p>If there is an <code>original[util.promisify.custom]</code> property present, <code>promisify</code>
will return its value, see <a href="#all_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"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

<span class="hljs-keyword">class</span> <span class="hljs-title class_">Foo</span> {
  <span class="hljs-title function_">constructor</span>(<span class="hljs-params"></span>) {
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">a</span> = <span class="hljs-number">42</span>;
  }

  <span class="hljs-title function_">bar</span>(<span class="hljs-params">callback</span>) {
    <span class="hljs-title function_">callback</span>(<span class="hljs-literal">null</span>, <span class="hljs-variable language_">this</span>.<span class="hljs-property">a</span>);
  }
}

<span class="hljs-keyword">const</span> foo = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Foo</span>();

<span class="hljs-keyword">const</span> naiveBar = util.<span class="hljs-title function_">promisify</span>(foo.<span class="hljs-property">bar</span>);
<span class="hljs-comment">// TypeError: Cannot read property 'a' of undefined</span>
<span class="hljs-comment">// naiveBar().then(a => console.log(a));</span>

naiveBar.<span class="hljs-title function_">call</span>(foo).<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">a</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(a)); <span class="hljs-comment">// '42'</span>

<span class="hljs-keyword">const</span> bindBar = naiveBar.<span class="hljs-title function_">bind</span>(foo);
<span class="hljs-title function_">bindBar</span>().<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">a</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(a)); <span class="hljs-comment">// '42'</span></code> <button class="copy-button">copy</button></pre>
<h4>Custom promisified functions<span><a class="mark" href="#all_util_custom-promisified-functions" id="all_util_custom-promisified-functions">#</a></span><a aria-hidden="true" class="legacy" id="util_custom_promisified_functions"></a></h4>
<p>Using the <code>util.promisify.custom</code> symbol one can override the return value of
<a href="#all_util_utilpromisifyoriginal"><code>util.promisify()</code></a>:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

<span class="hljs-keyword">function</span> <span class="hljs-title function_">doSomething</span>(<span class="hljs-params">foo, callback</span>) {
  <span class="hljs-comment">// ...</span>
}

doSomething[util.<span class="hljs-property">promisify</span>.<span class="hljs-property">custom</span>] = <span class="hljs-function">(<span class="hljs-params">foo</span>) =></span> {
  <span class="hljs-keyword">return</span> <span class="hljs-title function_">getPromiseSomehow</span>();
};

<span class="hljs-keyword">const</span> promisified = util.<span class="hljs-title function_">promisify</span>(doSomething);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(promisified === doSomething[util.<span class="hljs-property">promisify</span>.<span class="hljs-property">custom</span>]);
<span class="hljs-comment">// prints 'true'</span></code> <button class="copy-button">copy</button></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.<span class="hljs-property">promisify</span>.<span class="hljs-property">custom</span>] = <span class="hljs-function">(<span class="hljs-params">foo</span>) =></span> {
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =></span> {
    <span class="hljs-title function_">doSomething</span>(foo, resolve, reject);
  });
};</code> <button class="copy-button">copy</button></pre>
<p>If <code>promisify.custom</code> is defined but is not a function, <code>promisify()</code> will
throw an error.</p>
<h4><code>util.promisify.custom</code><span><a class="mark" href="#all_util_utilpromisifycustom" id="all_util_utilpromisifycustom">#</a></span><a aria-hidden="true" class="legacy" id="util_util_promisify_custom"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v13.12.0, 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="#all_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"><span class="hljs-keyword">const</span> kCustomPromisifiedSymbol = <span class="hljs-title class_">Symbol</span>.<span class="hljs-title function_">for</span>(<span class="hljs-string">'nodejs.util.promisify.custom'</span>);

doSomething[kCustomPromisifiedSymbol] = <span class="hljs-function">(<span class="hljs-params">foo</span>) =></span> {
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =></span> {
    <span class="hljs-title function_">doSomething</span>(foo, resolve, reject);
  });
};</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>util.stripVTControlCharacters(str)</code><span><a class="mark" href="#all_util_utilstripvtcontrolcharactersstr" id="all_util_utilstripvtcontrolcharactersstr">#</a></span><a aria-hidden="true" class="legacy" id="util_util_stripvtcontrolcharacters_str"></a></h3>
<div class="api_metadata">
<span>Added in: v16.11.0</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>
<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 <code>str</code> with any ANSI escape codes removed.</p>
<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(util.<span class="hljs-title function_">stripVTControlCharacters</span>(<span class="hljs-string">'\u001B[4mvalue\u001B[0m'</span>));
<span class="hljs-comment">// Prints "value"</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>util.styleText(format, text[, options])</code><span><a class="mark" href="#all_util_utilstyletextformat-text-options" id="all_util_utilstyletextformat-text-options">#</a></span><a aria-hidden="true" class="legacy" id="util_util_styletext_format_text_options"></a></h3>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active development</div><p></p>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.18.0</td>
<td><p>Respect isTTY and environment variables such as NO_COLORS, NODE_DISABLE_COLORS, and FORCE_COLOR.</p></td></tr>
<tr><td>v20.12.0</td>
<td><p><span>Added in: v20.12.0</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 href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type">&#x3C;Array></a> A text format or an Array
of text formats defined in <code>util.inspect.colors</code>.</li>
<li><code>text</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> The text to to be formatted.</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>
<ul>
<li><code>validateStream</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> When true, <code>stream</code> is checked to see if it can handle colors. <strong>Default:</strong> <code>true</code>.</li>
<li><code>stream</code> <a href="#all_stream_stream" class="type">&#x3C;Stream></a> A stream that will be validated if it can be colored. <strong>Default:</strong> <code>process.stdout</code>.</li>
</ul>
</li>
</ul>
<p>This function returns a formatted text considering the <code>format</code> passed
for printing in a terminal. It is aware of the terminal's capabilities
and acts according to the configuration set via <code>NO_COLORS</code>,
<code>NODE_DISABLE_COLORS</code> and <code>FORCE_COLOR</code> environment variables.</p>

<pre class="with-43-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { styleText } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;
<span class="hljs-keyword">import</span> { stderr } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-keyword">const</span> successMessage = <span class="hljs-title function_">styleText</span>(<span class="hljs-string">'green'</span>, <span class="hljs-string">'Success!'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(successMessage);

<span class="hljs-keyword">const</span> errorMessage = <span class="hljs-title function_">styleText</span>(
  <span class="hljs-string">'red'</span>,
  <span class="hljs-string">'Error! Error!'</span>,
  <span class="hljs-comment">// Validate if process.stderr has TTY</span>
  { <span class="hljs-attr">stream</span>: stderr },
);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(successMessage);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { styleText } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">const</span> { stderr } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);

<span class="hljs-keyword">const</span> successMessage = <span class="hljs-title function_">styleText</span>(<span class="hljs-string">'green'</span>, <span class="hljs-string">'Success!'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(successMessage);

<span class="hljs-keyword">const</span> errorMessage = <span class="hljs-title function_">styleText</span>(
  <span class="hljs-string">'red'</span>,
  <span class="hljs-string">'Error! Error!'</span>,
  <span class="hljs-comment">// Validate if process.stderr has TTY</span>
  { <span class="hljs-attr">stream</span>: stderr },
);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(successMessage);</code><button class="copy-button">copy</button></pre>
<p><code>util.inspect.colors</code> also provides text formats such as <code>italic</code>, and
<code>underline</code> and you can combine both:</p>
<pre><code class="language-js cjs"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(
  util.<span class="hljs-title function_">styleText</span>([<span class="hljs-string">'underline'</span>, <span class="hljs-string">'italic'</span>], <span class="hljs-string">'My italic underlined message'</span>),
);</code> <button class="copy-button">copy</button></pre>
<p>When passing an array of formats, the order of the format applied
is left to right so the following style might overwrite the previous one.</p>
<pre><code class="language-js cjs"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(
  util.<span class="hljs-title function_">styleText</span>([<span class="hljs-string">'red'</span>, <span class="hljs-string">'green'</span>], <span class="hljs-string">'text'</span>), <span class="hljs-comment">// green</span>
);</code> <button class="copy-button">copy</button></pre>
<p>The full list of formats can be found in <a href="#all_util_modifiers">modifiers</a>.</p>
</section><section><h3>Class: <code>util.TextDecoder</code><span><a class="mark" href="#all_util_class-utiltextdecoder" id="all_util_class-utiltextdecoder">#</a></span><a aria-hidden="true" class="legacy" id="util_class_util_textdecoder"></a></h3>
<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"><span class="hljs-keyword">const</span> decoder = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TextDecoder</span>();
<span class="hljs-keyword">const</span> u8arr = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>([<span class="hljs-number">72</span>, <span class="hljs-number">101</span>, <span class="hljs-number">108</span>, <span class="hljs-number">108</span>, <span class="hljs-number">111</span>]);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(decoder.<span class="hljs-title function_">decode</span>(u8arr)); <span class="hljs-comment">// Hello</span></code> <button class="copy-button">copy</button></pre>
<h4>WHATWG supported encodings<span><a class="mark" href="#all_util_whatwg-supported-encodings" id="all_util_whatwg-supported-encodings">#</a></span><a aria-hidden="true" class="legacy" id="util_whatwg_supported_encodings"></a></h4>
<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.
(see <a href="intl.html">Internationalization</a>)</p>
<h5>Encodings supported by default (with full ICU data)<span><a class="mark" href="#all_util_encodings-supported-by-default-with-full-icu-data" id="all_util_encodings-supported-by-default-with-full-icu-data">#</a></span><a aria-hidden="true" class="legacy" id="util_encodings_supported_by_default_with_full_icu_data"></a></h5>

















































































































































<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>
<h5>Encodings supported when Node.js is built with the <code>small-icu</code> option<span><a class="mark" href="#all_util_encodings-supported-when-nodejs-is-built-with-the-small-icu-option" id="all_util_encodings-supported-when-nodejs-is-built-with-the-small-icu-option">#</a></span><a aria-hidden="true" class="legacy" id="util_encodings_supported_when_node_js_is_built_with_the_small_icu_option"></a></h5>





















<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>
<h5>Encodings supported when ICU is disabled<span><a class="mark" href="#all_util_encodings-supported-when-icu-is-disabled" id="all_util_encodings-supported-when-icu-is-disabled">#</a></span><a aria-hidden="true" class="legacy" id="util_encodings_supported_when_icu_is_disabled"></a></h5>

















<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>
<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>
<h4><code>new TextDecoder([encoding[, options]])</code><span><a class="mark" href="#all_util_new-textdecoderencoding-options" id="all_util_new-textdecoderencoding-options">#</a></span><a aria-hidden="true" class="legacy" id="util_new_textdecoder_encoding_options"></a></h4>
<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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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 not supported when ICU is disabled
(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 a 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>
<h4><code>textDecoder.decode([input[, options]])</code><span><a class="mark" href="#all_util_textdecoderdecodeinput-options" id="all_util_textdecoderdecodeinput-options">#</a></span><a aria-hidden="true" class="legacy" id="util_textdecoder_decode_input_options"></a></h4>
<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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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>
<h4><code>textDecoder.encoding</code><span><a class="mark" href="#all_util_textdecoderencoding" id="all_util_textdecoderencoding">#</a></span><a aria-hidden="true" class="legacy" id="util_textdecoder_encoding"></a></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>The encoding supported by the <code>TextDecoder</code> instance.</p>
<h4><code>textDecoder.fatal</code><span><a class="mark" href="#all_util_textdecoderfatal" id="all_util_textdecoderfatal">#</a></span><a aria-hidden="true" class="legacy" id="util_textdecoder_fatal"></a></h4>
<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>
<h4><code>textDecoder.ignoreBOM</code><span><a class="mark" href="#all_util_textdecoderignorebom" id="all_util_textdecoderignorebom">#</a></span><a aria-hidden="true" class="legacy" id="util_textdecoder_ignorebom"></a></h4>
<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>
</section><section><h3>Class: <code>util.TextEncoder</code><span><a class="mark" href="#all_util_class-utiltextencoder" id="all_util_class-utiltextencoder">#</a></span><a aria-hidden="true" class="legacy" id="util_class_util_textencoder"></a></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>
<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"><span class="hljs-keyword">const</span> encoder = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TextEncoder</span>();
<span class="hljs-keyword">const</span> uint8array = encoder.<span class="hljs-title function_">encode</span>(<span class="hljs-string">'this is some data'</span>);</code> <button class="copy-button">copy</button></pre>
<p>The <code>TextEncoder</code> class is also available on the global object.</p>
<h4><code>textEncoder.encode([input])</code><span><a class="mark" href="#all_util_textencoderencodeinput" id="all_util_textencoderencodeinput">#</a></span><a aria-hidden="true" class="legacy" id="util_textencoder_encode_input"></a></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 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>
<h4><code>textEncoder.encodeInto(src, dest)</code><span><a class="mark" href="#all_util_textencoderencodeintosrc-dest" id="all_util_textencoderencodeintosrc-dest">#</a></span><a aria-hidden="true" class="legacy" id="util_textencoder_encodeinto_src_dest"></a></h4>
<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>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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"><span class="hljs-keyword">const</span> encoder = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TextEncoder</span>();
<span class="hljs-keyword">const</span> src = <span class="hljs-string">'this is some data'</span>;
<span class="hljs-keyword">const</span> dest = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(<span class="hljs-number">10</span>);
<span class="hljs-keyword">const</span> { read, written } = encoder.<span class="hljs-title function_">encodeInto</span>(src, dest);</code> <button class="copy-button">copy</button></pre>
<h4><code>textEncoder.encoding</code><span><a class="mark" href="#all_util_textencoderencoding" id="all_util_textencoderencoding">#</a></span><a aria-hidden="true" class="legacy" id="util_textencoder_encoding"></a></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>The encoding supported by the <code>TextEncoder</code> instance. Always set to <code>'utf-8'</code>.</p>
</section><section><h3><code>util.toUSVString(string)</code><span><a class="mark" href="#all_util_utiltousvstringstring" id="all_util_utiltousvstringstring">#</a></span><a aria-hidden="true" class="legacy" id="util_util_tousvstring_string"></a></h3>
<div class="api_metadata">
<span>Added in: v16.8.0, v14.18.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>Returns the <code>string</code> after replacing any surrogate code points
(or equivalently, any unpaired surrogate code units) with the
Unicode "replacement character" U+FFFD.</p>
</section><section><h3><code>util.transferableAbortController()</code><span><a class="mark" href="#all_util_utiltransferableabortcontroller" id="all_util_utiltransferableabortcontroller">#</a></span><a aria-hidden="true" class="legacy" id="util_util_transferableabortcontroller"></a></h3>
<div class="api_metadata">
<span>Added in: v18.11.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Creates and returns an <a href="#all_globals_class-abortcontroller" class="type">&#x3C;AbortController></a> instance whose <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> is marked
as transferable and can be used with <code>structuredClone()</code> or <code>postMessage()</code>.</p>
</section><section><h3><code>util.transferableAbortSignal(signal)</code><span><a class="mark" href="#all_util_utiltransferableabortsignalsignal" id="all_util_utiltransferableabortsignalsignal">#</a></span><a aria-hidden="true" class="legacy" id="util_util_transferableabortsignal_signal"></a></h3>
<div class="api_metadata">
<span>Added in: v18.11.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a></li>
<li>Returns: <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a></li>
</ul>
<p>Marks the given <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> as transferable so that it can be used with
<code>structuredClone()</code> and <code>postMessage()</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> signal = <span class="hljs-title function_">transferableAbortSignal</span>(<span class="hljs-title class_">AbortSignal</span>.<span class="hljs-title function_">timeout</span>(<span class="hljs-number">100</span>));
<span class="hljs-keyword">const</span> channel = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
channel.<span class="hljs-property">port2</span>.<span class="hljs-title function_">postMessage</span>(signal, [signal]);</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>util.aborted(signal, resource)</code><span><a class="mark" href="#all_util_utilabortedsignal-resource" id="all_util_utilabortedsignal-resource">#</a></span><a aria-hidden="true" class="legacy" id="util_util_aborted_signal_resource"></a></h3>
<div class="api_metadata">
<span>Added in: v19.7.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a></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> Any non-null entity, reference to which is held weakly.</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>Listens to abort event on the provided <code>signal</code> and
returns a promise that is fulfilled when the <code>signal</code> is
aborted. If the passed <code>resource</code> is garbage collected before the <code>signal</code> is
aborted, the returned promise shall remain pending indefinitely.</p>

<pre class="with-41-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { aborted } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

<span class="hljs-keyword">const</span> dependent = <span class="hljs-title function_">obtainSomethingAbortable</span>();

<span class="hljs-title function_">aborted</span>(dependent.<span class="hljs-property">signal</span>, dependent).<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> {
  <span class="hljs-comment">// Do something when dependent is aborted.</span>
});

dependent.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> {
  dependent.<span class="hljs-title function_">abort</span>();
});</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { aborted } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;

<span class="hljs-keyword">const</span> dependent = <span class="hljs-title function_">obtainSomethingAbortable</span>();

<span class="hljs-title function_">aborted</span>(dependent.<span class="hljs-property">signal</span>, dependent).<span class="hljs-title function_">then</span>(<span class="hljs-function">() =></span> {
  <span class="hljs-comment">// Do something when dependent is aborted.</span>
});

dependent.<span class="hljs-title function_">on</span>(<span class="hljs-string">'event'</span>, <span class="hljs-function">() =></span> {
  dependent.<span class="hljs-title function_">abort</span>();
});</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>util.types</code><span><a class="mark" href="#all_util_utiltypes" id="all_util_utiltypes">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.3.0</td>
<td><p>Exposed as <code>require('util/types')</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>
<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>
<p>The API is accessible via <code>require('node:util').types</code> or <code>require('node:util/types')</code>.</p>
<h4><code>util.types.isAnyArrayBuffer(value)</code><span><a class="mark" href="#all_util_utiltypesisanyarraybuffervalue" id="all_util_utiltypesisanyarraybuffervalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isanyarraybuffer_value"></a></h4>
<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="#all_util_utiltypesisarraybuffervalue"><code>util.types.isArrayBuffer()</code></a> and
<a href="#all_util_utiltypesissharedarraybuffervalue"><code>util.types.isSharedArrayBuffer()</code></a>.</p>
<pre><code class="language-js">util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isAnyArrayBuffer</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>());  <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isAnyArrayBuffer</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">SharedArrayBuffer</span>());  <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isArrayBufferView(value)</code><span><a class="mark" href="#all_util_utiltypesisarraybufferviewvalue" id="all_util_utiltypesisarraybufferviewvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isarraybufferview_value"></a></h4>
<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.<span class="hljs-property">types</span>.<span class="hljs-title function_">isArrayBufferView</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Int8Array</span>());  <span class="hljs-comment">// true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isArrayBufferView</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'hello world'</span>)); <span class="hljs-comment">// true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isArrayBufferView</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">DataView</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>(<span class="hljs-number">16</span>)));  <span class="hljs-comment">// true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isArrayBufferView</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>());  <span class="hljs-comment">// false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isArgumentsObject(value)</code><span><a class="mark" href="#all_util_utiltypesisargumentsobjectvalue" id="all_util_utiltypesisargumentsobjectvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isargumentsobject_value"></a></h4>
<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"><span class="hljs-keyword">function</span> <span class="hljs-title function_">foo</span>(<span class="hljs-params"></span>) {
  util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isArgumentsObject</span>(<span class="hljs-variable language_">arguments</span>);  <span class="hljs-comment">// Returns true</span>
}</code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isArrayBuffer(value)</code><span><a class="mark" href="#all_util_utiltypesisarraybuffervalue" id="all_util_utiltypesisarraybuffervalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isarraybuffer_value"></a></h4>
<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="#all_util_utiltypesisanyarraybuffervalue"><code>util.types.isAnyArrayBuffer()</code></a> for that.</p>
<pre><code class="language-js">util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isArrayBuffer</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>());  <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isArrayBuffer</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">SharedArrayBuffer</span>());  <span class="hljs-comment">// Returns false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isAsyncFunction(value)</code><span><a class="mark" href="#all_util_utiltypesisasyncfunctionvalue" id="all_util_utiltypesisasyncfunctionvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isasyncfunction_value"></a></h4>
<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.<span class="hljs-property">types</span>.<span class="hljs-title function_">isAsyncFunction</span>(<span class="hljs-keyword">function</span> <span class="hljs-title function_">foo</span>(<span class="hljs-params"></span>) {});  <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isAsyncFunction</span>(<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">foo</span>(<span class="hljs-params"></span>) {});  <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isBigInt64Array(value)</code><span><a class="mark" href="#all_util_utiltypesisbigint64arrayvalue" id="all_util_utiltypesisbigint64arrayvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isbigint64array_value"></a></h4>
<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.<span class="hljs-property">types</span>.<span class="hljs-title function_">isBigInt64Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">BigInt64Array</span>());   <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isBigInt64Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">BigUint64Array</span>());  <span class="hljs-comment">// Returns false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isBigUint64Array(value)</code><span><a class="mark" href="#all_util_utiltypesisbiguint64arrayvalue" id="all_util_utiltypesisbiguint64arrayvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isbiguint64array_value"></a></h4>
<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.<span class="hljs-property">types</span>.<span class="hljs-title function_">isBigUint64Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">BigInt64Array</span>());   <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isBigUint64Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">BigUint64Array</span>());  <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isBooleanObject(value)</code><span><a class="mark" href="#all_util_utiltypesisbooleanobjectvalue" id="all_util_utiltypesisbooleanobjectvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isbooleanobject_value"></a></h4>
<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.<span class="hljs-property">types</span>.<span class="hljs-title function_">isBooleanObject</span>(<span class="hljs-literal">false</span>);  <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isBooleanObject</span>(<span class="hljs-literal">true</span>);   <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isBooleanObject</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Boolean</span>(<span class="hljs-literal">false</span>)); <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isBooleanObject</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Boolean</span>(<span class="hljs-literal">true</span>));  <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isBooleanObject</span>(<span class="hljs-title class_">Boolean</span>(<span class="hljs-literal">false</span>)); <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isBooleanObject</span>(<span class="hljs-title class_">Boolean</span>(<span class="hljs-literal">true</span>));  <span class="hljs-comment">// Returns false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isBoxedPrimitive(value)</code><span><a class="mark" href="#all_util_utiltypesisboxedprimitivevalue" id="all_util_utiltypesisboxedprimitivevalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isboxedprimitive_value"></a></h4>
<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.<span class="hljs-property">types</span>.<span class="hljs-title function_">isBoxedPrimitive</span>(<span class="hljs-literal">false</span>); <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isBoxedPrimitive</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Boolean</span>(<span class="hljs-literal">false</span>)); <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isBoxedPrimitive</span>(<span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'foo'</span>)); <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isBoxedPrimitive</span>(<span class="hljs-title class_">Object</span>(<span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'foo'</span>))); <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isBoxedPrimitive</span>(<span class="hljs-title class_">Object</span>(<span class="hljs-title class_">BigInt</span>(<span class="hljs-number">5</span>))); <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isCryptoKey(value)</code><span><a class="mark" href="#all_util_utiltypesiscryptokeyvalue" id="all_util_utiltypesiscryptokeyvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_iscryptokey_value"></a></h4>
<div class="api_metadata">
<span>Added in: v16.2.0</span>
</div>
<ul>
<li><code>value</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>value</code> is a <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></a>, <code>false</code> otherwise.</p>
<h4><code>util.types.isDataView(value)</code><span><a class="mark" href="#all_util_utiltypesisdataviewvalue" id="all_util_utiltypesisdataviewvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isdataview_value"></a></h4>
<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"><span class="hljs-keyword">const</span> ab = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>(<span class="hljs-number">20</span>);
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isDataView</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">DataView</span>(ab));  <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isDataView</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Float64Array</span>());  <span class="hljs-comment">// Returns false</span></code> <button class="copy-button">copy</button></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>
<h4><code>util.types.isDate(value)</code><span><a class="mark" href="#all_util_utiltypesisdatevalue" id="all_util_utiltypesisdatevalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isdate_value"></a></h4>
<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.<span class="hljs-property">types</span>.<span class="hljs-title function_">isDate</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Date</span>());  <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isExternal(value)</code><span><a class="mark" href="#all_util_utiltypesisexternalvalue" id="all_util_utiltypesisexternalvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isexternal_value"></a></h4>
<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"><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;js_native_api.h></span></span>
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&#x3C;stdlib.h></span></span>
napi_value result;
<span class="hljs-type">static</span> napi_value <span class="hljs-title function_">MyNapi</span><span class="hljs-params">(napi_env env, napi_callback_info info)</span> {
  <span class="hljs-type">int</span>* raw = (<span class="hljs-type">int</span>*) <span class="hljs-built_in">malloc</span>(<span class="hljs-number">1024</span>);
  napi_status status = napi_create_external(env, (<span class="hljs-type">void</span>*) raw, <span class="hljs-literal">NULL</span>, <span class="hljs-literal">NULL</span>, &#x26;result);
  <span class="hljs-keyword">if</span> (status != napi_ok) {
    napi_throw_error(env, <span class="hljs-literal">NULL</span>, <span class="hljs-string">"napi_create_external failed"</span>);
    <span class="hljs-keyword">return</span> <span class="hljs-literal">NULL</span>;
  }
  <span class="hljs-keyword">return</span> result;
}
...
DECLARE_NAPI_PROPERTY(<span class="hljs-string">"myNapi"</span>, MyNapi)
...</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-js"><span class="hljs-keyword">const</span> native = <span class="hljs-built_in">require</span>(<span class="hljs-string">'napi_addon.node'</span>);
<span class="hljs-keyword">const</span> data = native.<span class="hljs-title function_">myNapi</span>();
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isExternal</span>(data); <span class="hljs-comment">// returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isExternal</span>(<span class="hljs-number">0</span>); <span class="hljs-comment">// returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isExternal</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">String</span>(<span class="hljs-string">'foo'</span>)); <span class="hljs-comment">// returns false</span></code> <button class="copy-button">copy</button></pre>
<p>For further information on <code>napi_create_external</code>, refer to
<a href="#all_n-api_napi_create_external"><code>napi_create_external()</code></a>.</p>
<h4><code>util.types.isFloat32Array(value)</code><span><a class="mark" href="#all_util_utiltypesisfloat32arrayvalue" id="all_util_utiltypesisfloat32arrayvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isfloat32array_value"></a></h4>
<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.<span class="hljs-property">types</span>.<span class="hljs-title function_">isFloat32Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>());  <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isFloat32Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Float32Array</span>());  <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isFloat32Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Float64Array</span>());  <span class="hljs-comment">// Returns false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isFloat64Array(value)</code><span><a class="mark" href="#all_util_utiltypesisfloat64arrayvalue" id="all_util_utiltypesisfloat64arrayvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isfloat64array_value"></a></h4>
<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.<span class="hljs-property">types</span>.<span class="hljs-title function_">isFloat64Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>());  <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isFloat64Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>());  <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isFloat64Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Float64Array</span>());  <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isGeneratorFunction(value)</code><span><a class="mark" href="#all_util_utiltypesisgeneratorfunctionvalue" id="all_util_utiltypesisgeneratorfunctionvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isgeneratorfunction_value"></a></h4>
<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.<span class="hljs-property">types</span>.<span class="hljs-title function_">isGeneratorFunction</span>(<span class="hljs-keyword">function</span> <span class="hljs-title function_">foo</span>(<span class="hljs-params"></span>) {});  <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isGeneratorFunction</span>(<span class="hljs-keyword">function</span>* <span class="hljs-title function_">foo</span>(<span class="hljs-params"></span>) {});  <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isGeneratorObject(value)</code><span><a class="mark" href="#all_util_utiltypesisgeneratorobjectvalue" id="all_util_utiltypesisgeneratorobjectvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isgeneratorobject_value"></a></h4>
<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"><span class="hljs-keyword">function</span>* <span class="hljs-title function_">foo</span>(<span class="hljs-params"></span>) {}
<span class="hljs-keyword">const</span> generator = <span class="hljs-title function_">foo</span>();
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isGeneratorObject</span>(generator);  <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isInt8Array(value)</code><span><a class="mark" href="#all_util_utiltypesisint8arrayvalue" id="all_util_utiltypesisint8arrayvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isint8array_value"></a></h4>
<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.<span class="hljs-property">types</span>.<span class="hljs-title function_">isInt8Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>());  <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isInt8Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Int8Array</span>());  <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isInt8Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Float64Array</span>());  <span class="hljs-comment">// Returns false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isInt16Array(value)</code><span><a class="mark" href="#all_util_utiltypesisint16arrayvalue" id="all_util_utiltypesisint16arrayvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isint16array_value"></a></h4>
<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.<span class="hljs-property">types</span>.<span class="hljs-title function_">isInt16Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>());  <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isInt16Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Int16Array</span>());  <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isInt16Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Float64Array</span>());  <span class="hljs-comment">// Returns false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isInt32Array(value)</code><span><a class="mark" href="#all_util_utiltypesisint32arrayvalue" id="all_util_utiltypesisint32arrayvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isint32array_value"></a></h4>
<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.<span class="hljs-property">types</span>.<span class="hljs-title function_">isInt32Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>());  <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isInt32Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Int32Array</span>());  <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isInt32Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Float64Array</span>());  <span class="hljs-comment">// Returns false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isKeyObject(value)</code><span><a class="mark" href="#all_util_utiltypesiskeyobjectvalue" id="all_util_utiltypesiskeyobjectvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_iskeyobject_value"></a></h4>
<div class="api_metadata">
<span>Added in: v16.2.0</span>
</div>
<ul>
<li><code>value</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>value</code> is a <a href="#all_crypto_class-keyobject" class="type">&#x3C;KeyObject></a>, <code>false</code> otherwise.</p>
<h4><code>util.types.isMap(value)</code><span><a class="mark" href="#all_util_utiltypesismapvalue" id="all_util_utiltypesismapvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_ismap_value"></a></h4>
<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.<span class="hljs-property">types</span>.<span class="hljs-title function_">isMap</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Map</span>());  <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isMapIterator(value)</code><span><a class="mark" href="#all_util_utiltypesismapiteratorvalue" id="all_util_utiltypesismapiteratorvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_ismapiterator_value"></a></h4>
<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"><span class="hljs-keyword">const</span> map = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Map</span>();
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isMapIterator</span>(map.<span class="hljs-title function_">keys</span>());  <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isMapIterator</span>(map.<span class="hljs-title function_">values</span>());  <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isMapIterator</span>(map.<span class="hljs-title function_">entries</span>());  <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isMapIterator</span>(map[<span class="hljs-title class_">Symbol</span>.<span class="hljs-property">iterator</span>]());  <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isModuleNamespaceObject(value)</code><span><a class="mark" href="#all_util_utiltypesismodulenamespaceobjectvalue" id="all_util_utiltypesismodulenamespaceobjectvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_ismodulenamespaceobject_value"></a></h4>
<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>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> ns <span class="hljs-keyword">from</span> <span class="hljs-string">'./a.js'</span>;

util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isModuleNamespaceObject</span>(ns);  <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isNativeError(value)</code><span><a class="mark" href="#all_util_utiltypesisnativeerrorvalue" id="all_util_utiltypesisnativeerrorvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isnativeerror_value"></a></h4>
<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 was returned by the constructor of a
<a href="https://tc39.es/ecma262/#sec-error-objects">built-in <code>Error</code> type</a>.</p>
<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isNativeError</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>()));  <span class="hljs-comment">// true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isNativeError</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>()));  <span class="hljs-comment">// true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isNativeError</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">RangeError</span>()));  <span class="hljs-comment">// true</span></code> <button class="copy-button">copy</button></pre>
<p>Subclasses of the native error types are also native errors:</p>
<pre><code class="language-js"><span class="hljs-keyword">class</span> <span class="hljs-title class_">MyError</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">Error</span> {}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isNativeError</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">MyError</span>()));  <span class="hljs-comment">// true</span></code> <button class="copy-button">copy</button></pre>
<p>A value being <code>instanceof</code> a native error class is not equivalent to <code>isNativeError()</code>
returning <code>true</code> for that value. <code>isNativeError()</code> returns <code>true</code> for errors
which come from a different <a href="https://tc39.es/ecma262/#realm">realm</a> while <code>instanceof Error</code> returns <code>false</code>
for these errors:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
<span class="hljs-keyword">const</span> context = vm.<span class="hljs-title function_">createContext</span>({});
<span class="hljs-keyword">const</span> myError = vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'new Error()'</span>, context);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isNativeError</span>(myError)); <span class="hljs-comment">// true</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myError <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">Error</span>); <span class="hljs-comment">// false</span></code> <button class="copy-button">copy</button></pre>
<p>Conversely, <code>isNativeError()</code> returns <code>false</code> for all objects which were not
returned by the constructor of a native error. That includes values
which are <code>instanceof</code> native errors:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> myError = { <span class="hljs-attr">__proto__</span>: <span class="hljs-title class_">Error</span>.<span class="hljs-property"><span class="hljs-keyword">prototype</span></span> };
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isNativeError</span>(myError)); <span class="hljs-comment">// false</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(myError <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">Error</span>); <span class="hljs-comment">// true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isNumberObject(value)</code><span><a class="mark" href="#all_util_utiltypesisnumberobjectvalue" id="all_util_utiltypesisnumberobjectvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isnumberobject_value"></a></h4>
<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.<span class="hljs-property">types</span>.<span class="hljs-title function_">isNumberObject</span>(<span class="hljs-number">0</span>);  <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isNumberObject</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Number</span>(<span class="hljs-number">0</span>));   <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isPromise(value)</code><span><a class="mark" href="#all_util_utiltypesispromisevalue" id="all_util_utiltypesispromisevalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_ispromise_value"></a></h4>
<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.<span class="hljs-property">types</span>.<span class="hljs-title function_">isPromise</span>(<span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">resolve</span>(<span class="hljs-number">42</span>));  <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isProxy(value)</code><span><a class="mark" href="#all_util_utiltypesisproxyvalue" id="all_util_utiltypesisproxyvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isproxy_value"></a></h4>
<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"><span class="hljs-keyword">const</span> target = {};
<span class="hljs-keyword">const</span> proxy = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Proxy</span>(target, {});
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isProxy</span>(target);  <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isProxy</span>(proxy);  <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isRegExp(value)</code><span><a class="mark" href="#all_util_utiltypesisregexpvalue" id="all_util_utiltypesisregexpvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isregexp_value"></a></h4>
<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.<span class="hljs-property">types</span>.<span class="hljs-title function_">isRegExp</span>(<span class="hljs-regexp">/abc/</span>);  <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isRegExp</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">RegExp</span>(<span class="hljs-string">'abc'</span>));  <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isSet(value)</code><span><a class="mark" href="#all_util_utiltypesissetvalue" id="all_util_utiltypesissetvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isset_value"></a></h4>
<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.<span class="hljs-property">types</span>.<span class="hljs-title function_">isSet</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Set</span>());  <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isSetIterator(value)</code><span><a class="mark" href="#all_util_utiltypesissetiteratorvalue" id="all_util_utiltypesissetiteratorvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_issetiterator_value"></a></h4>
<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"><span class="hljs-keyword">const</span> set = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Set</span>();
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isSetIterator</span>(set.<span class="hljs-title function_">keys</span>());  <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isSetIterator</span>(set.<span class="hljs-title function_">values</span>());  <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isSetIterator</span>(set.<span class="hljs-title function_">entries</span>());  <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isSetIterator</span>(set[<span class="hljs-title class_">Symbol</span>.<span class="hljs-property">iterator</span>]());  <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isSharedArrayBuffer(value)</code><span><a class="mark" href="#all_util_utiltypesissharedarraybuffervalue" id="all_util_utiltypesissharedarraybuffervalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_issharedarraybuffer_value"></a></h4>
<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="#all_util_utiltypesisanyarraybuffervalue"><code>util.types.isAnyArrayBuffer()</code></a> for that.</p>
<pre><code class="language-js">util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isSharedArrayBuffer</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>());  <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isSharedArrayBuffer</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">SharedArrayBuffer</span>());  <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isStringObject(value)</code><span><a class="mark" href="#all_util_utiltypesisstringobjectvalue" id="all_util_utiltypesisstringobjectvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isstringobject_value"></a></h4>
<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.<span class="hljs-property">types</span>.<span class="hljs-title function_">isStringObject</span>(<span class="hljs-string">'foo'</span>);  <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isStringObject</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">String</span>(<span class="hljs-string">'foo'</span>));   <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isSymbolObject(value)</code><span><a class="mark" href="#all_util_utiltypesissymbolobjectvalue" id="all_util_utiltypesissymbolobjectvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_issymbolobject_value"></a></h4>
<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"><span class="hljs-keyword">const</span> symbol = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'foo'</span>);
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isSymbolObject</span>(symbol);  <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isSymbolObject</span>(<span class="hljs-title class_">Object</span>(symbol));   <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isTypedArray(value)</code><span><a class="mark" href="#all_util_utiltypesistypedarrayvalue" id="all_util_utiltypesistypedarrayvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_istypedarray_value"></a></h4>
<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.<span class="hljs-property">types</span>.<span class="hljs-title function_">isTypedArray</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>());  <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isTypedArray</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>());  <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isTypedArray</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Float64Array</span>());  <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></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>
<h4><code>util.types.isUint8Array(value)</code><span><a class="mark" href="#all_util_utiltypesisuint8arrayvalue" id="all_util_utiltypesisuint8arrayvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isuint8array_value"></a></h4>
<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.<span class="hljs-property">types</span>.<span class="hljs-title function_">isUint8Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>());  <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isUint8Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>());  <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isUint8Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Float64Array</span>());  <span class="hljs-comment">// Returns false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isUint8ClampedArray(value)</code><span><a class="mark" href="#all_util_utiltypesisuint8clampedarrayvalue" id="all_util_utiltypesisuint8clampedarrayvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isuint8clampedarray_value"></a></h4>
<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.<span class="hljs-property">types</span>.<span class="hljs-title function_">isUint8ClampedArray</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>());  <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isUint8ClampedArray</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8ClampedArray</span>());  <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isUint8ClampedArray</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Float64Array</span>());  <span class="hljs-comment">// Returns false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isUint16Array(value)</code><span><a class="mark" href="#all_util_utiltypesisuint16arrayvalue" id="all_util_utiltypesisuint16arrayvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isuint16array_value"></a></h4>
<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.<span class="hljs-property">types</span>.<span class="hljs-title function_">isUint16Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>());  <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isUint16Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint16Array</span>());  <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isUint16Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Float64Array</span>());  <span class="hljs-comment">// Returns false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isUint32Array(value)</code><span><a class="mark" href="#all_util_utiltypesisuint32arrayvalue" id="all_util_utiltypesisuint32arrayvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isuint32array_value"></a></h4>
<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.<span class="hljs-property">types</span>.<span class="hljs-title function_">isUint32Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>());  <span class="hljs-comment">// Returns false</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isUint32Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint32Array</span>());  <span class="hljs-comment">// Returns true</span>
util.<span class="hljs-property">types</span>.<span class="hljs-title function_">isUint32Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Float64Array</span>());  <span class="hljs-comment">// Returns false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isWeakMap(value)</code><span><a class="mark" href="#all_util_utiltypesisweakmapvalue" id="all_util_utiltypesisweakmapvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isweakmap_value"></a></h4>
<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.<span class="hljs-property">types</span>.<span class="hljs-title function_">isWeakMap</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">WeakMap</span>());  <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.types.isWeakSet(value)</code><span><a class="mark" href="#all_util_utiltypesisweaksetvalue" id="all_util_utiltypesisweaksetvalue">#</a></span><a aria-hidden="true" class="legacy" id="util_util_types_isweakset_value"></a></h4>
<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.<span class="hljs-property">types</span>.<span class="hljs-title function_">isWeakSet</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">WeakSet</span>());  <span class="hljs-comment">// Returns true</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3>Deprecated APIs<span><a class="mark" href="#all_util_deprecated-apis" id="all_util_deprecated-apis">#</a></span><a aria-hidden="true" class="legacy" id="util_deprecated_apis"></a></h3>
<p>The following APIs are deprecated and should no longer be used. Existing
applications and modules should be updated to find alternative approaches.</p>
<h4><code>util._extend(target, source)</code><span><a class="mark" href="#all_util_util_extendtarget-source" id="all_util_util_extendtarget-source">#</a></span><a aria-hidden="true" class="legacy" id="util_util_extend_target_source"></a></h4>
<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="#all_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>
<h4><code>util.isArray(object)</code><span><a class="mark" href="#all_util_utilisarrayobject" id="all_util_utilisarrayobject">#</a></span><a aria-hidden="true" class="legacy" id="util_util_isarray_object"></a></h4>
<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="#all_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"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

util.<span class="hljs-title function_">isArray</span>([]);
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isArray</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Array</span>());
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isArray</span>({});
<span class="hljs-comment">// Returns: false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.isBoolean(object)</code><span><a class="mark" href="#all_util_utilisbooleanobject" id="all_util_utilisbooleanobject">#</a></span><a aria-hidden="true" class="legacy" id="util_util_isboolean_object"></a></h4>
<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="#all_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"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

util.<span class="hljs-title function_">isBoolean</span>(<span class="hljs-number">1</span>);
<span class="hljs-comment">// Returns: false</span>
util.<span class="hljs-title function_">isBoolean</span>(<span class="hljs-number">0</span>);
<span class="hljs-comment">// Returns: false</span>
util.<span class="hljs-title function_">isBoolean</span>(<span class="hljs-literal">false</span>);
<span class="hljs-comment">// Returns: true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.isBuffer(object)</code><span><a class="mark" href="#all_util_utilisbufferobject" id="all_util_utilisbufferobject">#</a></span><a aria-hidden="true" class="legacy" id="util_util_isbuffer_object"></a></h4>
<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="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_buffer_static-method-bufferisbufferobj"><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"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

util.<span class="hljs-title function_">isBuffer</span>({ <span class="hljs-attr">length</span>: <span class="hljs-number">0</span> });
<span class="hljs-comment">// Returns: false</span>
util.<span class="hljs-title function_">isBuffer</span>([]);
<span class="hljs-comment">// Returns: false</span>
util.<span class="hljs-title function_">isBuffer</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'hello world'</span>));
<span class="hljs-comment">// Returns: true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.isDate(object)</code><span><a class="mark" href="#all_util_utilisdateobject" id="all_util_utilisdateobject">#</a></span><a aria-hidden="true" class="legacy" id="util_util_isdate_object"></a></h4>
<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="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_util_utiltypesisdatevalue"><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"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

util.<span class="hljs-title function_">isDate</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Date</span>());
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isDate</span>(<span class="hljs-title class_">Date</span>());
<span class="hljs-comment">// false (without 'new' returns a String)</span>
util.<span class="hljs-title function_">isDate</span>({});
<span class="hljs-comment">// Returns: false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.isError(object)</code><span><a class="mark" href="#all_util_utiliserrorobject" id="all_util_utiliserrorobject">#</a></span><a aria-hidden="true" class="legacy" id="util_util_iserror_object"></a></h4>
<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="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_util_utiltypesisnativeerrorvalue"><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="#all_errors_class-error"><code>Error</code></a>. Otherwise, returns
<code>false</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

util.<span class="hljs-title function_">isError</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>());
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isError</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">TypeError</span>());
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isError</span>({ <span class="hljs-attr">name</span>: <span class="hljs-string">'Error'</span>, <span class="hljs-attr">message</span>: <span class="hljs-string">'an error occurred'</span> });
<span class="hljs-comment">// Returns: false</span></code> <button class="copy-button">copy</button></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"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">const</span> obj = { <span class="hljs-attr">name</span>: <span class="hljs-string">'Error'</span>, <span class="hljs-attr">message</span>: <span class="hljs-string">'an error occurred'</span> };

util.<span class="hljs-title function_">isError</span>(obj);
<span class="hljs-comment">// Returns: false</span>
obj[<span class="hljs-title class_">Symbol</span>.<span class="hljs-property">toStringTag</span>] = <span class="hljs-string">'Error'</span>;
util.<span class="hljs-title function_">isError</span>(obj);
<span class="hljs-comment">// Returns: true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.isFunction(object)</code><span><a class="mark" href="#all_util_utilisfunctionobject" id="all_util_utilisfunctionobject">#</a></span><a aria-hidden="true" class="legacy" id="util_util_isfunction_object"></a></h4>
<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="#all_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"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

<span class="hljs-keyword">function</span> <span class="hljs-title function_">Foo</span>(<span class="hljs-params"></span>) {}
<span class="hljs-keyword">const</span> <span class="hljs-title function_">Bar</span> = (<span class="hljs-params"></span>) => {};

util.<span class="hljs-title function_">isFunction</span>({});
<span class="hljs-comment">// Returns: false</span>
util.<span class="hljs-title function_">isFunction</span>(<span class="hljs-title class_">Foo</span>);
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isFunction</span>(<span class="hljs-title class_">Bar</span>);
<span class="hljs-comment">// Returns: true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.isNull(object)</code><span><a class="mark" href="#all_util_utilisnullobject" id="all_util_utilisnullobject">#</a></span><a aria-hidden="true" class="legacy" id="util_util_isnull_object"></a></h4>
<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="#all_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"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

util.<span class="hljs-title function_">isNull</span>(<span class="hljs-number">0</span>);
<span class="hljs-comment">// Returns: false</span>
util.<span class="hljs-title function_">isNull</span>(<span class="hljs-literal">undefined</span>);
<span class="hljs-comment">// Returns: false</span>
util.<span class="hljs-title function_">isNull</span>(<span class="hljs-literal">null</span>);
<span class="hljs-comment">// Returns: true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.isNullOrUndefined(object)</code><span><a class="mark" href="#all_util_utilisnullorundefinedobject" id="all_util_utilisnullorundefinedobject">#</a></span><a aria-hidden="true" class="legacy" id="util_util_isnullorundefined_object"></a></h4>
<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="#all_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"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

util.<span class="hljs-title function_">isNullOrUndefined</span>(<span class="hljs-number">0</span>);
<span class="hljs-comment">// Returns: false</span>
util.<span class="hljs-title function_">isNullOrUndefined</span>(<span class="hljs-literal">undefined</span>);
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isNullOrUndefined</span>(<span class="hljs-literal">null</span>);
<span class="hljs-comment">// Returns: true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.isNumber(object)</code><span><a class="mark" href="#all_util_utilisnumberobject" id="all_util_utilisnumberobject">#</a></span><a aria-hidden="true" class="legacy" id="util_util_isnumber_object"></a></h4>
<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="#all_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"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

util.<span class="hljs-title function_">isNumber</span>(<span class="hljs-literal">false</span>);
<span class="hljs-comment">// Returns: false</span>
util.<span class="hljs-title function_">isNumber</span>(<span class="hljs-title class_">Infinity</span>);
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isNumber</span>(<span class="hljs-number">0</span>);
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isNumber</span>(<span class="hljs-title class_">NaN</span>);
<span class="hljs-comment">// Returns: true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.isObject(object)</code><span><a class="mark" href="#all_util_utilisobjectobject" id="all_util_utilisobjectobject">#</a></span><a aria-hidden="true" class="legacy" id="util_util_isobject_object"></a></h4>
<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="#all_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"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

util.<span class="hljs-title function_">isObject</span>(<span class="hljs-number">5</span>);
<span class="hljs-comment">// Returns: false</span>
util.<span class="hljs-title function_">isObject</span>(<span class="hljs-literal">null</span>);
<span class="hljs-comment">// Returns: false</span>
util.<span class="hljs-title function_">isObject</span>({});
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isObject</span>(<span class="hljs-function">() =></span> {});
<span class="hljs-comment">// Returns: false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.isPrimitive(object)</code><span><a class="mark" href="#all_util_utilisprimitiveobject" id="all_util_utilisprimitiveobject">#</a></span><a aria-hidden="true" class="legacy" id="util_util_isprimitive_object"></a></h4>
<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="#all_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"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

util.<span class="hljs-title function_">isPrimitive</span>(<span class="hljs-number">5</span>);
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isPrimitive</span>(<span class="hljs-string">'foo'</span>);
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isPrimitive</span>(<span class="hljs-literal">false</span>);
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isPrimitive</span>(<span class="hljs-literal">null</span>);
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isPrimitive</span>(<span class="hljs-literal">undefined</span>);
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isPrimitive</span>({});
<span class="hljs-comment">// Returns: false</span>
util.<span class="hljs-title function_">isPrimitive</span>(<span class="hljs-function">() =></span> {});
<span class="hljs-comment">// Returns: false</span>
util.<span class="hljs-title function_">isPrimitive</span>(<span class="hljs-regexp">/^$/</span>);
<span class="hljs-comment">// Returns: false</span>
util.<span class="hljs-title function_">isPrimitive</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Date</span>());
<span class="hljs-comment">// Returns: false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.isRegExp(object)</code><span><a class="mark" href="#all_util_utilisregexpobject" id="all_util_utilisregexpobject">#</a></span><a aria-hidden="true" class="legacy" id="util_util_isregexp_object"></a></h4>
<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="#all_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"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

util.<span class="hljs-title function_">isRegExp</span>(<span class="hljs-regexp">/some regexp/</span>);
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isRegExp</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">RegExp</span>(<span class="hljs-string">'another regexp'</span>));
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isRegExp</span>({});
<span class="hljs-comment">// Returns: false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.isString(object)</code><span><a class="mark" href="#all_util_utilisstringobject" id="all_util_utilisstringobject">#</a></span><a aria-hidden="true" class="legacy" id="util_util_isstring_object"></a></h4>
<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="#all_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"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

util.<span class="hljs-title function_">isString</span>(<span class="hljs-string">''</span>);
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isString</span>(<span class="hljs-string">'foo'</span>);
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isString</span>(<span class="hljs-title class_">String</span>(<span class="hljs-string">'foo'</span>));
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isString</span>(<span class="hljs-number">5</span>);
<span class="hljs-comment">// Returns: false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.isSymbol(object)</code><span><a class="mark" href="#all_util_utilissymbolobject" id="all_util_utilissymbolobject">#</a></span><a aria-hidden="true" class="legacy" id="util_util_issymbol_object"></a></h4>
<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="#all_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"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

util.<span class="hljs-title function_">isSymbol</span>(<span class="hljs-number">5</span>);
<span class="hljs-comment">// Returns: false</span>
util.<span class="hljs-title function_">isSymbol</span>(<span class="hljs-string">'foo'</span>);
<span class="hljs-comment">// Returns: false</span>
util.<span class="hljs-title function_">isSymbol</span>(<span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'foo'</span>));
<span class="hljs-comment">// Returns: true</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.isUndefined(object)</code><span><a class="mark" href="#all_util_utilisundefinedobject" id="all_util_utilisundefinedobject">#</a></span><a aria-hidden="true" class="legacy" id="util_util_isundefined_object"></a></h4>
<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="#all_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"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

<span class="hljs-keyword">const</span> foo = <span class="hljs-literal">undefined</span>;
util.<span class="hljs-title function_">isUndefined</span>(<span class="hljs-number">5</span>);
<span class="hljs-comment">// Returns: false</span>
util.<span class="hljs-title function_">isUndefined</span>(foo);
<span class="hljs-comment">// Returns: true</span>
util.<span class="hljs-title function_">isUndefined</span>(<span class="hljs-literal">null</span>);
<span class="hljs-comment">// Returns: false</span></code> <button class="copy-button">copy</button></pre>
<h4><code>util.log(string)</code><span><a class="mark" href="#all_util_utillogstring" id="all_util_utillogstring">#</a></span><a aria-hidden="true" class="legacy" id="util_util_log_string"></a></h4>
<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="#all_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"><span class="hljs-keyword">const</span> util = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

util.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Timestamped message.'</span>);</code> <button class="copy-button">copy</button></pre></section>
        </section>
<section><h2>V8<span><a class="mark" href="#all_v8_v8" id="all_v8_v8">#</a></span><a aria-hidden="true" class="legacy" id="v8_v8"></a></h2>

<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/v8.js">lib/v8.js</a></p>
<p>The <code>node: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"><span class="hljs-keyword">const</span> v8 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:v8'</span>);</code> <button class="copy-button">copy</button></pre>
<section><h3><code>v8.cachedDataVersionTag()</code><span><a class="mark" href="#all_v8_v8cacheddataversiontag" id="all_v8_v8cacheddataversiontag">#</a></span><a aria-hidden="true" class="legacy" id="v8_v8_cacheddataversiontag"></a></h3>
<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="#all_vm_new-vmscriptcode-options"><code>vm.Script</code></a> <code>cachedData</code> buffer is compatible with this instance
of V8.</p>
<pre><code class="language-js"><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(v8.<span class="hljs-title function_">cachedDataVersionTag</span>()); <span class="hljs-comment">// 3947234607</span>
<span class="hljs-comment">// The value returned by v8.cachedDataVersionTag() is derived from the V8</span>
<span class="hljs-comment">// version, command-line flags, and detected CPU features. Test that the value</span>
<span class="hljs-comment">// does indeed update when flags are toggled.</span>
v8.<span class="hljs-title function_">setFlagsFromString</span>(<span class="hljs-string">'--allow_natives_syntax'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(v8.<span class="hljs-title function_">cachedDataVersionTag</span>()); <span class="hljs-comment">// 183726201</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>v8.getHeapCodeStatistics()</code><span><a class="mark" href="#all_v8_v8getheapcodestatistics" id="all_v8_v8getheapcodestatistics">#</a></span><a aria-hidden="true" class="legacy" id="v8_v8_getheapcodestatistics"></a></h3>
<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>Get statistics about code and its metadata in the heap, see V8
<a href="https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#a6079122af17612ef54ef3348ce170866"><code>GetHeapCodeAndMetadataStatistics</code></a> API. 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>
<li><code>cpu_profiler_metadata_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">{
  <span class="hljs-attr">code_and_metadata_size</span>: <span class="hljs-number">212208</span>,
  <span class="hljs-attr">bytecode_and_metadata_size</span>: <span class="hljs-number">161368</span>,
  <span class="hljs-attr">external_script_source_size</span>: <span class="hljs-number">1410794</span>,
  <span class="hljs-attr">cpu_profiler_metadata_size</span>: <span class="hljs-number">0</span>,
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>v8.getHeapSnapshot([options])</code><span><a class="mark" href="#all_v8_v8getheapsnapshotoptions" id="all_v8_v8getheapsnapshotoptions">#</a></span><a aria-hidden="true" class="legacy" id="v8_v8_getheapsnapshot_options"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.1.0</td>
<td><p>Support options to configure the heap snapshot.</p></td></tr>
<tr><td>v11.13.0</td>
<td><p><span>Added in: v11.13.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>exposeInternals</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If true, expose internals in the heap snapshot.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>exposeNumericValues</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If true, expose numeric values in
artificial fields. <strong>Default:</strong> <code>false</code>.</li>
</ul>
</li>
<li>
<p>Returns: <a href="#all_stream_class-streamreadable" class="type">&#x3C;stream.Readable></a> A Readable containing the V8 heap snapshot.</p>
</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. Therefore, the schema may change from one version of V8 to the next.</p>
<p>Creating a heap snapshot requires memory about twice the size of the heap at
the time the snapshot is created. This results in the risk of OOM killers
terminating the process.</p>
<p>Generating a snapshot is a synchronous operation which blocks the event loop
for a duration depending on the heap size.</p>
<pre><code class="language-js"><span class="hljs-comment">// Print heap snapshot to the console</span>
<span class="hljs-keyword">const</span> v8 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:v8'</span>);
<span class="hljs-keyword">const</span> stream = v8.<span class="hljs-title function_">getHeapSnapshot</span>();
stream.<span class="hljs-title function_">pipe</span>(process.<span class="hljs-property">stdout</span>);</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>v8.getHeapSpaceStatistics()</code><span><a class="mark" href="#all_v8_v8getheapspacestatistics" id="all_v8_v8getheapspacestatistics">#</a></span><a aria-hidden="true" class="legacy" id="v8_v8_getheapspacestatistics"></a></h3>
<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"><span class="hljs-punctuation">[</span>
  <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"space_name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"new_space"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"space_size"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">2063872</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"space_used_size"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">951112</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"space_available_size"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">80824</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"physical_space_size"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">2063872</span>
  <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
  <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"space_name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"old_space"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"space_size"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">3090560</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"space_used_size"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">2493792</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"space_available_size"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"physical_space_size"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">3090560</span>
  <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
  <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"space_name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"code_space"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"space_size"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1260160</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"space_used_size"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">644256</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"space_available_size"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">960</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"physical_space_size"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1260160</span>
  <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
  <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"space_name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"map_space"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"space_size"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1094160</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"space_used_size"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">201608</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"space_available_size"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"physical_space_size"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1094160</span>
  <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
  <span class="hljs-punctuation">{</span>
    <span class="hljs-attr">"space_name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"large_object_space"</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"space_size"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"space_used_size"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"space_available_size"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1490980608</span><span class="hljs-punctuation">,</span>
    <span class="hljs-attr">"physical_space_size"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span>
  <span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">]</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>v8.getHeapStatistics()</code><span><a class="mark" href="#all_v8_v8getheapstatistics" id="all_v8_v8getheapstatistics">#</a></span><a aria-hidden="true" class="legacy" id="v8_v8_getheapstatistics"></a></h3>
<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>
<li><code>total_global_handles_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_global_handles_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_memory</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>total_heap_size</code> The value of total_heap_size is the number of bytes V8 has
allocated for the heap. This can grow if used_heap needs more memory.</p>
<p><code>total_heap_size_executable</code> The value of total_heap_size_executable is the
portion of the heap that can contain executable code, in bytes. This includes
memory used by JIT-compiled code and any memory that must be kept executable.</p>
<p><code>total_physical_size</code> The value of total_physical_size is the actual physical memory
used by the V8 heap, in bytes. This is the amount of memory that is committed
(or in use) rather than reserved.</p>
<p><code>total_available_size</code> The value of total_available_size is the number of
bytes of memory available to the V8 heap. This value represents how much
more memory V8 can use before it exceeds the heap limit.</p>
<p><code>used_heap_size</code> The value of used_heap_size is number of bytes currently
being used by V8’s JavaScript objects. This is the actual memory in use and
does not include memory that has been allocated but not yet used.</p>
<p><code>heap_size_limit</code> The value of heap_size_limit is the maximum size of the V8
heap, in bytes (either the default limit, determined by system resources, or
the value passed to the <code>--max_old_space_size</code> option).</p>
<p><code>malloced_memory</code> The value of malloced_memory is the number of bytes allocated
through <code>malloc</code> by V8.</p>
<p><code>peak_malloced_memory</code> The value of peak_malloced_memory is the peak number of
bytes allocated through <code>malloc</code> by V8 during the lifetime of the process.</p>
<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 set size) 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>
<p><code>total_global_handles_size</code> The value of total_global_handles_size is the
total memory size of V8 global handles.</p>
<p><code>used_global_handles_size</code> The value of used_global_handles_size is the
used memory size of V8 global handles.</p>
<p><code>external_memory</code> The value of external_memory is the memory size of array
buffers and external strings.</p>
<!-- eslint-skip -->
<pre><code class="language-js">{
  <span class="hljs-attr">total_heap_size</span>: <span class="hljs-number">7326976</span>,
  <span class="hljs-attr">total_heap_size_executable</span>: <span class="hljs-number">4194304</span>,
  <span class="hljs-attr">total_physical_size</span>: <span class="hljs-number">7326976</span>,
  <span class="hljs-attr">total_available_size</span>: <span class="hljs-number">1152656</span>,
  <span class="hljs-attr">used_heap_size</span>: <span class="hljs-number">3476208</span>,
  <span class="hljs-attr">heap_size_limit</span>: <span class="hljs-number">1535115264</span>,
  <span class="hljs-attr">malloced_memory</span>: <span class="hljs-number">16384</span>,
  <span class="hljs-attr">peak_malloced_memory</span>: <span class="hljs-number">1127496</span>,
  <span class="hljs-attr">does_zap_garbage</span>: <span class="hljs-number">0</span>,
  <span class="hljs-attr">number_of_native_contexts</span>: <span class="hljs-number">1</span>,
  <span class="hljs-attr">number_of_detached_contexts</span>: <span class="hljs-number">0</span>,
  <span class="hljs-attr">total_global_handles_size</span>: <span class="hljs-number">8192</span>,
  <span class="hljs-attr">used_global_handles_size</span>: <span class="hljs-number">3296</span>,
  <span class="hljs-attr">external_memory</span>: <span class="hljs-number">318824</span>
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>v8.queryObjects(ctor[, options])</code><span><a class="mark" href="#all_v8_v8queryobjectsctor-options" id="all_v8_v8queryobjectsctor-options">#</a></span><a aria-hidden="true" class="legacy" id="v8_v8_queryobjects_ctor_options"></a></h3>
<div class="api_metadata">
<span>Added in: v20.13.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active development</div><p></p>
<ul>
<li><code>ctor</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The constructor that can be used to search on the
prototype chain in order to filter target objects in the heap.</li>
<li><code>options</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>
<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> If it's <code>'count'</code>, the count of matched objects
is returned. If it's <code>'summary'</code>, an array with summary strings
of the matched objects is returned.</li>
</ul>
</li>
<li>Returns: {number|Array<string>}</string></li>
</ul>
<p>This is similar to the <a href="https://developer.chrome.com/docs/devtools/console/utilities#queryObjects-function"><code>queryObjects()</code> console API</a> provided by the
Chromium DevTools console. It can be used to search for objects that
have the matching constructor on its prototype chain in the heap after
a full garbage collection, which can be useful for memory leak
regression tests. To avoid surprising results, users should avoid using
this API on constructors whose implementation they don't control, or on
constructors that can be invoked by other parties in the application.</p>
<p>To avoid accidental leaks, this API does not return raw references to
the objects found. By default, it returns the count of the objects
found. If <code>options.format</code> is <code>'summary'</code>, it returns an array
containing brief string representations for each object. The visibility
provided in this API is similar to what the heap snapshot provides,
while users can save the cost of serialization and parsing and directly
filter the target objects during the search.</p>
<p>Only objects created in the current execution context are included in the
results.</p>

<pre class="with-44-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { queryObjects } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:v8'</span>);
<span class="hljs-keyword">class</span> <span class="hljs-title class_">A</span> { foo = <span class="hljs-string">'bar'</span>; }
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">queryObjects</span>(A)); <span class="hljs-comment">// 0</span>
<span class="hljs-keyword">const</span> a = <span class="hljs-keyword">new</span> <span class="hljs-title function_">A</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">queryObjects</span>(A)); <span class="hljs-comment">// 1</span>
<span class="hljs-comment">// [ "A { foo: 'bar' }" ]</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">queryObjects</span>(A, { <span class="hljs-attr">format</span>: <span class="hljs-string">'summary'</span> }));

<span class="hljs-keyword">class</span> <span class="hljs-title class_">B</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">A</span> { bar = <span class="hljs-string">'qux'</span>; }
<span class="hljs-keyword">const</span> b = <span class="hljs-keyword">new</span> <span class="hljs-title function_">B</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">queryObjects</span>(B)); <span class="hljs-comment">// 1</span>
<span class="hljs-comment">// [ "B { foo: 'bar', bar: 'qux' }" ]</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">queryObjects</span>(B, { <span class="hljs-attr">format</span>: <span class="hljs-string">'summary'</span> }));

<span class="hljs-comment">// Note that, when there are child classes inheriting from a constructor,</span>
<span class="hljs-comment">// the constructor also shows up in the prototype chain of the child</span>
<span class="hljs-comment">// classes's prototoype, so the child classes's prototoype would also be</span>
<span class="hljs-comment">// included in the result.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">queryObjects</span>(A));  <span class="hljs-comment">// 3</span>
<span class="hljs-comment">// [ "B { foo: 'bar', bar: 'qux' }", 'A {}', "A { foo: 'bar' }" ]</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">queryObjects</span>(A, { <span class="hljs-attr">format</span>: <span class="hljs-string">'summary'</span> }));</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { queryObjects } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:v8'</span>;
<span class="hljs-keyword">class</span> <span class="hljs-title class_">A</span> { foo = <span class="hljs-string">'bar'</span>; }
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">queryObjects</span>(A)); <span class="hljs-comment">// 0</span>
<span class="hljs-keyword">const</span> a = <span class="hljs-keyword">new</span> <span class="hljs-title function_">A</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">queryObjects</span>(A)); <span class="hljs-comment">// 1</span>
<span class="hljs-comment">// [ "A { foo: 'bar' }" ]</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">queryObjects</span>(A, { <span class="hljs-attr">format</span>: <span class="hljs-string">'summary'</span> }));

<span class="hljs-keyword">class</span> <span class="hljs-title class_">B</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_ inherited__">A</span> { bar = <span class="hljs-string">'qux'</span>; }
<span class="hljs-keyword">const</span> b = <span class="hljs-keyword">new</span> <span class="hljs-title function_">B</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">queryObjects</span>(B)); <span class="hljs-comment">// 1</span>
<span class="hljs-comment">// [ "B { foo: 'bar', bar: 'qux' }" ]</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">queryObjects</span>(B, { <span class="hljs-attr">format</span>: <span class="hljs-string">'summary'</span> }));

<span class="hljs-comment">// Note that, when there are child classes inheriting from a constructor,</span>
<span class="hljs-comment">// the constructor also shows up in the prototype chain of the child</span>
<span class="hljs-comment">// classes's prototoype, so the child classes's prototoype would also be</span>
<span class="hljs-comment">// included in the result.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">queryObjects</span>(A));  <span class="hljs-comment">// 3</span>
<span class="hljs-comment">// [ "B { foo: 'bar', bar: 'qux' }", 'A {}', "A { foo: 'bar' }" ]</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">queryObjects</span>(A, { <span class="hljs-attr">format</span>: <span class="hljs-string">'summary'</span> }));</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>v8.setFlagsFromString(flags)</code><span><a class="mark" href="#all_v8_v8setflagsfromstringflags" id="all_v8_v8setflagsfromstringflags">#</a></span><a aria-hidden="true" class="legacy" id="v8_v8_setflagsfromstring_flags"></a></h3>
<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"><span class="hljs-comment">// Print GC events to stdout for one minute.</span>
<span class="hljs-keyword">const</span> v8 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:v8'</span>);
v8.<span class="hljs-title function_">setFlagsFromString</span>(<span class="hljs-string">'--trace_gc'</span>);
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> { v8.<span class="hljs-title function_">setFlagsFromString</span>(<span class="hljs-string">'--notrace_gc'</span>); }, <span class="hljs-number">60e3</span>);</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>v8.stopCoverage()</code><span><a class="mark" href="#all_v8_v8stopcoverage" id="all_v8_v8stopcoverage">#</a></span><a aria-hidden="true" class="legacy" id="v8_v8_stopcoverage"></a></h3>
<div class="api_metadata">
<span>Added in: v15.1.0, v14.18.0, v12.22.0</span>
</div>
<p>The <code>v8.stopCoverage()</code> method allows the user to stop the coverage collection
started by <a href="#all_cli_node_v8_coveragedir"><code>NODE_V8_COVERAGE</code></a>, so that V8 can release the execution count
records and optimize code. This can be used in conjunction with
<a href="#all_v8_v8takecoverage"><code>v8.takeCoverage()</code></a> if the user wants to collect the coverage on demand.</p>
</section><section><h3><code>v8.takeCoverage()</code><span><a class="mark" href="#all_v8_v8takecoverage" id="all_v8_v8takecoverage">#</a></span><a aria-hidden="true" class="legacy" id="v8_v8_takecoverage"></a></h3>
<div class="api_metadata">
<span>Added in: v15.1.0, v14.18.0, v12.22.0</span>
</div>
<p>The <code>v8.takeCoverage()</code> method allows the user to write the coverage started by
<a href="#all_cli_node_v8_coveragedir"><code>NODE_V8_COVERAGE</code></a> to disk on demand. This method can be invoked multiple
times during the lifetime of the process. Each time the execution counter will
be reset and a new coverage report will be written to the directory specified
by <a href="#all_cli_node_v8_coveragedir"><code>NODE_V8_COVERAGE</code></a>.</p>
<p>When the process is about to exit, one last coverage will still be written to
disk unless <a href="#all_v8_v8stopcoverage"><code>v8.stopCoverage()</code></a> is invoked before the process exits.</p>
</section><section><h3><code>v8.writeHeapSnapshot([filename[,options]])</code><span><a class="mark" href="#all_v8_v8writeheapsnapshotfilenameoptions" id="all_v8_v8writeheapsnapshotfilenameoptions">#</a></span><a aria-hidden="true" class="legacy" id="v8_v8_writeheapsnapshot_filename_options"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.1.0</td>
<td><p>Support options to configure the heap snapshot.</p></td></tr>
<tr><td>v18.0.0</td>
<td><p>An exception will now be thrown if the file could not be written.</p></td></tr>
<tr><td>v18.0.0</td>
<td><p>Make the returned error codes consistent across all platforms.</p></td></tr>
<tr><td>v11.13.0</td>
<td><p><span>Added in: v11.13.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> 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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>exposeInternals</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If true, expose internals in the heap snapshot.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>exposeNumericValues</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If true, expose numeric values in
artificial fields. <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 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>
<p>Creating a heap snapshot requires memory about twice the size of the heap at
the time the snapshot is created. This results in the risk of OOM killers
terminating the process.</p>
<p>Generating a snapshot is a synchronous operation which blocks the event loop
for a duration depending on the heap size.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { writeHeapSnapshot } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:v8'</span>);
<span class="hljs-keyword">const</span> {
  <span class="hljs-title class_">Worker</span>,
  isMainThread,
  parentPort,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);

<span class="hljs-keyword">if</span> (isMainThread) {
  <span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename);

  worker.<span class="hljs-title function_">once</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">filename</span>) =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`worker heapdump: <span class="hljs-subst">${filename}</span>`</span>);
    <span class="hljs-comment">// Now get a heapdump for the main thread.</span>
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`main thread heapdump: <span class="hljs-subst">${writeHeapSnapshot()}</span>`</span>);
  });

  <span class="hljs-comment">// Tell the worker to create a heapdump.</span>
  worker.<span class="hljs-title function_">postMessage</span>(<span class="hljs-string">'heapdump'</span>);
} <span class="hljs-keyword">else</span> {
  parentPort.<span class="hljs-title function_">once</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> {
    <span class="hljs-keyword">if</span> (message === <span class="hljs-string">'heapdump'</span>) {
      <span class="hljs-comment">// Generate a heapdump for the worker</span>
      <span class="hljs-comment">// and return the filename to the parent.</span>
      parentPort.<span class="hljs-title function_">postMessage</span>(<span class="hljs-title function_">writeHeapSnapshot</span>());
    }
  });
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>v8.setHeapSnapshotNearHeapLimit(limit)</code><span><a class="mark" href="#all_v8_v8setheapsnapshotnearheaplimitlimit" id="all_v8_v8setheapsnapshotnearheaplimitlimit">#</a></span><a aria-hidden="true" class="legacy" id="v8_v8_setheapsnapshotnearheaplimit_limit"></a></h3>
<div class="api_metadata">
<span>Added in: v18.10.0, v16.18.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<ul>
<li><code>limit</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 API is a no-op if <code>--heapsnapshot-near-heap-limit</code> is already set from the
command line or the API is called more than once. <code>limit</code> must be a positive
integer. See <a href="#all_cli_--heapsnapshot-near-heap-limitmax_count"><code>--heapsnapshot-near-heap-limit</code></a> for more information.</p>
</section><section><h3>Serialization API<span><a class="mark" href="#all_v8_serialization-api" id="all_v8_serialization-api">#</a></span><a aria-hidden="true" class="legacy" id="v8_serialization_api"></a></h3>
<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>
<h4><code>v8.serialize(value)</code><span><a class="mark" href="#all_v8_v8serializevalue" id="all_v8_v8serializevalue">#</a></span><a aria-hidden="true" class="legacy" id="v8_v8_serialize_value"></a></h4>
<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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a></li>
</ul>
<p>Uses a <a href="#all_v8_class-v8defaultserializer"><code>DefaultSerializer</code></a> to serialize <code>value</code> into a buffer.</p>
<p><a href="#all_errors_err_buffer_too_large"><code>ERR_BUFFER_TOO_LARGE</code></a> will be thrown when trying to
serialize a huge object which requires buffer
larger than <a href="#all_buffer_bufferconstantsmax_length"><code>buffer.constants.MAX_LENGTH</code></a>.</p>
<h4><code>v8.deserialize(buffer)</code><span><a class="mark" href="#all_v8_v8deserializebuffer" id="all_v8_v8deserializebuffer">#</a></span><a aria-hidden="true" class="legacy" id="v8_v8_deserialize_buffer"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<ul>
<li><code>buffer</code> <a href="#all_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="#all_v8_v8serializevalue"><code>serialize()</code></a>.</li>
</ul>
<p>Uses a <a href="#all_v8_class-v8defaultdeserializer"><code>DefaultDeserializer</code></a> with default options to read a JS value
from a buffer.</p>
<h4>Class: <code>v8.Serializer</code><span><a class="mark" href="#all_v8_class-v8serializer" id="all_v8_class-v8serializer">#</a></span><a aria-hidden="true" class="legacy" id="v8_class_v8_serializer"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<h5><code>new Serializer()</code><span><a class="mark" href="#all_v8_new-serializer" id="all_v8_new-serializer">#</a></span><a aria-hidden="true" class="legacy" id="v8_new_serializer"></a></h5>
<p>Creates a new <code>Serializer</code> object.</p>
<h5><code>serializer.writeHeader()</code><span><a class="mark" href="#all_v8_serializerwriteheader" id="all_v8_serializerwriteheader">#</a></span><a aria-hidden="true" class="legacy" id="v8_serializer_writeheader"></a></h5>
<p>Writes out a header, which includes the serialization format version.</p>
<h5><code>serializer.writeValue(value)</code><span><a class="mark" href="#all_v8_serializerwritevaluevalue" id="all_v8_serializerwritevaluevalue">#</a></span><a aria-hidden="true" class="legacy" id="v8_serializer_writevalue_value"></a></h5>
<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>
<h5><code>serializer.releaseBuffer()</code><span><a class="mark" href="#all_v8_serializerreleasebuffer" id="all_v8_serializerreleasebuffer">#</a></span><a aria-hidden="true" class="legacy" id="v8_serializer_releasebuffer"></a></h5>
<ul>
<li>Returns: <a href="#all_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>
<h5><code>serializer.transferArrayBuffer(id, arrayBuffer)</code><span><a class="mark" href="#all_v8_serializertransferarraybufferid-arraybuffer" id="all_v8_serializertransferarraybufferid-arraybuffer">#</a></span><a aria-hidden="true" class="legacy" id="v8_serializer_transferarraybuffer_id_arraybuffer"></a></h5>
<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="#all_v8_deserializertransferarraybufferid-arraybuffer"><code>deserializer.transferArrayBuffer()</code></a>.</p>
<h5><code>serializer.writeUint32(value)</code><span><a class="mark" href="#all_v8_serializerwriteuint32value" id="all_v8_serializerwriteuint32value">#</a></span><a aria-hidden="true" class="legacy" id="v8_serializer_writeuint32_value"></a></h5>
<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="#all_v8_serializer_writehostobjectobject"><code>serializer._writeHostObject()</code></a>.</p>
<h5><code>serializer.writeUint64(hi, lo)</code><span><a class="mark" href="#all_v8_serializerwriteuint64hi-lo" id="all_v8_serializerwriteuint64hi-lo">#</a></span><a aria-hidden="true" class="legacy" id="v8_serializer_writeuint64_hi_lo"></a></h5>
<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="#all_v8_serializer_writehostobjectobject"><code>serializer._writeHostObject()</code></a>.</p>
<h5><code>serializer.writeDouble(value)</code><span><a class="mark" href="#all_v8_serializerwritedoublevalue" id="all_v8_serializerwritedoublevalue">#</a></span><a aria-hidden="true" class="legacy" id="v8_serializer_writedouble_value"></a></h5>
<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="#all_v8_serializer_writehostobjectobject"><code>serializer._writeHostObject()</code></a>.</p>
<h5><code>serializer.writeRawBytes(buffer)</code><span><a class="mark" href="#all_v8_serializerwriterawbytesbuffer" id="all_v8_serializerwriterawbytesbuffer">#</a></span><a aria-hidden="true" class="legacy" id="v8_serializer_writerawbytes_buffer"></a></h5>
<ul>
<li><code>buffer</code> <a href="#all_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="#all_v8_serializer_writehostobjectobject"><code>serializer._writeHostObject()</code></a>.</p>
<h5><code>serializer._writeHostObject(object)</code><span><a class="mark" href="#all_v8_serializer_writehostobjectobject" id="all_v8_serializer_writehostobjectobject">#</a></span><a aria-hidden="true" class="legacy" id="v8_serializer_writehostobject_object"></a></h5>
<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>
<h5><code>serializer._getDataCloneError(message)</code><span><a class="mark" href="#all_v8_serializer_getdatacloneerrormessage" id="all_v8_serializer_getdatacloneerrormessage">#</a></span><a aria-hidden="true" class="legacy" id="v8_serializer_getdatacloneerror_message"></a></h5>
<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="#all_errors_class-error"><code>Error</code></a> constructor and can be overridden on
subclasses.</p>
<h5><code>serializer._getSharedArrayBufferId(sharedArrayBuffer)</code><span><a class="mark" href="#all_v8_serializer_getsharedarraybufferidsharedarraybuffer" id="all_v8_serializer_getsharedarraybufferidsharedarraybuffer">#</a></span><a aria-hidden="true" class="legacy" id="v8_serializer_getsharedarraybufferid_sharedarraybuffer"></a></h5>
<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="#all_v8_deserializertransferarraybufferid-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>
<h5><code>serializer._setTreatArrayBufferViewsAsHostObjects(flag)</code><span><a class="mark" href="#all_v8_serializer_settreatarraybufferviewsashostobjectsflag" id="all_v8_serializer_settreatarraybufferviewsashostobjectsflag">#</a></span><a aria-hidden="true" class="legacy" id="v8_serializer_settreatarraybufferviewsashostobjects_flag"></a></h5>
<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="#all_v8_serializer_writehostobjectobject"><code>serializer._writeHostObject()</code></a>.</p>
<h4>Class: <code>v8.Deserializer</code><span><a class="mark" href="#all_v8_class-v8deserializer" id="all_v8_class-v8deserializer">#</a></span><a aria-hidden="true" class="legacy" id="v8_class_v8_deserializer"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<h5><code>new Deserializer(buffer)</code><span><a class="mark" href="#all_v8_new-deserializerbuffer" id="all_v8_new-deserializerbuffer">#</a></span><a aria-hidden="true" class="legacy" id="v8_new_deserializer_buffer"></a></h5>
<ul>
<li><code>buffer</code> <a href="#all_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="#all_v8_serializerreleasebuffer"><code>serializer.releaseBuffer()</code></a>.</li>
</ul>
<p>Creates a new <code>Deserializer</code> object.</p>
<h5><code>deserializer.readHeader()</code><span><a class="mark" href="#all_v8_deserializerreadheader" id="all_v8_deserializerreadheader">#</a></span><a aria-hidden="true" class="legacy" id="v8_deserializer_readheader"></a></h5>
<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>
<h5><code>deserializer.readValue()</code><span><a class="mark" href="#all_v8_deserializerreadvalue" id="all_v8_deserializerreadvalue">#</a></span><a aria-hidden="true" class="legacy" id="v8_deserializer_readvalue"></a></h5>
<p>Deserializes a JavaScript value from the buffer and returns it.</p>
<h5><code>deserializer.transferArrayBuffer(id, arrayBuffer)</code><span><a class="mark" href="#all_v8_deserializertransferarraybufferid-arraybuffer" id="all_v8_deserializertransferarraybufferid-arraybuffer">#</a></span><a aria-hidden="true" class="legacy" id="v8_deserializer_transferarraybuffer_id_arraybuffer"></a></h5>
<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="#all_v8_serializertransferarraybufferid-arraybuffer"><code>serializer.transferArrayBuffer()</code></a> (or return the <code>id</code> from
<a href="#all_v8_serializer_getsharedarraybufferidsharedarraybuffer"><code>serializer._getSharedArrayBufferId()</code></a> in the case of <code>SharedArrayBuffer</code>s).</p>
<h5><code>deserializer.getWireFormatVersion()</code><span><a class="mark" href="#all_v8_deserializergetwireformatversion" id="all_v8_deserializergetwireformatversion">#</a></span><a aria-hidden="true" class="legacy" id="v8_deserializer_getwireformatversion"></a></h5>
<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>
<h5><code>deserializer.readUint32()</code><span><a class="mark" href="#all_v8_deserializerreaduint32" id="all_v8_deserializerreaduint32">#</a></span><a aria-hidden="true" class="legacy" id="v8_deserializer_readuint32"></a></h5>
<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="#all_v8_deserializer_readhostobject"><code>deserializer._readHostObject()</code></a>.</p>
<h5><code>deserializer.readUint64()</code><span><a class="mark" href="#all_v8_deserializerreaduint64" id="all_v8_deserializerreaduint64">#</a></span><a aria-hidden="true" class="legacy" id="v8_deserializer_readuint64"></a></h5>
<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="#all_v8_deserializer_readhostobject"><code>deserializer._readHostObject()</code></a>.</p>
<h5><code>deserializer.readDouble()</code><span><a class="mark" href="#all_v8_deserializerreaddouble" id="all_v8_deserializerreaddouble">#</a></span><a aria-hidden="true" class="legacy" id="v8_deserializer_readdouble"></a></h5>
<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="#all_v8_deserializer_readhostobject"><code>deserializer._readHostObject()</code></a>.</p>
<h5><code>deserializer.readRawBytes(length)</code><span><a class="mark" href="#all_v8_deserializerreadrawbyteslength" id="all_v8_deserializerreadrawbyteslength">#</a></span><a aria-hidden="true" class="legacy" id="v8_deserializer_readrawbytes_length"></a></h5>
<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="#all_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="#all_v8_serializerwriterawbytesbuffer"><code>serializer.writeRawBytes()</code></a>.
For use inside of a custom <a href="#all_v8_deserializer_readhostobject"><code>deserializer._readHostObject()</code></a>.</p>
<h5><code>deserializer._readHostObject()</code><span><a class="mark" href="#all_v8_deserializer_readhostobject" id="all_v8_deserializer_readhostobject">#</a></span><a aria-hidden="true" class="legacy" id="v8_deserializer_readhostobject"></a></h5>
<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>
<h4>Class: <code>v8.DefaultSerializer</code><span><a class="mark" href="#all_v8_class-v8defaultserializer" id="all_v8_class-v8defaultserializer">#</a></span><a aria-hidden="true" class="legacy" id="v8_class_v8_defaultserializer"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<p>A subclass of <a href="#all_v8_class-v8serializer"><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>
<h4>Class: <code>v8.DefaultDeserializer</code><span><a class="mark" href="#all_v8_class-v8defaultdeserializer" id="all_v8_class-v8defaultdeserializer">#</a></span><a aria-hidden="true" class="legacy" id="v8_class_v8_defaultdeserializer"></a></h4>
<div class="api_metadata">
<span>Added in: v8.0.0</span>
</div>
<p>A subclass of <a href="#all_v8_class-v8deserializer"><code>Deserializer</code></a> corresponding to the format written by
<a href="#all_v8_class-v8defaultserializer"><code>DefaultSerializer</code></a>.</p>
</section><section><h3>Promise hooks<span><a class="mark" href="#all_v8_promise-hooks" id="all_v8_promise-hooks">#</a></span><a aria-hidden="true" class="legacy" id="v8_promise_hooks"></a></h3>
<p>The <code>promiseHooks</code> interface can be used to track promise lifecycle events.
To track <em>all</em> async activity, see <a href="async_hooks.html"><code>async_hooks</code></a> which internally uses this
module to produce promise lifecycle events in addition to events for other
async resources. For request context management, see <a href="#all_async_context_class-asynclocalstorage"><code>AsyncLocalStorage</code></a>.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { promiseHooks } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:v8'</span>;

<span class="hljs-comment">// There are four lifecycle events produced by promises:</span>

<span class="hljs-comment">// The `init` event represents the creation of a promise. This could be a</span>
<span class="hljs-comment">// direct creation such as with `new Promise(...)` or a continuation such</span>
<span class="hljs-comment">// as `then()` or `catch()`. It also happens whenever an async function is</span>
<span class="hljs-comment">// called or does an `await`. If a continuation promise is created, the</span>
<span class="hljs-comment">// `parent` will be the promise it is a continuation from.</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">init</span>(<span class="hljs-params">promise, parent</span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'a promise was created'</span>, { promise, parent });
}

<span class="hljs-comment">// The `settled` event happens when a promise receives a resolution or</span>
<span class="hljs-comment">// rejection value. This may happen synchronously such as when using</span>
<span class="hljs-comment">// `Promise.resolve()` on non-promise input.</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">settled</span>(<span class="hljs-params">promise</span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'a promise resolved or rejected'</span>, { promise });
}

<span class="hljs-comment">// The `before` event runs immediately before a `then()` or `catch()` handler</span>
<span class="hljs-comment">// runs or an `await` resumes execution.</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">before</span>(<span class="hljs-params">promise</span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'a promise is about to call a then handler'</span>, { promise });
}

<span class="hljs-comment">// The `after` event runs immediately after a `then()` handler runs or when</span>
<span class="hljs-comment">// an `await` begins after resuming from another.</span>
<span class="hljs-keyword">function</span> <span class="hljs-title function_">after</span>(<span class="hljs-params">promise</span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'a promise is done calling a then handler'</span>, { promise });
}

<span class="hljs-comment">// Lifecycle hooks may be started and stopped individually</span>
<span class="hljs-keyword">const</span> stopWatchingInits = promiseHooks.<span class="hljs-title function_">onInit</span>(init);
<span class="hljs-keyword">const</span> stopWatchingSettleds = promiseHooks.<span class="hljs-title function_">onSettled</span>(settled);
<span class="hljs-keyword">const</span> stopWatchingBefores = promiseHooks.<span class="hljs-title function_">onBefore</span>(before);
<span class="hljs-keyword">const</span> stopWatchingAfters = promiseHooks.<span class="hljs-title function_">onAfter</span>(after);

<span class="hljs-comment">// Or they may be started and stopped in groups</span>
<span class="hljs-keyword">const</span> stopHookSet = promiseHooks.<span class="hljs-title function_">createHook</span>({
  init,
  settled,
  before,
  after,
});

<span class="hljs-comment">// To stop a hook, call the function returned at its creation.</span>
<span class="hljs-title function_">stopWatchingInits</span>();
<span class="hljs-title function_">stopWatchingSettleds</span>();
<span class="hljs-title function_">stopWatchingBefores</span>();
<span class="hljs-title function_">stopWatchingAfters</span>();
<span class="hljs-title function_">stopHookSet</span>();</code> <button class="copy-button">copy</button></pre>
<h4><code>promiseHooks.onInit(init)</code><span><a class="mark" href="#all_v8_promisehooksoninitinit" id="all_v8_promisehooksoninitinit">#</a></span><a aria-hidden="true" class="legacy" id="v8_promisehooks_oninit_init"></a></h4>
<div class="api_metadata">
<span>Added in: v17.1.0, v16.14.0</span>
</div>
<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="#all_v8_initpromise-parent"><code>init</code> callback</a> to call when a promise is created.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Call to stop the hook.</li>
</ul>
<p><strong>The <code>init</code> hook must be a plain function. Providing an async function will
throw as it would produce an infinite microtask loop.</strong></p>

<pre class="with-44-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { promiseHooks } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:v8'</span>;

<span class="hljs-keyword">const</span> stop = promiseHooks.<span class="hljs-title function_">onInit</span>(<span class="hljs-function">(<span class="hljs-params">promise, parent</span>) =></span> {});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { promiseHooks } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:v8'</span>);

<span class="hljs-keyword">const</span> stop = promiseHooks.<span class="hljs-title function_">onInit</span>(<span class="hljs-function">(<span class="hljs-params">promise, parent</span>) =></span> {});</code><button class="copy-button">copy</button></pre>
<h4><code>promiseHooks.onSettled(settled)</code><span><a class="mark" href="#all_v8_promisehooksonsettledsettled" id="all_v8_promisehooksonsettledsettled">#</a></span><a aria-hidden="true" class="legacy" id="v8_promisehooks_onsettled_settled"></a></h4>
<div class="api_metadata">
<span>Added in: v17.1.0, v16.14.0</span>
</div>
<ul>
<li><code>settled</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The <a href="#all_v8_settledpromise"><code>settled</code> callback</a> to call when a promise
is resolved or rejected.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Call to stop the hook.</li>
</ul>
<p><strong>The <code>settled</code> hook must be a plain function. Providing an async function will
throw as it would produce an infinite microtask loop.</strong></p>

<pre class="with-44-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { promiseHooks } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:v8'</span>;

<span class="hljs-keyword">const</span> stop = promiseHooks.<span class="hljs-title function_">onSettled</span>(<span class="hljs-function">(<span class="hljs-params">promise</span>) =></span> {});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { promiseHooks } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:v8'</span>);

<span class="hljs-keyword">const</span> stop = promiseHooks.<span class="hljs-title function_">onSettled</span>(<span class="hljs-function">(<span class="hljs-params">promise</span>) =></span> {});</code><button class="copy-button">copy</button></pre>
<h4><code>promiseHooks.onBefore(before)</code><span><a class="mark" href="#all_v8_promisehooksonbeforebefore" id="all_v8_promisehooksonbeforebefore">#</a></span><a aria-hidden="true" class="legacy" id="v8_promisehooks_onbefore_before"></a></h4>
<div class="api_metadata">
<span>Added in: v17.1.0, v16.14.0</span>
</div>
<ul>
<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="#all_v8_beforepromise"><code>before</code> callback</a> to call before a promise
continuation executes.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Call to stop the hook.</li>
</ul>
<p><strong>The <code>before</code> hook must be a plain function. Providing an async function will
throw as it would produce an infinite microtask loop.</strong></p>

<pre class="with-44-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { promiseHooks } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:v8'</span>;

<span class="hljs-keyword">const</span> stop = promiseHooks.<span class="hljs-title function_">onBefore</span>(<span class="hljs-function">(<span class="hljs-params">promise</span>) =></span> {});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { promiseHooks } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:v8'</span>);

<span class="hljs-keyword">const</span> stop = promiseHooks.<span class="hljs-title function_">onBefore</span>(<span class="hljs-function">(<span class="hljs-params">promise</span>) =></span> {});</code><button class="copy-button">copy</button></pre>
<h4><code>promiseHooks.onAfter(after)</code><span><a class="mark" href="#all_v8_promisehooksonafterafter" id="all_v8_promisehooksonafterafter">#</a></span><a aria-hidden="true" class="legacy" id="v8_promisehooks_onafter_after"></a></h4>
<div class="api_metadata">
<span>Added in: v17.1.0, v16.14.0</span>
</div>
<ul>
<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="#all_v8_afterpromise"><code>after</code> callback</a> to call after a promise
continuation executes.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Call to stop the hook.</li>
</ul>
<p><strong>The <code>after</code> hook must be a plain function. Providing an async function will
throw as it would produce an infinite microtask loop.</strong></p>

<pre class="with-44-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { promiseHooks } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:v8'</span>;

<span class="hljs-keyword">const</span> stop = promiseHooks.<span class="hljs-title function_">onAfter</span>(<span class="hljs-function">(<span class="hljs-params">promise</span>) =></span> {});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { promiseHooks } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:v8'</span>);

<span class="hljs-keyword">const</span> stop = promiseHooks.<span class="hljs-title function_">onAfter</span>(<span class="hljs-function">(<span class="hljs-params">promise</span>) =></span> {});</code><button class="copy-button">copy</button></pre>
<h4><code>promiseHooks.createHook(callbacks)</code><span><a class="mark" href="#all_v8_promisehookscreatehookcallbacks" id="all_v8_promisehookscreatehookcallbacks">#</a></span><a aria-hidden="true" class="legacy" id="v8_promisehooks_createhook_callbacks"></a></h4>
<div class="api_metadata">
<span>Added in: v17.1.0, v16.14.0</span>
</div>
<ul>
<li><code>callbacks</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> The <a href="#all_v8_hook-callbacks">Hook Callbacks</a> to register
<ul>
<li><code>init</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The <a href="#all_v8_initpromise-parent"><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="#all_v8_beforepromise"><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="#all_v8_afterpromise"><code>after</code> callback</a>.</li>
<li><code>settled</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> The <a href="#all_v8_settledpromise"><code>settled</code> callback</a>.</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> Used for disabling hooks</li>
</ul>
<p><strong>The hook callbacks must be plain functions. Providing async functions will
throw as it would produce an infinite microtask loop.</strong></p>
<p>Registers functions to be called for different lifetime events of each promise.</p>
<p>The callbacks <code>init()</code>/<code>before()</code>/<code>after()</code>/<code>settled()</code> are called for the
respective events during a promise's lifetime.</p>
<p>All callbacks are optional. For example, if only promise creation needs to
be tracked, then only the <code>init</code> callback needs to be passed. The
specifics of all functions that can be passed to <code>callbacks</code> is in the
<a href="#all_v8_hook-callbacks">Hook Callbacks</a> section.</p>

<pre class="with-44-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { promiseHooks } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:v8'</span>;

<span class="hljs-keyword">const</span> stopAll = promiseHooks.<span class="hljs-title function_">createHook</span>({
  <span class="hljs-title function_">init</span>(<span class="hljs-params">promise, parent</span>) {},
});</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { promiseHooks } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:v8'</span>);

<span class="hljs-keyword">const</span> stopAll = promiseHooks.<span class="hljs-title function_">createHook</span>({
  <span class="hljs-title function_">init</span>(<span class="hljs-params">promise, parent</span>) {},
});</code><button class="copy-button">copy</button></pre>
<h4>Hook callbacks<span><a class="mark" href="#all_v8_hook-callbacks" id="all_v8_hook-callbacks">#</a></span><a aria-hidden="true" class="legacy" id="v8_hook_callbacks"></a></h4>
<p>Key events in the lifetime of a promise have been categorized into four areas:
creation of a promise, before/after a continuation handler is called or around
an await, and when the promise resolves or rejects.</p>
<p>While these hooks are similar to those of <a href="async_hooks.html"><code>async_hooks</code></a> they lack a
<code>destroy</code> hook. Other types of async resources typically represent sockets or
file descriptors which have a distinct "closed" state to express the <code>destroy</code>
lifecycle event while promises remain usable for as long as code can still
reach them. Garbage collection tracking is used to make promises fit into the
<code>async_hooks</code> event model, however this tracking is very expensive and they may
not necessarily ever even be garbage collected.</p>
<p>Because promises are asynchronous resources whose lifecycle is tracked
via the promise hooks mechanism, the <code>init()</code>, <code>before()</code>, <code>after()</code>, and
<code>settled()</code> callbacks <em>must not</em> be async functions as they create more
promises which would produce an infinite loop.</p>
<p>While this API is used to feed promise events into <a href="async_hooks.html"><code>async_hooks</code></a>, the
ordering between the two is undefined. Both APIs are multi-tenant
and therefore could produce events in any order relative to each other.</p>
<h5><code>init(promise, parent)</code><span><a class="mark" href="#all_v8_initpromise-parent" id="all_v8_initpromise-parent">#</a></span><a aria-hidden="true" class="legacy" id="v8_init_promise_parent"></a></h5>
<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 promise being created.</li>
<li><code>parent</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> The promise continued from, if applicable.</li>
</ul>
<p>Called when a promise is constructed. This <em>does not</em> mean that corresponding
<code>before</code>/<code>after</code> events will occur, only that the possibility exists. This will
happen if a promise is created without ever getting a continuation.</p>
<h5><code>before(promise)</code><span><a class="mark" href="#all_v8_beforepromise" id="all_v8_beforepromise">#</a></span><a aria-hidden="true" class="legacy" id="v8_before_promise"></a></h5>
<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></li>
</ul>
<p>Called before a promise continuation executes. This can be in the form of
<code>then()</code>, <code>catch()</code>, or <code>finally()</code> handlers or an <code>await</code> resuming.</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 no continuation was ever made for the
promise. The <code>before</code> callback may be called many times in the case where
many continuations have been made from the same promise.</p>
<h5><code>after(promise)</code><span><a class="mark" href="#all_v8_afterpromise" id="all_v8_afterpromise">#</a></span><a aria-hidden="true" class="legacy" id="v8_after_promise"></a></h5>
<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></li>
</ul>
<p>Called immediately after a promise continuation executes. This may be after a
<code>then()</code>, <code>catch()</code>, or <code>finally()</code> handler or before an <code>await</code> after another
<code>await</code>.</p>
<h5><code>settled(promise)</code><span><a class="mark" href="#all_v8_settledpromise" id="all_v8_settledpromise">#</a></span><a aria-hidden="true" class="legacy" id="v8_settled_promise"></a></h5>
<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></li>
</ul>
<p>Called when the promise receives a resolution or rejection value. This may
occur synchronously in the case of <code>Promise.resolve()</code> or <code>Promise.reject()</code>.</p>
</section><section><h3>Startup Snapshot API<span><a class="mark" href="#all_v8_startup-snapshot-api" id="all_v8_startup-snapshot-api">#</a></span><a aria-hidden="true" class="legacy" id="v8_startup_snapshot_api"></a></h3>
<div class="api_metadata">
<span>Added in: v18.6.0, v16.17.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>The <code>v8.startupSnapshot</code> interface can be used to add serialization and
deserialization hooks for custom startup snapshots.</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">node --snapshot-blob snapshot.blob --build-snapshot entry.js</span>
<span class="hljs-meta prompt_"># </span><span class="language-bash">This launches a process with the snapshot</span>
<span class="hljs-meta prompt_">$ </span><span class="language-bash">node --snapshot-blob snapshot.blob</span></code> <button class="copy-button">copy</button></pre>
<p>In the example above, <code>entry.js</code> can use methods from the <code>v8.startupSnapshot</code>
interface to specify how to save information for custom objects in the snapshot
during serialization and how the information can be used to synchronize these
objects during deserialization of the snapshot. For example, if the <code>entry.js</code>
contains the following script:</p>
<pre><code class="language-js cjs"><span class="hljs-meta">'use strict'</span>;

<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> zlib = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:zlib'</span>);
<span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:path'</span>);
<span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);

<span class="hljs-keyword">const</span> v8 = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:v8'</span>);

<span class="hljs-keyword">class</span> <span class="hljs-title class_">BookShelf</span> {
  storage = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Map</span>();

  <span class="hljs-comment">// Reading a series of files from directory and store them into storage.</span>
  <span class="hljs-title function_">constructor</span>(<span class="hljs-params">directory, books</span>) {
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> book <span class="hljs-keyword">of</span> books) {
      <span class="hljs-variable language_">this</span>.<span class="hljs-property">storage</span>.<span class="hljs-title function_">set</span>(book, fs.<span class="hljs-title function_">readFileSync</span>(path.<span class="hljs-title function_">join</span>(directory, book)));
    }
  }

  <span class="hljs-keyword">static</span> <span class="hljs-title function_">compressAll</span>(<span class="hljs-params">shelf</span>) {
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> [ book, content ] <span class="hljs-keyword">of</span> shelf.<span class="hljs-property">storage</span>) {
      shelf.<span class="hljs-property">storage</span>.<span class="hljs-title function_">set</span>(book, zlib.<span class="hljs-title function_">gzipSync</span>(content));
    }
  }

  <span class="hljs-keyword">static</span> <span class="hljs-title function_">decompressAll</span>(<span class="hljs-params">shelf</span>) {
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> [ book, content ] <span class="hljs-keyword">of</span> shelf.<span class="hljs-property">storage</span>) {
      shelf.<span class="hljs-property">storage</span>.<span class="hljs-title function_">set</span>(book, zlib.<span class="hljs-title function_">gunzipSync</span>(content));
    }
  }
}

<span class="hljs-comment">// __dirname here is where the snapshot script is placed</span>
<span class="hljs-comment">// during snapshot building time.</span>
<span class="hljs-keyword">const</span> shelf = <span class="hljs-keyword">new</span> <span class="hljs-title class_">BookShelf</span>(__dirname, [
  <span class="hljs-string">'book1.en_US.txt'</span>,
  <span class="hljs-string">'book1.es_ES.txt'</span>,
  <span class="hljs-string">'book2.zh_CN.txt'</span>,
]);

<span class="hljs-title function_">assert</span>(v8.<span class="hljs-property">startupSnapshot</span>.<span class="hljs-title function_">isBuildingSnapshot</span>());
<span class="hljs-comment">// On snapshot serialization, compress the books to reduce size.</span>
v8.<span class="hljs-property">startupSnapshot</span>.<span class="hljs-title function_">addSerializeCallback</span>(<span class="hljs-title class_">BookShelf</span>.<span class="hljs-property">compressAll</span>, shelf);
<span class="hljs-comment">// On snapshot deserialization, decompress the books.</span>
v8.<span class="hljs-property">startupSnapshot</span>.<span class="hljs-title function_">addDeserializeCallback</span>(<span class="hljs-title class_">BookShelf</span>.<span class="hljs-property">decompressAll</span>, shelf);
v8.<span class="hljs-property">startupSnapshot</span>.<span class="hljs-title function_">setDeserializeMainFunction</span>(<span class="hljs-function">(<span class="hljs-params">shelf</span>) =></span> {
  <span class="hljs-comment">// process.env and process.argv are refreshed during snapshot</span>
  <span class="hljs-comment">// deserialization.</span>
  <span class="hljs-keyword">const</span> lang = process.<span class="hljs-property">env</span>.<span class="hljs-property">BOOK_LANG</span> || <span class="hljs-string">'en_US'</span>;
  <span class="hljs-keyword">const</span> book = process.<span class="hljs-property">argv</span>[<span class="hljs-number">1</span>];
  <span class="hljs-keyword">const</span> name = <span class="hljs-string">`<span class="hljs-subst">${book}</span>.<span class="hljs-subst">${lang}</span>.txt`</span>;
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(shelf.<span class="hljs-property">storage</span>.<span class="hljs-title function_">get</span>(name));
}, shelf);</code> <button class="copy-button">copy</button></pre>
<p>The resulted binary will get print the data deserialized from the snapshot
during start up, using the refreshed <code>process.env</code> and <code>process.argv</code> of
the launched process:</p>
<pre><code class="language-console"><span class="hljs-meta prompt_">$ </span><span class="language-bash">BOOK_LANG=es_ES node --snapshot-blob snapshot.blob book1</span>
<span class="hljs-meta prompt_"># </span><span class="language-bash">Prints content of book1.es_ES.txt deserialized from the snapshot.</span></code> <button class="copy-button">copy</button></pre>
<p>Currently the application deserialized from a user-land snapshot cannot
be snapshotted again, so these APIs are only available to applications
that are not deserialized from a user-land snapshot.</p>
<h4><code>v8.startupSnapshot.addSerializeCallback(callback[, data])</code><span><a class="mark" href="#all_v8_v8startupsnapshotaddserializecallbackcallback-data" id="all_v8_v8startupsnapshotaddserializecallbackcallback-data">#</a></span><a aria-hidden="true" class="legacy" id="v8_v8_startupsnapshot_addserializecallback_callback_data"></a></h4>
<div class="api_metadata">
<span>Added in: v18.6.0, v16.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> Callback to be invoked before serialization.</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> Optional data that will be passed to the <code>callback</code> when it
gets called.</li>
</ul>
<p>Add a callback that will be called when the Node.js instance is about to
get serialized into a snapshot and exit. This can be used to release
resources that should not or cannot be serialized or to convert user data
into a form more suitable for serialization.</p>
<p>Callbacks are run in the order in which they are added.</p>
<h4><code>v8.startupSnapshot.addDeserializeCallback(callback[, data])</code><span><a class="mark" href="#all_v8_v8startupsnapshotadddeserializecallbackcallback-data" id="all_v8_v8startupsnapshotadddeserializecallbackcallback-data">#</a></span><a aria-hidden="true" class="legacy" id="v8_v8_startupsnapshot_adddeserializecallback_callback_data"></a></h4>
<div class="api_metadata">
<span>Added in: v18.6.0, v16.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> Callback to be invoked after the snapshot is
deserialized.</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> Optional data that will be passed to the <code>callback</code> when it
gets called.</li>
</ul>
<p>Add a callback that will be called when the Node.js instance is deserialized
from a snapshot. The <code>callback</code> and the <code>data</code> (if provided) will be
serialized into the snapshot, they can be used to re-initialize the state
of the application or to re-acquire resources that the application needs
when the application is restarted from the snapshot.</p>
<p>Callbacks are run in the order in which they are added.</p>
<h4><code>v8.startupSnapshot.setDeserializeMainFunction(callback[, data])</code><span><a class="mark" href="#all_v8_v8startupsnapshotsetdeserializemainfunctioncallback-data" id="all_v8_v8startupsnapshotsetdeserializemainfunctioncallback-data">#</a></span><a aria-hidden="true" class="legacy" id="v8_v8_startupsnapshot_setdeserializemainfunction_callback_data"></a></h4>
<div class="api_metadata">
<span>Added in: v18.6.0, v16.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> Callback to be invoked as the entry point after the
snapshot is deserialized.</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> Optional data that will be passed to the <code>callback</code> when it
gets called.</li>
</ul>
<p>This sets the entry point of the Node.js application when it is deserialized
from a snapshot. This can be called only once in the snapshot building
script. If called, the deserialized application no longer needs an additional
entry point script to start up and will simply invoke the callback along with
the deserialized data (if provided), otherwise an entry point script still
needs to be provided to the deserialized application.</p>
<h4><code>v8.startupSnapshot.isBuildingSnapshot()</code><span><a class="mark" href="#all_v8_v8startupsnapshotisbuildingsnapshot" id="all_v8_v8startupsnapshotisbuildingsnapshot">#</a></span><a aria-hidden="true" class="legacy" id="v8_v8_startupsnapshot_isbuildingsnapshot"></a></h4>
<div class="api_metadata">
<span>Added in: v18.6.0, v16.17.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 true if the Node.js instance is run to build a snapshot.</p>
</section><section><h3>Class: <code>v8.GCProfiler</code><span><a class="mark" href="#all_v8_class-v8gcprofiler" id="all_v8_class-v8gcprofiler">#</a></span><a aria-hidden="true" class="legacy" id="v8_class_v8_gcprofiler"></a></h3>
<div class="api_metadata">
<span>Added in: v19.6.0, v18.15.0</span>
</div>
<p>This API collects GC data in current thread.</p>
<h4><code>new v8.GCProfiler()</code><span><a class="mark" href="#all_v8_new-v8gcprofiler" id="all_v8_new-v8gcprofiler">#</a></span><a aria-hidden="true" class="legacy" id="v8_new_v8_gcprofiler"></a></h4>
<div class="api_metadata">
<span>Added in: v19.6.0, v18.15.0</span>
</div>
<p>Create a new instance of the <code>v8.GCProfiler</code> class.</p>
<h4><code>profiler.start()</code><span><a class="mark" href="#all_v8_profilerstart" id="all_v8_profilerstart">#</a></span><a aria-hidden="true" class="legacy" id="v8_profiler_start"></a></h4>
<div class="api_metadata">
<span>Added in: v19.6.0, v18.15.0</span>
</div>
<p>Start collecting GC data.</p>
<h4><code>profiler.stop()</code><span><a class="mark" href="#all_v8_profilerstop" id="all_v8_profilerstop">#</a></span><a aria-hidden="true" class="legacy" id="v8_profiler_stop"></a></h4>
<div class="api_metadata">
<span>Added in: v19.6.0, v18.15.0</span>
</div>
<p>Stop collecting GC data and return an object.The content of object
is as follows.</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span>
  <span class="hljs-attr">"version"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"startTime"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1674059033862</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"statistics"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
    <span class="hljs-punctuation">{</span>
      <span class="hljs-attr">"gcType"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"Scavenge"</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"beforeGC"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
        <span class="hljs-attr">"heapStatistics"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
          <span class="hljs-attr">"totalHeapSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">5005312</span><span class="hljs-punctuation">,</span>
          <span class="hljs-attr">"totalHeapSizeExecutable"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">524288</span><span class="hljs-punctuation">,</span>
          <span class="hljs-attr">"totalPhysicalSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">5226496</span><span class="hljs-punctuation">,</span>
          <span class="hljs-attr">"totalAvailableSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">4341325216</span><span class="hljs-punctuation">,</span>
          <span class="hljs-attr">"totalGlobalHandlesSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">8192</span><span class="hljs-punctuation">,</span>
          <span class="hljs-attr">"usedGlobalHandlesSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">2112</span><span class="hljs-punctuation">,</span>
          <span class="hljs-attr">"usedHeapSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">4883840</span><span class="hljs-punctuation">,</span>
          <span class="hljs-attr">"heapSizeLimit"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">4345298944</span><span class="hljs-punctuation">,</span>
          <span class="hljs-attr">"mallocedMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">254128</span><span class="hljs-punctuation">,</span>
          <span class="hljs-attr">"externalMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">225138</span><span class="hljs-punctuation">,</span>
          <span class="hljs-attr">"peakMallocedMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">181760</span>
        <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"heapSpaceStatistics"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
          <span class="hljs-punctuation">{</span>
            <span class="hljs-attr">"spaceName"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"read_only_space"</span><span class="hljs-punctuation">,</span>
            <span class="hljs-attr">"spaceSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
            <span class="hljs-attr">"spaceUsedSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
            <span class="hljs-attr">"spaceAvailableSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
            <span class="hljs-attr">"physicalSpaceSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span>
          <span class="hljs-punctuation">}</span>
        <span class="hljs-punctuation">]</span>
      <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"cost"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1574.14</span><span class="hljs-punctuation">,</span>
      <span class="hljs-attr">"afterGC"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
        <span class="hljs-attr">"heapStatistics"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
          <span class="hljs-attr">"totalHeapSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">6053888</span><span class="hljs-punctuation">,</span>
          <span class="hljs-attr">"totalHeapSizeExecutable"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">524288</span><span class="hljs-punctuation">,</span>
          <span class="hljs-attr">"totalPhysicalSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">5500928</span><span class="hljs-punctuation">,</span>
          <span class="hljs-attr">"totalAvailableSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">4341101384</span><span class="hljs-punctuation">,</span>
          <span class="hljs-attr">"totalGlobalHandlesSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">8192</span><span class="hljs-punctuation">,</span>
          <span class="hljs-attr">"usedGlobalHandlesSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">2112</span><span class="hljs-punctuation">,</span>
          <span class="hljs-attr">"usedHeapSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">4059096</span><span class="hljs-punctuation">,</span>
          <span class="hljs-attr">"heapSizeLimit"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">4345298944</span><span class="hljs-punctuation">,</span>
          <span class="hljs-attr">"mallocedMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">254128</span><span class="hljs-punctuation">,</span>
          <span class="hljs-attr">"externalMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">225138</span><span class="hljs-punctuation">,</span>
          <span class="hljs-attr">"peakMallocedMemory"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">181760</span>
        <span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
        <span class="hljs-attr">"heapSpaceStatistics"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span>
          <span class="hljs-punctuation">{</span>
            <span class="hljs-attr">"spaceName"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"read_only_space"</span><span class="hljs-punctuation">,</span>
            <span class="hljs-attr">"spaceSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
            <span class="hljs-attr">"spaceUsedSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
            <span class="hljs-attr">"spaceAvailableSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span><span class="hljs-punctuation">,</span>
            <span class="hljs-attr">"physicalSpaceSize"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">0</span>
          <span class="hljs-punctuation">}</span>
        <span class="hljs-punctuation">]</span>
      <span class="hljs-punctuation">}</span>
    <span class="hljs-punctuation">}</span>
  <span class="hljs-punctuation">]</span><span class="hljs-punctuation">,</span>
  <span class="hljs-attr">"endTime"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">1674059036865</span>
<span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>Here's an example.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">GCProfiler</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'v8'</span>);
<span class="hljs-keyword">const</span> profiler = <span class="hljs-keyword">new</span> <span class="hljs-title class_">GCProfiler</span>();
profiler.<span class="hljs-title function_">start</span>();
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(profiler.<span class="hljs-title function_">stop</span>());
}, <span class="hljs-number">1000</span>);</code> <button class="copy-button">copy</button></pre></section>
        </section>
<section><h2>VM (executing JavaScript)<span><a class="mark" href="#all_vm_vm-executing-javascript" id="all_vm_vm-executing-javascript">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_executing_javascript"></a></h2>

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

<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/vm.js">lib/vm.js</a></p>
<p>The <code>node:vm</code> module enables compiling and running code within V8 Virtual
Machine contexts.</p>
<p><strong class="critical">The <code>node: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="#all_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"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-keyword">const</span> x = <span class="hljs-number">1</span>;

<span class="hljs-keyword">const</span> context = { <span class="hljs-attr">x</span>: <span class="hljs-number">2</span> };
vm.<span class="hljs-title function_">createContext</span>(context); <span class="hljs-comment">// Contextify the object.</span>

<span class="hljs-keyword">const</span> code = <span class="hljs-string">'x += 40; var y = 17;'</span>;
<span class="hljs-comment">// `x` and `y` are global variables in the context.</span>
<span class="hljs-comment">// Initially, x has the value 2 because that is the value of context.x.</span>
vm.<span class="hljs-title function_">runInContext</span>(code, context);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(context.<span class="hljs-property">x</span>); <span class="hljs-comment">// 42</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(context.<span class="hljs-property">y</span>); <span class="hljs-comment">// 17</span>

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(x); <span class="hljs-comment">// 1; y is not defined.</span></code> <button class="copy-button">copy</button></pre>
<section><h3>Class: <code>vm.Script</code><span><a class="mark" href="#all_vm_class-vmscript" id="all_vm_class-vmscript">#</a></span><a aria-hidden="true" class="legacy" id="vm_class_vm_script"></a></h3>
<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>
<h4><code>new vm.Script(code[, options])</code><span><a class="mark" href="#all_vm_new-vmscriptcode-options" id="all_vm_new-vmscriptcode-options">#</a></span><a aria-hidden="true" class="legacy" id="vm_new_vm_script_code_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.12.0</td>
<td><p>Added support for <code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code>.</p></td></tr>
<tr><td>v17.0.0, v16.12.0</td>
<td><p>Added support for import attributes to the <code>importModuleDynamically</code> parameter.</p></td></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><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>
<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 first-line 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="#all_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><code>importModuleDynamically</code>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> | <a href="#all_vm_vmconstantsuse_main_context_default_loader" class="type">&#x3C;vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER></a>
Used to specify how the modules should be loaded during the evaluation
of this script when <code>import()</code> is called. This option is part of the
experimental modules API. We do not recommend using it in a production
environment. For detailed information, see
<a href="#all_vm_support-of-dynamic-import-in-compilation-apis">Support of dynamic <code>import()</code> in compilation APIs</a>.</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>
<h4><code>script.cachedDataRejected</code><span><a class="mark" href="#all_vm_scriptcacheddatarejected" id="all_vm_scriptcacheddatarejected">#</a></span><a aria-hidden="true" class="legacy" id="vm_script_cacheddatarejected"></a></h4>
<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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a></li>
</ul>
<p>When <code>cachedData</code> is supplied to create the <code>vm.Script</code>, this value will be set
to either <code>true</code> or <code>false</code> depending on acceptance of the data by V8.
Otherwise the value is <code>undefined</code>.</p>
<h4><code>script.createCachedData()</code><span><a class="mark" href="#all_vm_scriptcreatecacheddata" id="all_vm_scriptcreatecacheddata">#</a></span><a aria-hidden="true" class="legacy" id="vm_script_createcacheddata"></a></h4>
<div class="api_metadata">
<span>Added in: v10.6.0</span>
</div>
<ul>
<li>Returns: <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a></li>
</ul>
<p>Creates a code cache that can be used with the <code>Script</code> constructor's
<code>cachedData</code> option. Returns a <code>Buffer</code>. This method may be called at any
time and any number of times.</p>
<p>The code cache of the <code>Script</code> doesn't contain any JavaScript observable
states. The code cache is safe to be saved along side the script source and
used to construct new <code>Script</code> instances multiple times.</p>
<p>Functions in the <code>Script</code> source can be marked as lazily compiled and they are
not compiled at construction of the <code>Script</code>. These functions are going to be
compiled when they are invoked the first time. The code cache serializes the
metadata that V8 currently knows about the <code>Script</code> that it can use to speed up
future compilations.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">Script</span>(<span class="hljs-string">`
function add(a, b) {
  return a + b;
}

const x = add(1, 2);
`</span>);

<span class="hljs-keyword">const</span> cacheWithoutAdd = script.<span class="hljs-title function_">createCachedData</span>();
<span class="hljs-comment">// In `cacheWithoutAdd` the function `add()` is marked for full compilation</span>
<span class="hljs-comment">// upon invocation.</span>

script.<span class="hljs-title function_">runInThisContext</span>();

<span class="hljs-keyword">const</span> cacheWithAdd = script.<span class="hljs-title function_">createCachedData</span>();
<span class="hljs-comment">// `cacheWithAdd` contains fully compiled function `add()`.</span></code> <button class="copy-button">copy</button></pre>
<h4><code>script.runInContext(contextifiedObject[, options])</code><span><a class="mark" href="#all_vm_scriptrunincontextcontextifiedobject-options" id="all_vm_scriptrunincontextcontextifiedobject-options">#</a></span><a aria-hidden="true" class="legacy" id="vm_script_runincontext_contextifiedobject_options"></a></h4>
<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="#all_vm_what-does-it-mean-to-contextify-an-object">contextified</a> object as returned by the
<code>vm.createContext()</code> method.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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="#all_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="#all_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>, receiving <code>SIGINT</code>
(<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an
<a href="#all_errors_class-error"><code>Error</code></a>. Existing handlers for the event that have been attached via
<code>process.on('SIGINT')</code> are disabled during script execution, but continue to
work after that. <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"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-keyword">const</span> context = {
  <span class="hljs-attr">animal</span>: <span class="hljs-string">'cat'</span>,
  <span class="hljs-attr">count</span>: <span class="hljs-number">2</span>,
};

<span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">Script</span>(<span class="hljs-string">'count += 1; name = "kitty";'</span>);

vm.<span class="hljs-title function_">createContext</span>(context);
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; <span class="hljs-number">10</span>; ++i) {
  script.<span class="hljs-title function_">runInContext</span>(context);
}

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(context);
<span class="hljs-comment">// Prints: { animal: 'cat', count: 12, name: 'kitty' }</span></code> <button class="copy-button">copy</button></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>
<h4><code>script.runInNewContext([contextObject[, options]])</code><span><a class="mark" href="#all_vm_scriptruninnewcontextcontextobject-options" id="all_vm_scriptruninnewcontextcontextobject-options">#</a></span><a aria-hidden="true" class="legacy" id="vm_script_runinnewcontext_contextobject_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.18.0</td>
<td><p>The <code>contextObject</code> argument now accepts <code>vm.constants.DONT_CONTEXTIFY</code>.</p></td></tr>
<tr><td>v14.6.0</td>
<td><p>The <code>microtaskMode</code> option is supported now.</p></td></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> | <a href="#all_vm_vmconstantsdont_contextify" class="type">&#x3C;vm.constants.DONT_CONTEXTIFY></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a>
Either <a href="#all_vm_vmconstantsdont_contextify"><code>vm.constants.DONT_CONTEXTIFY</code></a> or an object that will be <a href="#all_vm_what-does-it-mean-to-contextify-an-object">contextified</a>.
If <code>undefined</code>, an empty contextified object will be created for backwards compatibility.</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>
<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="#all_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="#all_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>, receiving <code>SIGINT</code>
(<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an
<a href="#all_errors_class-error"><code>Error</code></a>. Existing handlers for the event that have been attached via
<code>process.on('SIGINT')</code> are disabled during script execution, but continue to
work after that. <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="#all_url_urlorigin"><code>url.origin</code></a> property of a <a href="#all_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><code>contextCodeGeneration</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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>microtaskMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> If set to <code>afterEvaluate</code>, microtasks (tasks
scheduled through <code>Promise</code>s and <code>async function</code>s) will be run immediately
after the script has run. They are included in the <code>timeout</code> and
<code>breakOnSigint</code> scopes in that case.</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>This method is a shortcut to <code>script.runInContext(vm.createContext(options), options)</code>.
It does several things at once:</p>
<ol>
<li>Creates a new context.</li>
<li>If <code>contextObject</code> is an object, <a href="#all_vm_what-does-it-mean-to-contextify-an-object">contextifies</a> it with the new context.
If  <code>contextObject</code> is undefined, creates a new object and <a href="#all_vm_what-does-it-mean-to-contextify-an-object">contextifies</a> it.
If <code>contextObject</code> is <a href="#all_vm_vmconstantsdont_contextify"><code>vm.constants.DONT_CONTEXTIFY</code></a>, don't <a href="#all_vm_what-does-it-mean-to-contextify-an-object">contextify</a> anything.</li>
<li>Runs the compiled code contained by the <code>vm.Script</code> object within the created context. The code
does not have access to the scope in which this method is called.</li>
<li>Returns the result.</li>
</ol>
<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"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">Script</span>(<span class="hljs-string">'globalVar = "set"'</span>);

<span class="hljs-keyword">const</span> contexts = [{}, {}, {}];
contexts.<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">context</span>) =></span> {
  script.<span class="hljs-title function_">runInNewContext</span>(context);
});

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(contexts);
<span class="hljs-comment">// Prints: [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }]</span>

<span class="hljs-comment">// This would throw if the context is created from a contextified object.</span>
<span class="hljs-comment">// vm.constants.DONT_CONTEXTIFY allows creating contexts with ordinary</span>
<span class="hljs-comment">// global objects that can be frozen.</span>
<span class="hljs-keyword">const</span> freezeScript = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">Script</span>(<span class="hljs-string">'Object.freeze(globalThis); globalThis;'</span>);
<span class="hljs-keyword">const</span> frozenContext = freezeScript.<span class="hljs-title function_">runInNewContext</span>(vm.<span class="hljs-property">constants</span>.<span class="hljs-property">DONT_CONTEXTIFY</span>);</code> <button class="copy-button">copy</button></pre>
<h4><code>script.runInThisContext([options])</code><span><a class="mark" href="#all_vm_scriptruninthiscontextoptions" id="all_vm_scriptruninthiscontextoptions">#</a></span><a aria-hidden="true" class="legacy" id="vm_script_runinthiscontext_options"></a></h4>
<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>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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="#all_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="#all_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>, receiving <code>SIGINT</code>
(<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an
<a href="#all_errors_class-error"><code>Error</code></a>. Existing handlers for the event that have been attached via
<code>process.on('SIGINT')</code> are disabled during script execution, but continue to
work after that. <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"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-variable language_">global</span>.<span class="hljs-property">globalVar</span> = <span class="hljs-number">0</span>;

<span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">Script</span>(<span class="hljs-string">'globalVar += 1'</span>, { <span class="hljs-attr">filename</span>: <span class="hljs-string">'myfile.vm'</span> });

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; <span class="hljs-number">1000</span>; ++i) {
  script.<span class="hljs-title function_">runInThisContext</span>();
}

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(globalVar);

<span class="hljs-comment">// 1000</span></code> <button class="copy-button">copy</button></pre>
<h4><code>script.sourceMapURL</code><span><a class="mark" href="#all_vm_scriptsourcemapurl" id="all_vm_scriptsourcemapurl">#</a></span><a aria-hidden="true" class="legacy" id="vm_script_sourcemapurl"></a></h4>
<div class="api_metadata">
<span>Added in: v19.1.0, v18.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> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a></li>
</ul>
<p>When the script is compiled from a source that contains a source map magic
comment, this property will be set to the URL of the source map.</p>

<pre class="with-30-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> vm <span class="hljs-keyword">from</span> <span class="hljs-string">'node:vm'</span>;

<span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">Script</span>(<span class="hljs-string">`
function myFunc() {}
//# sourceMappingURL=sourcemap.json
`</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(script.<span class="hljs-property">sourceMapURL</span>);
<span class="hljs-comment">// Prints: sourcemap.json</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">Script</span>(<span class="hljs-string">`
function myFunc() {}
//# sourceMappingURL=sourcemap.json
`</span>);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(script.<span class="hljs-property">sourceMapURL</span>);
<span class="hljs-comment">// Prints: sourcemap.json</span></code><button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>vm.Module</code><span><a class="mark" href="#all_vm_class-vmmodule" id="all_vm_class-vmmodule">#</a></span><a aria-hidden="true" class="legacy" id="vm_class_vm_module"></a></h3>
<div class="api_metadata">
<span>Added in: v13.0.0, v12.16.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>This feature is only available with the <code>--experimental-vm-modules</code> command
flag enabled.</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://262.ecma-international.org/14.0/#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="#all_esm_modules-ecmascript-modules">ECMAScript Module
loader</a>. There is also no way to interact with the Loader yet, though
support is planned.</p>

<pre class="with-30-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> vm <span class="hljs-keyword">from</span> <span class="hljs-string">'node:vm'</span>;

<span class="hljs-keyword">const</span> contextifiedObject = vm.<span class="hljs-title function_">createContext</span>({
  <span class="hljs-attr">secret</span>: <span class="hljs-number">42</span>,
  <span class="hljs-attr">print</span>: <span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>,
});

<span class="hljs-comment">// Step 1</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// Create a Module by constructing a new `vm.SourceTextModule` object. This</span>
<span class="hljs-comment">// parses the provided source text, throwing a `SyntaxError` if anything goes</span>
<span class="hljs-comment">// wrong. By default, a Module is created in the top context. But here, we</span>
<span class="hljs-comment">// specify `contextifiedObject` as the context this Module belongs to.</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// Here, we attempt to obtain the default export from the module "foo", and</span>
<span class="hljs-comment">// put it into local binding "secret".</span>

<span class="hljs-keyword">const</span> bar = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SourceTextModule</span>(<span class="hljs-string">`
  import s from 'foo';
  s;
  print(s);
`</span>, { <span class="hljs-attr">context</span>: contextifiedObject });

<span class="hljs-comment">// Step 2</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// "Link" the imported dependencies of this Module to it.</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// The provided linking callback (the "linker") accepts two arguments: the</span>
<span class="hljs-comment">// parent module (`bar` in this case) and the string that is the specifier of</span>
<span class="hljs-comment">// the imported module. The callback is expected to return a Module that</span>
<span class="hljs-comment">// corresponds to the provided specifier, with certain requirements documented</span>
<span class="hljs-comment">// in `module.link()`.</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// If linking has not started for the returned Module, the same linker</span>
<span class="hljs-comment">// callback will be called on the returned Module.</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// Even top-level Modules without dependencies must be explicitly linked. The</span>
<span class="hljs-comment">// callback provided would never be called, however.</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// The link() method returns a Promise that will be resolved when all the</span>
<span class="hljs-comment">// Promises returned by the linker resolve.</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// Note: This is a contrived example in that the linker function creates a new</span>
<span class="hljs-comment">// "foo" module every time it is called. In a full-fledged module system, a</span>
<span class="hljs-comment">// cache would probably be used to avoid duplicated modules.</span>

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">linker</span>(<span class="hljs-params">specifier, referencingModule</span>) {
  <span class="hljs-keyword">if</span> (specifier === <span class="hljs-string">'foo'</span>) {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SourceTextModule</span>(<span class="hljs-string">`
      // The "secret" variable refers to the global variable we added to
      // "contextifiedObject" when creating the context.
      export default secret;
    `</span>, { <span class="hljs-attr">context</span>: referencingModule.<span class="hljs-property">context</span> });

    <span class="hljs-comment">// Using `contextifiedObject` instead of `referencingModule.context`</span>
    <span class="hljs-comment">// here would work as well.</span>
  }
  <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">`Unable to resolve dependency: <span class="hljs-subst">${specifier}</span>`</span>);
}
<span class="hljs-keyword">await</span> bar.<span class="hljs-title function_">link</span>(linker);

<span class="hljs-comment">// Step 3</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// Evaluate the Module. The evaluate() method returns a promise which will</span>
<span class="hljs-comment">// resolve after the module has finished evaluating.</span>

<span class="hljs-comment">// Prints 42.</span>
<span class="hljs-keyword">await</span> bar.evaluate();</code><code class="language-js cjs"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-keyword">const</span> contextifiedObject = vm.<span class="hljs-title function_">createContext</span>({
  <span class="hljs-attr">secret</span>: <span class="hljs-number">42</span>,
  <span class="hljs-attr">print</span>: <span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>,
});

(<span class="hljs-keyword">async</span> () => {
  <span class="hljs-comment">// Step 1</span>
  <span class="hljs-comment">//</span>
  <span class="hljs-comment">// Create a Module by constructing a new `vm.SourceTextModule` object. This</span>
  <span class="hljs-comment">// parses the provided source text, throwing a `SyntaxError` if anything goes</span>
  <span class="hljs-comment">// wrong. By default, a Module is created in the top context. But here, we</span>
  <span class="hljs-comment">// specify `contextifiedObject` as the context this Module belongs to.</span>
  <span class="hljs-comment">//</span>
  <span class="hljs-comment">// Here, we attempt to obtain the default export from the module "foo", and</span>
  <span class="hljs-comment">// put it into local binding "secret".</span>

  <span class="hljs-keyword">const</span> bar = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SourceTextModule</span>(<span class="hljs-string">`
    import s from 'foo';
    s;
    print(s);
  `</span>, { <span class="hljs-attr">context</span>: contextifiedObject });

  <span class="hljs-comment">// Step 2</span>
  <span class="hljs-comment">//</span>
  <span class="hljs-comment">// "Link" the imported dependencies of this Module to it.</span>
  <span class="hljs-comment">//</span>
  <span class="hljs-comment">// The provided linking callback (the "linker") accepts two arguments: the</span>
  <span class="hljs-comment">// parent module (`bar` in this case) and the string that is the specifier of</span>
  <span class="hljs-comment">// the imported module. The callback is expected to return a Module that</span>
  <span class="hljs-comment">// corresponds to the provided specifier, with certain requirements documented</span>
  <span class="hljs-comment">// in `module.link()`.</span>
  <span class="hljs-comment">//</span>
  <span class="hljs-comment">// If linking has not started for the returned Module, the same linker</span>
  <span class="hljs-comment">// callback will be called on the returned Module.</span>
  <span class="hljs-comment">//</span>
  <span class="hljs-comment">// Even top-level Modules without dependencies must be explicitly linked. The</span>
  <span class="hljs-comment">// callback provided would never be called, however.</span>
  <span class="hljs-comment">//</span>
  <span class="hljs-comment">// The link() method returns a Promise that will be resolved when all the</span>
  <span class="hljs-comment">// Promises returned by the linker resolve.</span>
  <span class="hljs-comment">//</span>
  <span class="hljs-comment">// Note: This is a contrived example in that the linker function creates a new</span>
  <span class="hljs-comment">// "foo" module every time it is called. In a full-fledged module system, a</span>
  <span class="hljs-comment">// cache would probably be used to avoid duplicated modules.</span>

  <span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">linker</span>(<span class="hljs-params">specifier, referencingModule</span>) {
    <span class="hljs-keyword">if</span> (specifier === <span class="hljs-string">'foo'</span>) {
      <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SourceTextModule</span>(<span class="hljs-string">`
        // The "secret" variable refers to the global variable we added to
        // "contextifiedObject" when creating the context.
        export default secret;
      `</span>, { <span class="hljs-attr">context</span>: referencingModule.<span class="hljs-property">context</span> });

      <span class="hljs-comment">// Using `contextifiedObject` instead of `referencingModule.context`</span>
      <span class="hljs-comment">// here would work as well.</span>
    }
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">`Unable to resolve dependency: <span class="hljs-subst">${specifier}</span>`</span>);
  }
  <span class="hljs-keyword">await</span> bar.<span class="hljs-title function_">link</span>(linker);

  <span class="hljs-comment">// Step 3</span>
  <span class="hljs-comment">//</span>
  <span class="hljs-comment">// Evaluate the Module. The evaluate() method returns a promise which will</span>
  <span class="hljs-comment">// resolve after the module has finished evaluating.</span>

  <span class="hljs-comment">// Prints 42.</span>
  <span class="hljs-keyword">await</span> bar.evaluate();
})();</code><button class="copy-button">copy</button></pre>
<h4><code>module.dependencySpecifiers</code><span><a class="mark" href="#all_vm_moduledependencyspecifiers" id="all_vm_moduledependencyspecifiers">#</a></span><a aria-hidden="true" class="legacy" id="vm_module_dependencyspecifiers"></a></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>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>
<h4><code>module.error</code><span><a class="mark" href="#all_vm_moduleerror" id="all_vm_moduleerror">#</a></span><a aria-hidden="true" class="legacy" id="vm_module_error"></a></h4>
<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>
<h4><code>module.evaluate([options])</code><span><a class="mark" href="#all_vm_moduleevaluateoptions" id="all_vm_moduleevaluateoptions">#</a></span><a aria-hidden="true" class="legacy" id="vm_module_evaluate_options"></a></h4>
<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>
<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="#all_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>, receiving <code>SIGINT</code>
(<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an
<a href="#all_errors_class-error"><code>Error</code></a>. Existing handlers for the event that have been attached via
<code>process.on('SIGINT')</code> are disabled during script execution, but continue to
work after that. <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> Fulfills with <code>undefined</code> upon success.</li>
</ul>
<p>Evaluate the module.</p>
<p>This must be called after the module has been linked; otherwise it will reject.
It could be called also when the module has already been evaluated, in which
case it will either do nothing if the initial evaluation ended in success
(<code>module.status</code> is <code>'evaluated'</code>) or it will re-throw the exception that the
initial evaluation resulted in (<code>module.status</code> is <code>'errored'</code>).</p>
<p>This method cannot be called while the module is being evaluated
(<code>module.status</code> is <code>'evaluating'</code>).</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>
<h4><code>module.identifier</code><span><a class="mark" href="#all_vm_moduleidentifier" id="all_vm_moduleidentifier">#</a></span><a aria-hidden="true" class="legacy" id="vm_module_identifier"></a></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>The identifier of the current module, as set in the constructor.</p>
<h4><code>module.link(linker)</code><span><a class="mark" href="#all_vm_modulelinklinker" id="all_vm_modulelinklinker">#</a></span><a aria-hidden="true" class="legacy" id="vm_module_link_linker"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.10.0</td>
<td><p>The option <code>extra.assert</code> is renamed to <code>extra.attributes</code>. The former name is still provided for backward compatibility.</p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>linker</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<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>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> foo <span class="hljs-keyword">from</span> <span class="hljs-string">'foo'</span>;
<span class="hljs-comment">//              ^^^^^ the module specifier</span></code> <button class="copy-button">copy</button></pre>
</li>
<li>
<p><code>referencingModule</code> <a href="#all_vm_class-vmmodule" class="type">&#x3C;vm.Module></a> The <code>Module</code> object <code>link()</code> is called on.</p>
</li>
<li>
<p><code>extra</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>attributes</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> The data from the attribute:
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> foo <span class="hljs-keyword">from</span> <span class="hljs-string">'foo'</span> <span class="hljs-keyword">with</span> { <span class="hljs-attr">name</span>: <span class="hljs-string">'value'</span> };
<span class="hljs-comment">//                         ^^^^^^^^^^^^^^^^^ the attribute</span></code> <button class="copy-button">copy</button></pre>
Per ECMA-262, hosts are expected to trigger an error if an
unsupported attribute is present.</li>
<li><code>assert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> Alias for <code>extra.attributes</code>.</li>
</ul>
</li>
<li>
<p>Returns: <a href="#all_vm_class-vmmodule" 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>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a></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>
<h4><code>module.namespace</code><span><a class="mark" href="#all_vm_modulenamespace" id="all_vm_modulenamespace">#</a></span><a aria-hidden="true" class="legacy" id="vm_module_namespace"></a></h4>
<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>
<h4><code>module.status</code><span><a class="mark" href="#all_vm_modulestatus" id="all_vm_modulestatus">#</a></span><a aria-hidden="true" class="legacy" id="vm_module_status"></a></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>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>
</section><section><h3>Class: <code>vm.SourceTextModule</code><span><a class="mark" href="#all_vm_class-vmsourcetextmodule" id="all_vm_class-vmsourcetextmodule">#</a></span><a aria-hidden="true" class="legacy" id="vm_class_vm_sourcetextmodule"></a></h3>
<div class="api_metadata">
<span>Added in: v9.6.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>This feature is only available with the <code>--experimental-vm-modules</code> command
flag enabled.</p>
<ul>
<li>Extends: <a href="#all_vm_class-vmmodule" 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>
<h4><code>new vm.SourceTextModule(code[, options])</code><span><a class="mark" href="#all_vm_new-vmsourcetextmodulecode-options" id="all_vm_new-vmsourcetextmodulecode-options">#</a></span><a aria-hidden="true" class="legacy" id="vm_new_vm_sourcetextmodule_code_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.0.0, v16.12.0</td>
<td><p>Added support for import attributes to the <code>importModuleDynamically</code> parameter.</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> JavaScript Module code to parse</li>
<li><code>options</code>
<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="#all_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="#all_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.
If no context is specified, the module is evaluated in the current
execution context.</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 first-line column number offset that
is displayed in stack traces produced by this <code>Module</code>. <strong>Default:</strong> <code>0</code>.</li>
<li><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>.
<ul>
<li><code>meta</code> <a href="#all_esm_importmeta" class="type">&#x3C;import.meta></a></li>
<li><code>module</code> <a href="#all_vm_class-vmsourcetextmodule" class="type">&#x3C;vm.SourceTextModule></a></li>
</ul>
</li>
<li><code>importModuleDynamically</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Used to specify the
how the modules should be loaded during the evaluation of this module
when <code>import()</code> is called. This option is part of the experimental
modules API. We do not recommend using it in a production environment.
For detailed information, see
<a href="#all_vm_support-of-dynamic-import-in-compilation-apis">Support of dynamic <code>import()</code> in compilation APIs</a>.</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 class="with-60-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> vm <span class="hljs-keyword">from</span> <span class="hljs-string">'node:vm'</span>;

<span class="hljs-keyword">const</span> contextifiedObject = vm.<span class="hljs-title function_">createContext</span>({ <span class="hljs-attr">secret</span>: <span class="hljs-number">42</span> });

<span class="hljs-keyword">const</span> <span class="hljs-variable language_">module</span> = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SourceTextModule</span>(
  <span class="hljs-string">'Object.getPrototypeOf(import.meta.prop).secret = secret;'</span>,
  {
    <span class="hljs-title function_">initializeImportMeta</span>(<span class="hljs-params">meta</span>) {
      <span class="hljs-comment">// Note: this object is created in the top context. As such,</span>
      <span class="hljs-comment">// Object.getPrototypeOf(import.meta.prop) points to the</span>
      <span class="hljs-comment">// Object.prototype in the top context rather than that in</span>
      <span class="hljs-comment">// the contextified object.</span>
      meta.<span class="hljs-property">prop</span> = {};
    },
  });
<span class="hljs-comment">// Since module has no dependencies, the linker function will never be called.</span>
<span class="hljs-keyword">await</span> <span class="hljs-variable language_">module</span>.<span class="hljs-title function_">link</span>(<span class="hljs-function">() =></span> {});
<span class="hljs-keyword">await</span> <span class="hljs-variable language_">module</span>.evaluate();

<span class="hljs-comment">// Now, Object.prototype.secret will be equal to 42.</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// To fix this problem, replace</span>
<span class="hljs-comment">//     meta.prop = {};</span>
<span class="hljs-comment">// above with</span>
<span class="hljs-comment">//     meta.prop = vm.runInContext('{}', contextifiedObject);</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
<span class="hljs-keyword">const</span> contextifiedObject = vm.<span class="hljs-title function_">createContext</span>({ <span class="hljs-attr">secret</span>: <span class="hljs-number">42</span> });
(<span class="hljs-keyword">async</span> () => {
  <span class="hljs-keyword">const</span> <span class="hljs-variable language_">module</span> = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SourceTextModule</span>(
    <span class="hljs-string">'Object.getPrototypeOf(import.meta.prop).secret = secret;'</span>,
    {
      <span class="hljs-title function_">initializeImportMeta</span>(<span class="hljs-params">meta</span>) {
        <span class="hljs-comment">// Note: this object is created in the top context. As such,</span>
        <span class="hljs-comment">// Object.getPrototypeOf(import.meta.prop) points to the</span>
        <span class="hljs-comment">// Object.prototype in the top context rather than that in</span>
        <span class="hljs-comment">// the contextified object.</span>
        meta.<span class="hljs-property">prop</span> = {};
      },
    });
  <span class="hljs-comment">// Since module has no dependencies, the linker function will never be called.</span>
  <span class="hljs-keyword">await</span> <span class="hljs-variable language_">module</span>.<span class="hljs-title function_">link</span>(<span class="hljs-function">() =></span> {});
  <span class="hljs-keyword">await</span> <span class="hljs-variable language_">module</span>.evaluate();
  <span class="hljs-comment">// Now, Object.prototype.secret will be equal to 42.</span>
  <span class="hljs-comment">//</span>
  <span class="hljs-comment">// To fix this problem, replace</span>
  <span class="hljs-comment">//     meta.prop = {};</span>
  <span class="hljs-comment">// above with</span>
  <span class="hljs-comment">//     meta.prop = vm.runInContext('{}', contextifiedObject);</span>
})();</code><button class="copy-button">copy</button></pre>
<h4><code>sourceTextModule.createCachedData()</code><span><a class="mark" href="#all_vm_sourcetextmodulecreatecacheddata" id="all_vm_sourcetextmodulecreatecacheddata">#</a></span><a aria-hidden="true" class="legacy" id="vm_sourcetextmodule_createcacheddata"></a></h4>
<div class="api_metadata">
<span>Added in: v13.7.0, v12.17.0</span>
</div>
<ul>
<li>Returns: <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a></li>
</ul>
<p>Creates a code cache that can be used with the <code>SourceTextModule</code> constructor's
<code>cachedData</code> option. Returns a <code>Buffer</code>. This method may be called any number
of times before the module has been evaluated.</p>
<p>The code cache of the <code>SourceTextModule</code> doesn't contain any JavaScript
observable states. The code cache is safe to be saved along side the script
source and used to construct new <code>SourceTextModule</code> instances multiple times.</p>
<p>Functions in the <code>SourceTextModule</code> source can be marked as lazily compiled
and they are not compiled at construction of the <code>SourceTextModule</code>. These
functions are going to be compiled when they are invoked the first time. The
code cache serializes the metadata that V8 currently knows about the
<code>SourceTextModule</code> that it can use to speed up future compilations.</p>
<pre><code class="language-js"><span class="hljs-comment">// Create an initial module</span>
<span class="hljs-keyword">const</span> <span class="hljs-variable language_">module</span> = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SourceTextModule</span>(<span class="hljs-string">'const a = 1;'</span>);

<span class="hljs-comment">// Create cached data from this module</span>
<span class="hljs-keyword">const</span> cachedData = <span class="hljs-variable language_">module</span>.<span class="hljs-title function_">createCachedData</span>();

<span class="hljs-comment">// Create a new module using the cached data. The code must be the same.</span>
<span class="hljs-keyword">const</span> module2 = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SourceTextModule</span>(<span class="hljs-string">'const a = 1;'</span>, { cachedData });</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>vm.SyntheticModule</code><span><a class="mark" href="#all_vm_class-vmsyntheticmodule" id="all_vm_class-vmsyntheticmodule">#</a></span><a aria-hidden="true" class="legacy" id="vm_class_vm_syntheticmodule"></a></h3>
<div class="api_metadata">
<span>Added in: v13.0.0, v12.16.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>This feature is only available with the <code>--experimental-vm-modules</code> command
flag enabled.</p>
<ul>
<li>Extends: <a href="#all_vm_class-vmmodule" 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"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-keyword">const</span> source = <span class="hljs-string">'{ "a": 1 }'</span>;
<span class="hljs-keyword">const</span> <span class="hljs-variable language_">module</span> = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SyntheticModule</span>([<span class="hljs-string">'default'</span>], <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">const</span> obj = <span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">parse</span>(source);
  <span class="hljs-variable language_">this</span>.<span class="hljs-title function_">setExport</span>(<span class="hljs-string">'default'</span>, obj);
});

<span class="hljs-comment">// Use `module` in linking...</span></code> <button class="copy-button">copy</button></pre>
<h4><code>new vm.SyntheticModule(exportNames, evaluateCallback[, options])</code><span><a class="mark" href="#all_vm_new-vmsyntheticmoduleexportnames-evaluatecallback-options" id="all_vm_new-vmsyntheticmoduleexportnames-evaluatecallback-options">#</a></span><a aria-hidden="true" class="legacy" id="vm_new_vm_syntheticmodule_exportnames_evaluatecallback_options"></a></h4>
<div class="api_metadata">
<span>Added in: v13.0.0, 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><code>options</code>
<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="#all_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>
<h4><code>syntheticModule.setExport(name, value)</code><span><a class="mark" href="#all_vm_syntheticmodulesetexportname-value" id="all_vm_syntheticmodulesetexportname-value">#</a></span><a aria-hidden="true" class="legacy" id="vm_syntheticmodule_setexport_name_value"></a></h4>
<div class="api_metadata">
<span>Added in: v13.0.0, 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="#all_errors_err_vm_module_status"><code>ERR_VM_MODULE_STATUS</code></a> error
will be thrown.</p>

<pre class="with-30-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> vm <span class="hljs-keyword">from</span> <span class="hljs-string">'node:vm'</span>;

<span class="hljs-keyword">const</span> m = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SyntheticModule</span>([<span class="hljs-string">'x'</span>], <span class="hljs-function">() =></span> {
  m.<span class="hljs-title function_">setExport</span>(<span class="hljs-string">'x'</span>, <span class="hljs-number">1</span>);
});

<span class="hljs-keyword">await</span> m.<span class="hljs-title function_">link</span>(<span class="hljs-function">() =></span> {});
<span class="hljs-keyword">await</span> m.evaluate();

assert.<span class="hljs-title function_">strictEqual</span>(m.<span class="hljs-property">namespace</span>.<span class="hljs-property">x</span>, <span class="hljs-number">1</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
(<span class="hljs-keyword">async</span> () => {
  <span class="hljs-keyword">const</span> m = <span class="hljs-keyword">new</span> vm.<span class="hljs-title class_">SyntheticModule</span>([<span class="hljs-string">'x'</span>], <span class="hljs-function">() =></span> {
    m.<span class="hljs-title function_">setExport</span>(<span class="hljs-string">'x'</span>, <span class="hljs-number">1</span>);
  });
  <span class="hljs-keyword">await</span> m.<span class="hljs-title function_">link</span>(<span class="hljs-function">() =></span> {});
  <span class="hljs-keyword">await</span> m.evaluate();
  assert.<span class="hljs-title function_">strictEqual</span>(m.<span class="hljs-property">namespace</span>.<span class="hljs-property">x</span>, <span class="hljs-number">1</span>);
})();</code><button class="copy-button">copy</button></pre>
</section><section><h3><code>vm.compileFunction(code[, params[, options]])</code><span><a class="mark" href="#all_vm_vmcompilefunctioncode-params-options" id="all_vm_vmcompilefunctioncode-params-options">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_compilefunction_code_params_options"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.12.0</td>
<td><p>Added support for <code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code>.</p></td></tr>
<tr><td>v19.6.0, v18.15.0</td>
<td><p>The return value now includes <code>cachedDataRejected</code> with the same semantics as the <code>vm.Script</code> version if the <code>cachedData</code> option was passed.</p></td></tr>
<tr><td>v17.0.0, v16.12.0</td>
<td><p>Added support for import attributes to the <code>importModuleDynamically</code> parameter.</p></td></tr>
<tr><td>v15.9.0</td>
<td><p>Added <code>importModuleDynamically</code> option again.</p></td></tr>
<tr><td>v14.3.0</td>
<td><p>Removal of <code>importModuleDynamically</code> due to compatibility issues.</p></td></tr>
<tr><td>v14.1.0, v13.14.0</td>
<td><p>The <code>importModuleDynamically</code> option is now supported.</p></td></tr>
<tr><td>v10.10.0</td>
<td><p><span>Added in: v10.10.0</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 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><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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 first-line 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="#all_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. This must be produced by a prior call to <a href="#all_vm_vmcompilefunctioncode-params-options"><code>vm.compileFunction()</code></a>
with the same <code>code</code> and <code>params</code>.</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="#all_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><code>importModuleDynamically</code>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> | <a href="#all_vm_vmconstantsuse_main_context_default_loader" class="type">&#x3C;vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER></a>
Used to specify the how the modules should be loaded during the evaluation of
this function when <code>import()</code> is called. This option is part of the
experimental modules API. We do not recommend using it in a production
environment. For detailed information, see
<a href="#all_vm_support-of-dynamic-import-in-compilation-apis">Support of dynamic <code>import()</code> in compilation APIs</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>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>
</section><section><h3><code>vm.constants</code><span><a class="mark" href="#all_vm_vmconstants" id="all_vm_vmconstants">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_constants"></a></h3>
<div class="api_metadata">
<span>Added in: v20.12.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>Returns an object containing commonly used constants for VM operations.</p>
<h4><code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code><span><a class="mark" href="#all_vm_vmconstantsuse_main_context_default_loader" id="all_vm_vmconstantsuse_main_context_default_loader">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_constants_use_main_context_default_loader"></a></h4>
<div class="api_metadata">
<span>Added in: v20.12.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a>.1 - Active development</div><p></p>
<p>A constant that can be used as the <code>importModuleDynamically</code> option to
<code>vm.Script</code> and <code>vm.compileFunction()</code> so that Node.js uses the default
ESM loader from the main context to load the requested module.</p>
<p>For detailed information, see
<a href="#all_vm_support-of-dynamic-import-in-compilation-apis">Support of dynamic <code>import()</code> in compilation APIs</a>.</p>
</section><section><h3><code>vm.createContext([contextObject[, options]])</code><span><a class="mark" href="#all_vm_vmcreatecontextcontextobject-options" id="all_vm_vmcreatecontextcontextobject-options">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_createcontext_contextobject_options"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.18.0</td>
<td><p>The <code>contextObject</code> argument now accepts <code>vm.constants.DONT_CONTEXTIFY</code>.</p></td></tr>
<tr><td>v20.12.0</td>
<td><p>Added support for <code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code>.</p></td></tr>
<tr><td>v20.11.0</td>
<td><p>The <code>importModuleDynamically</code> option is supported now.</p></td></tr>
<tr><td>v14.6.0</td>
<td><p>The <code>microtaskMode</code> option is supported now.</p></td></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> | <a href="#all_vm_vmconstantsdont_contextify" class="type">&#x3C;vm.constants.DONT_CONTEXTIFY></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a>
Either <a href="#all_vm_vmconstantsdont_contextify"><code>vm.constants.DONT_CONTEXTIFY</code></a> or an object that will be <a href="#all_vm_what-does-it-mean-to-contextify-an-object">contextified</a>.
If <code>undefined</code>, an empty contextified object will be created for backwards compatibility.</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>
<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="#all_url_urlorigin"><code>url.origin</code></a> property of a <a href="#all_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><code>codeGeneration</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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>microtaskMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> If set to <code>afterEvaluate</code>, microtasks (tasks
scheduled through <code>Promise</code>s and <code>async function</code>s) will be run immediately
after a script has run through <a href="#all_vm_scriptrunincontextcontextifiedobject-options"><code>script.runInContext()</code></a>.
They are included in the <code>timeout</code> and <code>breakOnSigint</code> scopes in that case.</li>
<li><code>importModuleDynamically</code>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> | <a href="#all_vm_vmconstantsuse_main_context_default_loader" class="type">&#x3C;vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER></a>
Used to specify the how the modules should be loaded when <code>import()</code> is
called in this context without a referrer script or module. This option is
part of the experimental modules API. We do not recommend using it in a
production environment. For detailed information, see
<a href="#all_vm_support-of-dynamic-import-in-compilation-apis">Support of dynamic <code>import()</code> in compilation APIs</a>.</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 the given <code>contextObject</code> is an object, the <code>vm.createContext()</code> method will <a href="#all_vm_what-does-it-mean-to-contextify-an-object">prepare that
object</a> and return a reference to it so that it can be used in
calls to <a href="#all_vm_vmrunincontextcode-contextifiedobject-options"><code>vm.runInContext()</code></a> or <a href="#all_vm_scriptrunincontextcontextifiedobject-options"><code>script.runInContext()</code></a>. Inside such
scripts, the global object will be wrapped by the <code>contextObject</code>, 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"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-variable language_">global</span>.<span class="hljs-property">globalVar</span> = <span class="hljs-number">3</span>;

<span class="hljs-keyword">const</span> context = { <span class="hljs-attr">globalVar</span>: <span class="hljs-number">1</span> };
vm.<span class="hljs-title function_">createContext</span>(context);

vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'globalVar *= 2;'</span>, context);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(context);
<span class="hljs-comment">// Prints: { globalVar: 2 }</span>

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-variable language_">global</span>.<span class="hljs-property">globalVar</span>);
<span class="hljs-comment">// Prints: 3</span></code> <button class="copy-button">copy</button></pre>
<p>If <code>contextObject</code> is omitted (or passed explicitly as <code>undefined</code>), a new,
empty <a href="#all_vm_what-does-it-mean-to-contextify-an-object">contextified</a> object will be returned.</p>
<p>When the global object in the newly created context is <a href="#all_vm_what-does-it-mean-to-contextify-an-object">contextified</a>, it has some quirks
compared to ordinary global objects. For example, it cannot be frozen. To create a context
without the contextifying quirks, pass <a href="#all_vm_vmconstantsdont_contextify"><code>vm.constants.DONT_CONTEXTIFY</code></a> as the <code>contextObject</code>
argument. See the documentation of <a href="#all_vm_vmconstantsdont_contextify"><code>vm.constants.DONT_CONTEXTIFY</code></a> for details.</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>
</section><section><h3><code>vm.isContext(object)</code><span><a class="mark" href="#all_vm_vmiscontextobject" id="all_vm_vmiscontextobject">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_iscontext_object"></a></h3>
<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>object</code> object has been <a href="#all_vm_what-does-it-mean-to-contextify-an-object">contextified</a> using
<a href="#all_vm_vmcreatecontextcontextobject-options"><code>vm.createContext()</code></a>, or if it's the global object of a context created
using <a href="#all_vm_vmconstantsdont_contextify"><code>vm.constants.DONT_CONTEXTIFY</code></a>.</p>
</section><section><h3><code>vm.measureMemory([options])</code><span><a class="mark" href="#all_vm_vmmeasurememoryoptions" id="all_vm_vmmeasurememoryoptions">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_measurememory_options"></a></h3>
<div class="api_metadata">
<span>Added in: v13.10.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p>Measure the memory known to V8 and used by all contexts known to the
current V8 isolate, or the main context.</p>
<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> Optional.
<ul>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Either <code>'summary'</code> or <code>'detailed'</code>. In summary mode,
only the memory measured for the main context will be returned. In
detailed mode, the memory measured for all contexts known to the
current V8 isolate will be returned.
<strong>Default:</strong> <code>'summary'</code></li>
<li><code>execution</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Either <code>'default'</code> or <code>'eager'</code>. With default
execution, the promise will not resolve until after the next scheduled
garbage collection starts, which may take a while (or never if the program
exits before the next GC). With eager execution, the GC will be started
right away to measure the memory.
<strong>Default:</strong> <code>'default'</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> If the memory is successfully measured, the promise will
resolve with an object containing information about the memory usage.
Otherwise it will be rejected with an <code>ERR_CONTEXT_NOT_INITIALIZED</code> error.</li>
</ul>
<p>The format of the object that the returned Promise may resolve with is
specific to the V8 engine and may change from one version of V8 to the next.</p>
<p>The returned result is different from the statistics returned by
<code>v8.getHeapSpaceStatistics()</code> in that <code>vm.measureMemory()</code> measure the
memory reachable by each V8 specific contexts in the current instance of
the V8 engine, while the result of <code>v8.getHeapSpaceStatistics()</code> measure
the memory occupied by each heap space in the current V8 instance.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
<span class="hljs-comment">// Measure the memory used by the main context.</span>
vm.<span class="hljs-title function_">measureMemory</span>({ <span class="hljs-attr">mode</span>: <span class="hljs-string">'summary'</span> })
  <span class="hljs-comment">// This is the same as vm.measureMemory()</span>
  .<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">result</span>) =></span> {
    <span class="hljs-comment">// The current format is:</span>
    <span class="hljs-comment">// {</span>
    <span class="hljs-comment">//   total: {</span>
    <span class="hljs-comment">//      jsMemoryEstimate: 2418479, jsMemoryRange: [ 2418479, 2745799 ]</span>
    <span class="hljs-comment">//    }</span>
    <span class="hljs-comment">// }</span>
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result);
  });

<span class="hljs-keyword">const</span> context = vm.<span class="hljs-title function_">createContext</span>({ <span class="hljs-attr">a</span>: <span class="hljs-number">1</span> });
vm.<span class="hljs-title function_">measureMemory</span>({ <span class="hljs-attr">mode</span>: <span class="hljs-string">'detailed'</span>, <span class="hljs-attr">execution</span>: <span class="hljs-string">'eager'</span> })
  .<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">result</span>) =></span> {
    <span class="hljs-comment">// Reference the context here so that it won't be GC'ed</span>
    <span class="hljs-comment">// until the measurement is complete.</span>
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(context.<span class="hljs-property">a</span>);
    <span class="hljs-comment">// {</span>
    <span class="hljs-comment">//   total: {</span>
    <span class="hljs-comment">//     jsMemoryEstimate: 2574732,</span>
    <span class="hljs-comment">//     jsMemoryRange: [ 2574732, 2904372 ]</span>
    <span class="hljs-comment">//   },</span>
    <span class="hljs-comment">//   current: {</span>
    <span class="hljs-comment">//     jsMemoryEstimate: 2438996,</span>
    <span class="hljs-comment">//     jsMemoryRange: [ 2438996, 2768636 ]</span>
    <span class="hljs-comment">//   },</span>
    <span class="hljs-comment">//   other: [</span>
    <span class="hljs-comment">//     {</span>
    <span class="hljs-comment">//       jsMemoryEstimate: 135736,</span>
    <span class="hljs-comment">//       jsMemoryRange: [ 135736, 465376 ]</span>
    <span class="hljs-comment">//     }</span>
    <span class="hljs-comment">//   ]</span>
    <span class="hljs-comment">// }</span>
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result);
  });</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>vm.runInContext(code, contextifiedObject[, options])</code><span><a class="mark" href="#all_vm_vmrunincontextcode-contextifiedobject-options" id="all_vm_vmrunincontextcode-contextifiedobject-options">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_runincontext_code_contextifiedobject_options"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.12.0</td>
<td><p>Added support for <code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code>.</p></td></tr>
<tr><td>v17.0.0, v16.12.0</td>
<td><p>Added support for import attributes to the <code>importModuleDynamically</code> parameter.</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>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="#all_vm_what-does-it-mean-to-contextify-an-object">contextified</a> object that will be used
as the <code>global</code> when the <code>code</code> is compiled and run.</li>
<li><code>options</code> <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>
<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 first-line 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="#all_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="#all_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>, receiving <code>SIGINT</code>
(<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an
<a href="#all_errors_class-error"><code>Error</code></a>. Existing handlers for the event that have been attached via
<code>process.on('SIGINT')</code> are disabled during script execution, but continue to
work after that. <strong>Default:</strong> <code>false</code>.</li>
<li><code>cachedData</code> <a href="#all_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>importModuleDynamically</code>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> | <a href="#all_vm_vmconstantsuse_main_context_default_loader" class="type">&#x3C;vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER></a>
Used to specify the how the modules should be loaded during the evaluation
of this script when <code>import()</code> is called. This option is part of the
experimental modules API. We do not recommend using it in a production
environment. For detailed information, see
<a href="#all_vm_support-of-dynamic-import-in-compilation-apis">Support of dynamic <code>import()</code> in compilation APIs</a>.</li>
</ul>
</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="#all_vm_what-does-it-mean-to-contextify-an-object">contextified</a> using the <a href="#all_vm_vmcreatecontextcontextobject-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="#all_vm_what-does-it-mean-to-contextify-an-object">contextified</a> object:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-keyword">const</span> contextObject = { <span class="hljs-attr">globalVar</span>: <span class="hljs-number">1</span> };
vm.<span class="hljs-title function_">createContext</span>(contextObject);

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; <span class="hljs-number">10</span>; ++i) {
  vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'globalVar *= 2;'</span>, contextObject);
}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(contextObject);
<span class="hljs-comment">// Prints: { globalVar: 1024 }</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>vm.runInNewContext(code[, contextObject[, options]])</code><span><a class="mark" href="#all_vm_vmruninnewcontextcode-contextobject-options" id="all_vm_vmruninnewcontextcode-contextobject-options">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_runinnewcontext_code_contextobject_options"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.18.0</td>
<td><p>The <code>contextObject</code> argument now accepts <code>vm.constants.DONT_CONTEXTIFY</code>.</p></td></tr>
<tr><td>v20.12.0</td>
<td><p>Added support for <code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code>.</p></td></tr>
<tr><td>v17.0.0, v16.12.0</td>
<td><p>Added support for import attributes to the <code>importModuleDynamically</code> parameter.</p></td></tr>
<tr><td>v14.6.0</td>
<td><p>The <code>microtaskMode</code> option is supported now.</p></td></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> | <a href="#all_vm_vmconstantsdont_contextify" class="type">&#x3C;vm.constants.DONT_CONTEXTIFY></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type" class="type">&#x3C;undefined></a>
Either <a href="#all_vm_vmconstantsdont_contextify"><code>vm.constants.DONT_CONTEXTIFY</code></a> or an object that will be <a href="#all_vm_what-does-it-mean-to-contextify-an-object">contextified</a>.
If <code>undefined</code>, an empty contextified object will be created for backwards compatibility.</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>
<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 first-line 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="#all_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="#all_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>, receiving <code>SIGINT</code>
(<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an
<a href="#all_errors_class-error"><code>Error</code></a>. Existing handlers for the event that have been attached via
<code>process.on('SIGINT')</code> are disabled during script execution, but continue to
work after that. <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="#all_url_urlorigin"><code>url.origin</code></a> property of a <a href="#all_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><code>contextCodeGeneration</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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="#all_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>importModuleDynamically</code>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> | <a href="#all_vm_vmconstantsuse_main_context_default_loader" class="type">&#x3C;vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER></a>
Used to specify the how the modules should be loaded during the evaluation
of this script when <code>import()</code> is called. This option is part of the
experimental modules API. We do not recommend using it in a production
environment. For detailed information, see
<a href="#all_vm_support-of-dynamic-import-in-compilation-apis">Support of dynamic <code>import()</code> in compilation APIs</a>.</li>
<li><code>microtaskMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> If set to <code>afterEvaluate</code>, microtasks (tasks
scheduled through <code>Promise</code>s and <code>async function</code>s) will be run immediately
after the script has run. They are included in the <code>timeout</code> and
<code>breakOnSigint</code> scopes in that case.</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>This method is a shortcut to
<code>(new vm.Script(code, options)).runInContext(vm.createContext(options), options)</code>.
If <code>options</code> is a string, then it specifies the filename.</p>
<p>It does several things at once:</p>
<ol>
<li>Creates a new context.</li>
<li>If <code>contextObject</code> is an object, <a href="#all_vm_what-does-it-mean-to-contextify-an-object">contextifies</a> it with the new context.
If  <code>contextObject</code> is undefined, creates a new object and <a href="#all_vm_what-does-it-mean-to-contextify-an-object">contextifies</a> it.
If <code>contextObject</code> is <a href="#all_vm_vmconstantsdont_contextify"><code>vm.constants.DONT_CONTEXTIFY</code></a>, don't <a href="#all_vm_what-does-it-mean-to-contextify-an-object">contextify</a> anything.</li>
<li>Compiles the code as a<code>vm.Script</code></li>
<li>Runs the compield code within the created context. The code does not have access to the scope in
which this method is called.</li>
<li>Returns the result.</li>
</ol>
<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"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-keyword">const</span> contextObject = {
  <span class="hljs-attr">animal</span>: <span class="hljs-string">'cat'</span>,
  <span class="hljs-attr">count</span>: <span class="hljs-number">2</span>,
};

vm.<span class="hljs-title function_">runInNewContext</span>(<span class="hljs-string">'count += 1; name = "kitty"'</span>, contextObject);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(contextObject);
<span class="hljs-comment">// Prints: { animal: 'cat', count: 3, name: 'kitty' }</span>

<span class="hljs-comment">// This would throw if the context is created from a contextified object.</span>
<span class="hljs-comment">// vm.constants.DONT_CONTEXTIFY allows creating contexts with ordinary global objects that</span>
<span class="hljs-comment">// can be frozen.</span>
<span class="hljs-keyword">const</span> frozenContext = vm.<span class="hljs-title function_">runInNewContext</span>(<span class="hljs-string">'Object.freeze(globalThis); globalThis;'</span>, vm.<span class="hljs-property">constants</span>.<span class="hljs-property">DONT_CONTEXTIFY</span>);</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>vm.runInThisContext(code[, options])</code><span><a class="mark" href="#all_vm_vmruninthiscontextcode-options" id="all_vm_vmruninthiscontextcode-options">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_runinthiscontext_code_options"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.12.0</td>
<td><p>Added support for <code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code>.</p></td></tr>
<tr><td>v17.0.0, v16.12.0</td>
<td><p>Added support for import attributes to the <code>importModuleDynamically</code> parameter.</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>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>
<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 first-line 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="#all_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="#all_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>, receiving <code>SIGINT</code>
(<kbd>Ctrl</kbd>+<kbd>C</kbd>) will terminate execution and throw an
<a href="#all_errors_class-error"><code>Error</code></a>. Existing handlers for the event that have been attached via
<code>process.on('SIGINT')</code> are disabled during script execution, but continue to
work after that. <strong>Default:</strong> <code>false</code>.</li>
<li><code>cachedData</code> <a href="#all_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>importModuleDynamically</code>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> | <a href="#all_vm_vmconstantsuse_main_context_default_loader" class="type">&#x3C;vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER></a>
Used to specify the how the modules should be loaded during the evaluation
of this script when <code>import()</code> is called. This option is part of the
experimental modules API. We do not recommend using it in a production
environment. For detailed information, see
<a href="#all_vm_support-of-dynamic-import-in-compilation-apis">Support of dynamic <code>import()</code> in compilation APIs</a>.</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"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
<span class="hljs-keyword">let</span> localVar = <span class="hljs-string">'initial value'</span>;

<span class="hljs-keyword">const</span> vmResult = vm.<span class="hljs-title function_">runInThisContext</span>(<span class="hljs-string">'localVar = "vm";'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`vmResult: '<span class="hljs-subst">${vmResult}</span>', localVar: '<span class="hljs-subst">${localVar}</span>'`</span>);
<span class="hljs-comment">// Prints: vmResult: 'vm', localVar: 'initial value'</span>

<span class="hljs-keyword">const</span> evalResult = <span class="hljs-built_in">eval</span>(<span class="hljs-string">'localVar = "eval";'</span>);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`evalResult: '<span class="hljs-subst">${evalResult}</span>', localVar: '<span class="hljs-subst">${localVar}</span>'`</span>);
<span class="hljs-comment">// Prints: evalResult: 'eval', localVar: 'eval'</span></code> <button class="copy-button">copy</button></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>
</section><section><h3>Example: Running an HTTP server within a VM<span><a class="mark" href="#all_vm_example-running-an-http-server-within-a-vm" id="all_vm_example-running-an-http-server-within-a-vm">#</a></span><a aria-hidden="true" class="legacy" id="vm_example_running_an_http_server_within_a_vm"></a></h3>
<p>When using either <a href="#all_vm_scriptruninthiscontextoptions"><code>script.runInThisContext()</code></a> or
<a href="#all_vm_vmruninthiscontextcode-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>node:http</code> module the code passed
to the context must either call <code>require('node:http')</code> on its own, or have a
reference to the <code>node:http</code> module passed to it. For instance:</p>
<pre><code class="language-js"><span class="hljs-meta">'use strict'</span>;
<span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-keyword">const</span> code = <span class="hljs-string">`
((require) => {
  const http = require('node: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/');
})`</span>;

vm.<span class="hljs-title function_">runInThisContext</span>(code)(<span class="hljs-built_in">require</span>);</code> <button class="copy-button">copy</button></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>
</section><section><h3>What does it mean to "contextify" an object?<span><a class="mark" href="#all_vm_what-does-it-mean-to-contextify-an-object" id="all_vm_what-does-it-mean-to-contextify-an-object">#</a></span><a aria-hidden="true" class="legacy" id="vm_what_does_it_mean_to_contextify_an_object"></a></h3>
<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 with an object, the <code>contextObject</code> argument
will be used to wrap the global object of a new instance of a V8 Context
(if <code>contextObject</code> is <code>undefined</code>, a new object will be created from the current context
before its contextified). This V8 Context provides the <code>code</code> run using the <code>node: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>
in the outer context is what this document refers to as "contextifying" the object.</p>
<p>The contextifying would introduce some quirks to the <code>globalThis</code> value in the context.
For example, it cannot be frozen, and it is not reference equal to the <code>contextObject</code>
in the outer context.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-comment">// An undefined `contextObject` option makes the global object contextified.</span>
<span class="hljs-keyword">const</span> context = vm.<span class="hljs-title function_">createContext</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'globalThis'</span>, context) === context);  <span class="hljs-comment">// false</span>
<span class="hljs-comment">// A contextified global object cannot be frozen.</span>
<span class="hljs-keyword">try</span> {
  vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'Object.freeze(globalThis);'</span>, context);
} <span class="hljs-keyword">catch</span> (e) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(e); <span class="hljs-comment">// TypeError: Cannot freeze</span>
}
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'globalThis.foo = 1; foo;'</span>, context));  <span class="hljs-comment">// 1</span></code> <button class="copy-button">copy</button></pre>
<p>To create a context with an ordinary global object and get access to a global proxy in
the outer context with fewer quirks, specify <code>vm.constants.DONT_CONTEXTIFY</code> as the
<code>contextObject</code> argument.</p>
<h4><code>vm.constants.DONT_CONTEXTIFY</code><span><a class="mark" href="#all_vm_vmconstantsdont_contextify" id="all_vm_vmconstantsdont_contextify">#</a></span><a aria-hidden="true" class="legacy" id="vm_vm_constants_dont_contextify"></a></h4>
<p>This constant, when used as the <code>contextObject</code> argument in vm APIs, instructs Node.js to create
a context without wrapping its global object with another object in a Node.js-specific manner.
As a result, the <code>globalThis</code> value inside the new context would behave more closely to an ordinary
one.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-comment">// Use vm.constants.DONT_CONTEXTIFY to freeze the global object.</span>
<span class="hljs-keyword">const</span> context = vm.<span class="hljs-title function_">createContext</span>(vm.<span class="hljs-property">constants</span>.<span class="hljs-property">DONT_CONTEXTIFY</span>);
vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'Object.freeze(globalThis);'</span>, context);
<span class="hljs-keyword">try</span> {
  vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'bar = 1; bar;'</span>, context);
} <span class="hljs-keyword">catch</span> (e) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(e); <span class="hljs-comment">// Uncaught ReferenceError: bar is not defined</span>
}</code> <button class="copy-button">copy</button></pre>
<p>When <code>vm.constants.DONT_CONTEXTIFY</code> is used as the <code>contextObject</code> argument to <a href="#all_vm_vmcreatecontextcontextobject-options"><code>vm.createContext()</code></a>,
the returned object is a proxy-like object to the global object in the newly created context with
fewer Node.js-specific quirks. It is reference equal to the <code>globalThis</code> value in the new context,
can be modified from outside the context, and can be used to access built-ins in the new context directly.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-keyword">const</span> context = vm.<span class="hljs-title function_">createContext</span>(vm.<span class="hljs-property">constants</span>.<span class="hljs-property">DONT_CONTEXTIFY</span>);

<span class="hljs-comment">// Returned object is reference equal to globalThis in the new context.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'globalThis'</span>, context) === context);  <span class="hljs-comment">// true</span>

<span class="hljs-comment">// Can be used to access globals in the new context directly.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(context.<span class="hljs-property">Array</span>);  <span class="hljs-comment">// [Function: Array]</span>
vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'foo = 1;'</span>, context);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(context.<span class="hljs-property">foo</span>);  <span class="hljs-comment">// 1</span>
context.<span class="hljs-property">bar</span> = <span class="hljs-number">1</span>;
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'bar;'</span>, context));  <span class="hljs-comment">// 1</span>

<span class="hljs-comment">// Can be frozen and it affects the inner context.</span>
<span class="hljs-title class_">Object</span>.<span class="hljs-title function_">freeze</span>(context);
<span class="hljs-keyword">try</span> {
  vm.<span class="hljs-title function_">runInContext</span>(<span class="hljs-string">'baz = 1; baz;'</span>, context);
} <span class="hljs-keyword">catch</span> (e) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(e); <span class="hljs-comment">// Uncaught ReferenceError: baz is not defined</span>
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Timeout interactions with asynchronous tasks and Promises<span><a class="mark" href="#all_vm_timeout-interactions-with-asynchronous-tasks-and-promises" id="all_vm_timeout-interactions-with-asynchronous-tasks-and-promises">#</a></span><a aria-hidden="true" class="legacy" id="vm_timeout_interactions_with_asynchronous_tasks_and_promises"></a></h3>
<p><code>Promise</code>s and <code>async function</code>s can schedule tasks run by the JavaScript
engine asynchronously. By default, these tasks are run after all JavaScript
functions on the current stack are done executing.
This allows escaping the functionality of the <code>timeout</code> and
<code>breakOnSigint</code> options.</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"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-keyword">function</span> <span class="hljs-title function_">loop</span>(<span class="hljs-params"></span>) {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'entering loop'</span>);
  <span class="hljs-keyword">while</span> (<span class="hljs-number">1</span>) <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>());
}

vm.<span class="hljs-title function_">runInNewContext</span>(
  <span class="hljs-string">'Promise.resolve().then(() => loop());'</span>,
  { loop, <span class="hljs-variable language_">console</span> },
  { <span class="hljs-attr">timeout</span>: <span class="hljs-number">5</span> },
);
<span class="hljs-comment">// This is printed *before* 'entering loop' (!)</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'done executing'</span>);</code> <button class="copy-button">copy</button></pre>
<p>This can be addressed by passing <code>microtaskMode: 'afterEvaluate'</code> to the code
that creates the <code>Context</code>:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> vm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

<span class="hljs-keyword">function</span> <span class="hljs-title function_">loop</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">while</span> (<span class="hljs-number">1</span>) <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>());
}

vm.<span class="hljs-title function_">runInNewContext</span>(
  <span class="hljs-string">'Promise.resolve().then(() => loop());'</span>,
  { loop, <span class="hljs-variable language_">console</span> },
  { <span class="hljs-attr">timeout</span>: <span class="hljs-number">5</span>, <span class="hljs-attr">microtaskMode</span>: <span class="hljs-string">'afterEvaluate'</span> },
);</code> <button class="copy-button">copy</button></pre>
<p>In this case, the microtask scheduled through <code>promise.then()</code> will be run
before returning from <code>vm.runInNewContext()</code>, and will be interrupted
by the <code>timeout</code> functionality. This applies only to code running in a
<code>vm.Context</code>, so e.g. <a href="#all_vm_vmruninthiscontextcode-options"><code>vm.runInThisContext()</code></a> does not take this option.</p>
<p>Promise callbacks are entered into the microtask queue of the context in which
they were created. For example, if <code>() => loop()</code> is replaced with just <code>loop</code>
in the above example, then <code>loop</code> will be pushed into the global microtask
queue, because it is a function from the outer (main) context, and thus will
also be able to escape the timeout.</p>
<p>If asynchronous scheduling functions such as <code>process.nextTick()</code>,
<code>queueMicrotask()</code>, <code>setTimeout()</code>, <code>setImmediate()</code>, etc. are made available
inside a <code>vm.Context</code>, functions passed to them will be added to global queues,
which are shared by all contexts. Therefore, callbacks passed to those functions
are not controllable through the timeout either.</p>
</section><section><h3>Support of dynamic <code>import()</code> in compilation APIs<span><a class="mark" href="#all_vm_support-of-dynamic-import-in-compilation-apis" id="all_vm_support-of-dynamic-import-in-compilation-apis">#</a></span><a aria-hidden="true" class="legacy" id="vm_support_of_dynamic_import_in_compilation_apis"></a></h3>
<p>The following APIs support an <code>importModuleDynamically</code> option to enable dynamic
<code>import()</code> in code compiled by the vm module.</p>
<ul>
<li><code>new vm.Script</code></li>
<li><code>vm.compileFunction()</code></li>
<li><code>new vm.SourceTextModule</code></li>
<li><code>vm.runInThisContext()</code></li>
<li><code>vm.runInContext()</code></li>
<li><code>vm.runInNewContext()</code></li>
<li><code>vm.createContext()</code></li>
</ul>
<p>This option is still part of the experimental modules API. We do not recommend
using it in a production environment.</p>
<h4>When the <code>importModuleDynamically</code> option is not specified or undefined<span><a class="mark" href="#all_vm_when-the-importmoduledynamically-option-is-not-specified-or-undefined" id="all_vm_when-the-importmoduledynamically-option-is-not-specified-or-undefined">#</a></span><a aria-hidden="true" class="legacy" id="vm_when_the_importmoduledynamically_option_is_not_specified_or_undefined"></a></h4>
<p>If this option is not specified, or if it's <code>undefined</code>, code containing
<code>import()</code> can still be compiled by the vm APIs, but when the compiled code is
executed and it actually calls <code>import()</code>, the result will reject with
<a href="#all_errors_err_vm_dynamic_import_callback_missing"><code>ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING</code></a>.</p>
<h4>When <code>importModuleDynamically</code> is <code>vm.constants.USE_MAIN_CONTEXT_DEFAULT_LOADER</code><span><a class="mark" href="#all_vm_when-importmoduledynamically-is-vmconstantsuse_main_context_default_loader" id="all_vm_when-importmoduledynamically-is-vmconstantsuse_main_context_default_loader">#</a></span><a aria-hidden="true" class="legacy" id="vm_when_importmoduledynamically_is_vm_constants_use_main_context_default_loader"></a></h4>
<p>This option is currently not supported for <code>vm.SourceTextModule</code>.</p>
<p>With this option, when an <code>import()</code> is initiated in the compiled code, Node.js
would use the default ESM loader from the main context to load the requested
module and return it to the code being executed.</p>
<p>This gives access to Node.js built-in modules such as <code>fs</code> or <code>http</code>
to the code being compiled. If the code is executed in a different context,
be aware that the objects created by modules loaded from the main context
are still from the main context and not <code>instanceof</code> built-in classes in the
new context.</p>

<pre class="with-49-chars"><input class="js-flavor-toggle" type="checkbox" aria-label="Show modern ES modules syntax"><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Script</span>, constants } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
<span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Script</span>(
  <span class="hljs-string">'import("node:fs").then(({readFile}) => readFile instanceof Function)'</span>,
  { <span class="hljs-attr">importModuleDynamically</span>: constants.<span class="hljs-property">USE_MAIN_CONTEXT_DEFAULT_LOADER</span> });

<span class="hljs-comment">// false: URL loaded from the main context is not an instance of the Function</span>
<span class="hljs-comment">// class in the new context.</span>
script.<span class="hljs-title function_">runInNewContext</span>().<span class="hljs-title function_">then</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>);</code><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Script</span>, constants } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:vm'</span>;

<span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Script</span>(
  <span class="hljs-string">'import("node:fs").then(({readFile}) => readFile instanceof Function)'</span>,
  { <span class="hljs-attr">importModuleDynamically</span>: constants.<span class="hljs-property">USE_MAIN_CONTEXT_DEFAULT_LOADER</span> });

<span class="hljs-comment">// false: URL loaded from the main context is not an instance of the Function</span>
<span class="hljs-comment">// class in the new context.</span>
script.<span class="hljs-title function_">runInNewContext</span>().<span class="hljs-title function_">then</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>);</code><button class="copy-button">copy</button></pre>
<p>This option also allows the script or function to load user modules:</p>

<pre class="with-49-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Script</span>, constants } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:vm'</span>;
<span class="hljs-keyword">import</span> { resolve } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:path'</span>;
<span class="hljs-keyword">import</span> { writeFileSync } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs'</span>;

<span class="hljs-comment">// Write test.js and test.txt to the directory where the current script</span>
<span class="hljs-comment">// being run is located.</span>
<span class="hljs-title function_">writeFileSync</span>(<span class="hljs-title function_">resolve</span>(<span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">dirname</span>, <span class="hljs-string">'test.mjs'</span>),
              <span class="hljs-string">'export const filename = "./test.json";'</span>);
<span class="hljs-title function_">writeFileSync</span>(<span class="hljs-title function_">resolve</span>(<span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">dirname</span>, <span class="hljs-string">'test.json'</span>),
              <span class="hljs-string">'{"hello": "world"}'</span>);

<span class="hljs-comment">// Compile a script that loads test.mjs and then test.json</span>
<span class="hljs-comment">// as if the script is placed in the same directory.</span>
<span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Script</span>(
  <span class="hljs-string">`(async function() {
    const { filename } = await import('./test.mjs');
    return import(filename, { with: { type: 'json' } })
  })();`</span>,
  {
    <span class="hljs-attr">filename</span>: <span class="hljs-title function_">resolve</span>(<span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">dirname</span>, <span class="hljs-string">'test-with-default.js'</span>),
    <span class="hljs-attr">importModuleDynamically</span>: constants.<span class="hljs-property">USE_MAIN_CONTEXT_DEFAULT_LOADER</span>,
  });

<span class="hljs-comment">// { default: { hello: 'world' } }</span>
script.<span class="hljs-title function_">runInThisContext</span>().<span class="hljs-title function_">then</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Script</span>, constants } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);
<span class="hljs-keyword">const</span> { resolve } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:path'</span>);
<span class="hljs-keyword">const</span> { writeFileSync } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);

<span class="hljs-comment">// Write test.js and test.txt to the directory where the current script</span>
<span class="hljs-comment">// being run is located.</span>
<span class="hljs-title function_">writeFileSync</span>(<span class="hljs-title function_">resolve</span>(__dirname, <span class="hljs-string">'test.mjs'</span>),
              <span class="hljs-string">'export const filename = "./test.json";'</span>);
<span class="hljs-title function_">writeFileSync</span>(<span class="hljs-title function_">resolve</span>(__dirname, <span class="hljs-string">'test.json'</span>),
              <span class="hljs-string">'{"hello": "world"}'</span>);

<span class="hljs-comment">// Compile a script that loads test.mjs and then test.json</span>
<span class="hljs-comment">// as if the script is placed in the same directory.</span>
<span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Script</span>(
  <span class="hljs-string">`(async function() {
    const { filename } = await import('./test.mjs');
    return import(filename, { with: { type: 'json' } })
  })();`</span>,
  {
    <span class="hljs-attr">filename</span>: <span class="hljs-title function_">resolve</span>(__dirname, <span class="hljs-string">'test-with-default.js'</span>),
    <span class="hljs-attr">importModuleDynamically</span>: constants.<span class="hljs-property">USE_MAIN_CONTEXT_DEFAULT_LOADER</span>,
  });

<span class="hljs-comment">// { default: { hello: 'world' } }</span>
script.<span class="hljs-title function_">runInThisContext</span>().<span class="hljs-title function_">then</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>);</code><button class="copy-button">copy</button></pre>
<p>There are a few caveats with loading user modules using the default loader
from the main context:</p>
<ol>
<li>The module being resolved would be relative to the <code>filename</code> option passed
to <code>vm.Script</code> or <code>vm.compileFunction()</code>. The resolution can work with a
<code>filename</code> that's either an absolute path or a URL string.  If <code>filename</code> is
a string that's neither an absolute path or a URL, or if it's undefined,
the resolution will be relative to the current working directory
of the process. In the case of <code>vm.createContext()</code>, the resolution is always
relative to the current working directory since this option is only used when
there isn't a referrer script or module.</li>
<li>For any given <code>filename</code> that resolves to a specific path, once the process
manages to load a particular module from that path, the result may be cached,
and subsequent load of the same module from the same path would return the
same thing. If the <code>filename</code> is a URL string, the cache would not be hit
if it has different search parameters. For <code>filename</code>s that are not URL
strings, there is currently no way to bypass the caching behavior.</li>
</ol>
<h4>When <code>importModuleDynamically</code> is a function<span><a class="mark" href="#all_vm_when-importmoduledynamically-is-a-function" id="all_vm_when-importmoduledynamically-is-a-function">#</a></span><a aria-hidden="true" class="legacy" id="vm_when_importmoduledynamically_is_a_function"></a></h4>
<p>When <code>importModuleDynamically</code> is a function, it will be invoked when <code>import()</code>
is called in the compiled code for users to customize how the requested module
should be compiled and evaluated. Currently, the Node.js instance must be
launched with the <code>--experimental-vm-modules</code> flag for this option to work. If
the flag isn't set, this callback will be ignored. If the code evaluated
actually calls to <code>import()</code>, the result will reject with
<a href="#all_errors_err_vm_dynamic_import_callback_missing_flag"><code>ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG</code></a>.</p>
<p>The callback <code>importModuleDynamically(specifier, referrer, importAttributes)</code>
has the following signature:</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>referrer</code> <a href="#all_vm_class-vmscript" class="type">&#x3C;vm.Script></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> | <a href="#all_vm_class-vmsourcetextmodule" class="type">&#x3C;vm.SourceTextModule></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
The referrer is the compiled <code>vm.Script</code> for <code>new vm.Script</code>,
<code>vm.runInThisContext</code>, <code>vm.runInContext</code> and <code>vm.runInNewContext</code>. It's the
compiled <code>Function</code> for <code>vm.compileFunction</code>, the compiled
<code>vm.SourceTextModule</code> for <code>new vm.SourceTextModule</code>, and the context <code>Object</code>
for <code>vm.createContext()</code>.</li>
<li><code>importAttributes</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> The <code>"with"</code> value passed to the
<a href="https://tc39.es/proposal-import-attributes/#sec-evaluate-import-call"><code>optionsExpression</code></a> optional parameter, or an empty object if no value was
provided.</li>
<li>Returns: <a href="https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects" class="type">&#x3C;Module Namespace Object></a> | <a href="#all_vm_class-vmmodule" 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>

<pre class="with-58-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-comment">// This script must be run with --experimental-vm-modules.</span>
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Script</span>, <span class="hljs-title class_">SyntheticModule</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:vm'</span>;

<span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Script</span>(<span class="hljs-string">'import("foo.json", { with: { type: "json" } })'</span>, {
  <span class="hljs-keyword">async</span> <span class="hljs-title function_">importModuleDynamically</span>(<span class="hljs-params">specifier, referrer, importAttributes</span>) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(specifier);  <span class="hljs-comment">// 'foo.json'</span>
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(referrer);   <span class="hljs-comment">// The compiled script</span>
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(importAttributes);  <span class="hljs-comment">// { type: 'json' }</span>
    <span class="hljs-keyword">const</span> m = <span class="hljs-keyword">new</span> <span class="hljs-title class_">SyntheticModule</span>([<span class="hljs-string">'bar'</span>], <span class="hljs-function">() =></span> { });
    <span class="hljs-keyword">await</span> m.<span class="hljs-title function_">link</span>(<span class="hljs-function">() =></span> { });
    m.<span class="hljs-title function_">setExport</span>(<span class="hljs-string">'bar'</span>, { <span class="hljs-attr">hello</span>: <span class="hljs-string">'world'</span> });
    <span class="hljs-keyword">return</span> m;
  },
});
<span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> script.<span class="hljs-title function_">runInThisContext</span>();
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result);  <span class="hljs-comment">//  { bar: { hello: 'world' } }</span></code><code class="language-js cjs"><span class="hljs-comment">// This script must be run with --experimental-vm-modules.</span>
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Script</span>, <span class="hljs-title class_">SyntheticModule</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:vm'</span>);

(<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">main</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">const</span> script = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Script</span>(<span class="hljs-string">'import("foo.json", { with: { type: "json" } })'</span>, {
    <span class="hljs-keyword">async</span> <span class="hljs-title function_">importModuleDynamically</span>(<span class="hljs-params">specifier, referrer, importAttributes</span>) {
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(specifier);  <span class="hljs-comment">// 'foo.json'</span>
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(referrer);   <span class="hljs-comment">// The compiled script</span>
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(importAttributes);  <span class="hljs-comment">// { type: 'json' }</span>
      <span class="hljs-keyword">const</span> m = <span class="hljs-keyword">new</span> <span class="hljs-title class_">SyntheticModule</span>([<span class="hljs-string">'bar'</span>], <span class="hljs-function">() =></span> { });
      <span class="hljs-keyword">await</span> m.<span class="hljs-title function_">link</span>(<span class="hljs-function">() =></span> { });
      m.<span class="hljs-title function_">setExport</span>(<span class="hljs-string">'bar'</span>, { <span class="hljs-attr">hello</span>: <span class="hljs-string">'world'</span> });
      <span class="hljs-keyword">return</span> m;
    },
  });
  <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> script.<span class="hljs-title function_">runInThisContext</span>();
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(result);  <span class="hljs-comment">//  { bar: { hello: 'world' } }</span>
})();</code><button class="copy-button">copy</button></pre></section>
        </section>
<section><h2>WebAssembly System Interface (WASI)<span><a class="mark" href="#all_wasi_webassembly-system-interface-wasi" id="all_wasi_webassembly-system-interface-wasi">#</a></span><a aria-hidden="true" class="legacy" id="wasi_webassembly_system_interface_wasi"></a></h2>

<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<p><strong class="critical">The <code>node:wasi</code> module does not currently provide the
comprehensive file system security properties provided by some WASI runtimes.
Full support for secure file system sandboxing may or may not be implemented in
future. In the mean time, do not rely on it to run untrusted code. </strong></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/wasi.js">lib/wasi.js</a></p>
<p>The WASI API provides an implementation of the <a href="https://wasi.dev/">WebAssembly System Interface</a>
specification. WASI gives WebAssembly applications access to the underlying
operating system via a collection of POSIX-like functions.</p>

<pre class="with-49-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { readFile } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-variable constant_">WASI</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:wasi'</span>;
<span class="hljs-keyword">import</span> { argv, env } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:process'</span>;

<span class="hljs-keyword">const</span> wasi = <span class="hljs-keyword">new</span> <span class="hljs-title function_">WASI</span>({
  <span class="hljs-attr">version</span>: <span class="hljs-string">'preview1'</span>,
  <span class="hljs-attr">args</span>: argv,
  env,
  <span class="hljs-attr">preopens</span>: {
    <span class="hljs-string">'/local'</span>: <span class="hljs-string">'/some/real/path/that/wasm/can/access'</span>,
  },
});

<span class="hljs-keyword">const</span> wasm = <span class="hljs-keyword">await</span> <span class="hljs-title class_">WebAssembly</span>.<span class="hljs-title function_">compile</span>(
  <span class="hljs-keyword">await</span> <span class="hljs-title function_">readFile</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'./demo.wasm'</span>, <span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>)),
);
<span class="hljs-keyword">const</span> instance = <span class="hljs-keyword">await</span> <span class="hljs-title class_">WebAssembly</span>.<span class="hljs-title function_">instantiate</span>(wasm, wasi.<span class="hljs-title function_">getImportObject</span>());

wasi.<span class="hljs-title function_">start</span>(instance);</code><code class="language-js cjs"><span class="hljs-meta">'use strict'</span>;
<span class="hljs-keyword">const</span> { readFile } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs/promises'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-variable constant_">WASI</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:wasi'</span>);
<span class="hljs-keyword">const</span> { argv, env } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:process'</span>);
<span class="hljs-keyword">const</span> { join } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:path'</span>);

<span class="hljs-keyword">const</span> wasi = <span class="hljs-keyword">new</span> <span class="hljs-title function_">WASI</span>({
  <span class="hljs-attr">version</span>: <span class="hljs-string">'preview1'</span>,
  <span class="hljs-attr">args</span>: argv,
  env,
  <span class="hljs-attr">preopens</span>: {
    <span class="hljs-string">'/local'</span>: <span class="hljs-string">'/some/real/path/that/wasm/can/access'</span>,
  },
});

(<span class="hljs-keyword">async</span> () => {
  <span class="hljs-keyword">const</span> wasm = <span class="hljs-keyword">await</span> <span class="hljs-title class_">WebAssembly</span>.<span class="hljs-title function_">compile</span>(
    <span class="hljs-keyword">await</span> <span class="hljs-title function_">readFile</span>(<span class="hljs-title function_">join</span>(__dirname, <span class="hljs-string">'demo.wasm'</span>)),
  );
  <span class="hljs-keyword">const</span> instance = <span class="hljs-keyword">await</span> <span class="hljs-title class_">WebAssembly</span>.<span class="hljs-title function_">instantiate</span>(wasm, wasi.<span class="hljs-title function_">getImportObject</span>());

  wasi.<span class="hljs-title function_">start</span>(instance);
})();</code><button class="copy-button">copy</button></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> <button class="copy-button">copy</button></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-bash">wat2wasm demo.wat</code> <button class="copy-button">copy</button></pre>
<section><h3>Security<span><a class="mark" href="#all_wasi_security" id="all_wasi_security">#</a></span><a aria-hidden="true" class="legacy" id="wasi_security"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.11.0</td>
<td><p>Clarify WASI security properties.</p></td></tr>
<tr><td>v20.11.0</td>
<td><p><span>Added in: v20.11.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>WASI provides a capabilities-based model through which applications are provided
their own custom <code>env</code>, <code>preopens</code>, <code>stdin</code>, <code>stdout</code>, <code>stderr</code>, and <code>exit</code>
capabilities.</p>
<p><strong>The current Node.js threat model does not provide secure sandboxing as is
present in some WASI runtimes.</strong></p>
<p>While the capability features are supported, they do not form a security model
in Node.js. For example, the file system sandboxing can be escaped with various
techniques. The project is exploring whether these security guarantees could be
added in future.</p>
</section><section><h3>Class: <code>WASI</code><span><a class="mark" href="#all_wasi_class-wasi" id="all_wasi_class-wasi">#</a></span><a aria-hidden="true" class="legacy" id="wasi_class_wasi"></a></h3>
<div class="api_metadata">
<span>Added in: v13.3.0, 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 environment.</p>
<h4><code>new WASI([options])</code><span><a class="mark" href="#all_wasi_new-wasioptions" id="all_wasi_new-wasioptions">#</a></span><a aria-hidden="true" class="legacy" id="wasi_new_wasi_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.1.0</td>
<td><p>default value of returnOnExit changed to true.</p></td></tr>
<tr><td>v20.0.0</td>
<td><p>The version option is now required and has no default value.</p></td></tr>
<tr><td>v19.8.0</td>
<td><p>version field added to options.</p></td></tr>
<tr><td>v13.3.0, v12.16.0</td>
<td><p><span>Added in: v13.3.0, v12.16.0</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>
<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
local directory structure. The string keys of <code>preopens</code> are treated as
directories within the file system. 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, when WASI applications call
<code>__wasi_proc_exit()</code>  <code>wasi.start()</code> will return with the exit code
specified rather than terminating the process. Setting this option to
<code>false</code> will cause the Node.js process to exit with the specified
exit code instead.  <strong>Default:</strong> <code>true</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>
<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 version of WASI requested. Currently the only
supported versions are <code>unstable</code> and <code>preview1</code>. This option is
mandatory.</li>
</ul>
</li>
</ul>
<h4><code>wasi.getImportObject()</code><span><a class="mark" href="#all_wasi_wasigetimportobject" id="all_wasi_wasigetimportobject">#</a></span><a aria-hidden="true" class="legacy" id="wasi_wasi_getimportobject"></a></h4>
<div class="api_metadata">
<span>Added in: v19.8.0</span>
</div>
<p>Return an import object that can be passed to <code>WebAssembly.instantiate()</code> if
no other WASM imports are needed beyond those provided by WASI.</p>
<p>If version <code>unstable</code> was passed into the constructor it will return:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span> wasi_unstable<span class="hljs-punctuation">:</span> wasi.wasiImport <span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<p>If version <code>preview1</code> was passed into the constructor or no version was
specified it will return:</p>
<pre><code class="language-json"><span class="hljs-punctuation">{</span> wasi_snapshot_preview1<span class="hljs-punctuation">:</span> wasi.wasiImport <span class="hljs-punctuation">}</span></code> <button class="copy-button">copy</button></pre>
<h4><code>wasi.start(instance)</code><span><a class="mark" href="#all_wasi_wasistartinstance" id="all_wasi_wasistartinstance">#</a></span><a aria-hidden="true" class="legacy" id="wasi_wasi_start_instance"></a></h4>
<div class="api_metadata">
<span>Added in: v13.3.0, 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>
<h4><code>wasi.initialize(instance)</code><span><a class="mark" href="#all_wasi_wasiinitializeinstance" id="all_wasi_wasiinitializeinstance">#</a></span><a aria-hidden="true" class="legacy" id="wasi_wasi_initialize_instance"></a></h4>
<div class="api_metadata">
<span>Added in: v14.6.0, v12.19.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 initialize <code>instance</code> as a WASI reactor by invoking its
<code>_initialize()</code> export, if it is present. If <code>instance</code> contains a <code>_start()</code>
export, then an exception is thrown.</p>
<p><code>initialize()</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>initialize()</code> is called more than once, an exception is thrown.</p>
<h4><code>wasi.wasiImport</code><span><a class="mark" href="#all_wasi_wasiwasiimport" id="all_wasi_wasiwasiimport">#</a></span><a aria-hidden="true" class="legacy" id="wasi_wasi_wasiimport"></a></h4>
<div class="api_metadata">
<span>Added in: v13.3.0, 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></section>
        </section>
<section><h2>Web Crypto API<span><a class="mark" href="#all_webcrypto_web-crypto-api" id="all_webcrypto_web-crypto-api">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_web_crypto_api"></a></h2>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.0.0</td>
<td><p>Arguments are now coerced and validated as per their WebIDL definitions like in other Web Crypto API implementations.</p></td></tr>
<tr><td>v19.0.0</td>
<td><p>No longer experimental except for the <code>Ed25519</code>, <code>Ed448</code>, <code>X25519</code>, and <code>X448</code> algorithms.</p></td></tr>
<tr><td>v18.4.0, v16.17.0</td>
<td><p>Removed proprietary <code>'node.keyObject'</code> import/export format.</p></td></tr>
<tr><td>v18.4.0, v16.17.0</td>
<td><p>Removed proprietary <code>'NODE-DSA'</code>, <code>'NODE-DH'</code>, and <code>'NODE-SCRYPT'</code> algorithms.</p></td></tr>
<tr><td>v18.4.0, v16.17.0</td>
<td><p>Added <code>'Ed25519'</code>, <code>'Ed448'</code>, <code>'X25519'</code>, and <code>'X448'</code> algorithms.</p></td></tr>
<tr><td>v18.4.0, v16.17.0</td>
<td><p>Removed proprietary <code>'NODE-ED25519'</code> and <code>'NODE-ED448'</code> algorithms.</p></td></tr>
<tr><td>v18.4.0, v16.17.0</td>
<td><p>Removed proprietary <code>'NODE-X25519'</code> and <code>'NODE-X448'</code> named curves from the <code>'ECDH'</code> algorithm.</p></td></tr>
</tbody></table>
</details>
</div>

<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p>Node.js provides an implementation of the standard <a href="https://www.w3.org/TR/WebCryptoAPI/">Web Crypto API</a>.</p>
<p>Use <code>globalThis.crypto</code> or <code>require('node:crypto').webcrypto</code> to access this
module.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { subtle } = globalThis.<span class="hljs-property">crypto</span>;

(<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) {

  <span class="hljs-keyword">const</span> key = <span class="hljs-keyword">await</span> subtle.<span class="hljs-title function_">generateKey</span>({
    <span class="hljs-attr">name</span>: <span class="hljs-string">'HMAC'</span>,
    <span class="hljs-attr">hash</span>: <span class="hljs-string">'SHA-256'</span>,
    <span class="hljs-attr">length</span>: <span class="hljs-number">256</span>,
  }, <span class="hljs-literal">true</span>, [<span class="hljs-string">'sign'</span>, <span class="hljs-string">'verify'</span>]);

  <span class="hljs-keyword">const</span> enc = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TextEncoder</span>();
  <span class="hljs-keyword">const</span> message = enc.<span class="hljs-title function_">encode</span>(<span class="hljs-string">'I love cupcakes'</span>);

  <span class="hljs-keyword">const</span> digest = <span class="hljs-keyword">await</span> subtle.<span class="hljs-title function_">sign</span>({
    <span class="hljs-attr">name</span>: <span class="hljs-string">'HMAC'</span>,
  }, key, message);

})();</code> <button class="copy-button">copy</button></pre>
<section><h3>Examples<span><a class="mark" href="#all_webcrypto_examples" id="all_webcrypto_examples">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_examples"></a></h3>
<h4>Generating keys<span><a class="mark" href="#all_webcrypto_generating-keys" id="all_webcrypto_generating-keys">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_generating_keys"></a></h4>
<p>The <a href="#all_webcrypto_class-subtlecrypto" class="type">&#x3C;SubtleCrypto></a> class can be used to generate symmetric (secret) keys
or asymmetric key pairs (public key and private key).</p>
<h5>AES keys<span><a class="mark" href="#all_webcrypto_aes-keys" id="all_webcrypto_aes-keys">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_aes_keys"></a></h5>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { subtle } = globalThis.<span class="hljs-property">crypto</span>;

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">generateAesKey</span>(<span class="hljs-params">length = <span class="hljs-number">256</span></span>) {
  <span class="hljs-keyword">const</span> key = <span class="hljs-keyword">await</span> subtle.<span class="hljs-title function_">generateKey</span>({
    <span class="hljs-attr">name</span>: <span class="hljs-string">'AES-CBC'</span>,
    length,
  }, <span class="hljs-literal">true</span>, [<span class="hljs-string">'encrypt'</span>, <span class="hljs-string">'decrypt'</span>]);

  <span class="hljs-keyword">return</span> key;
}</code> <button class="copy-button">copy</button></pre>
<h5>ECDSA key pairs<span><a class="mark" href="#all_webcrypto_ecdsa-key-pairs" id="all_webcrypto_ecdsa-key-pairs">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_ecdsa_key_pairs"></a></h5>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { subtle } = globalThis.<span class="hljs-property">crypto</span>;

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">generateEcKey</span>(<span class="hljs-params">namedCurve = <span class="hljs-string">'P-521'</span></span>) {
  <span class="hljs-keyword">const</span> {
    publicKey,
    privateKey,
  } = <span class="hljs-keyword">await</span> subtle.<span class="hljs-title function_">generateKey</span>({
    <span class="hljs-attr">name</span>: <span class="hljs-string">'ECDSA'</span>,
    namedCurve,
  }, <span class="hljs-literal">true</span>, [<span class="hljs-string">'sign'</span>, <span class="hljs-string">'verify'</span>]);

  <span class="hljs-keyword">return</span> { publicKey, privateKey };
}</code> <button class="copy-button">copy</button></pre>
<h5>Ed25519/Ed448/X25519/X448 key pairs<span><a class="mark" href="#all_webcrypto_ed25519ed448x25519x448-key-pairs" id="all_webcrypto_ed25519ed448x25519x448-key-pairs">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_ed25519_ed448_x25519_x448_key_pairs"></a></h5>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { subtle } = globalThis.<span class="hljs-property">crypto</span>;

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">generateEd25519Key</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">return</span> subtle.<span class="hljs-title function_">generateKey</span>({
    <span class="hljs-attr">name</span>: <span class="hljs-string">'Ed25519'</span>,
  }, <span class="hljs-literal">true</span>, [<span class="hljs-string">'sign'</span>, <span class="hljs-string">'verify'</span>]);
}

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">generateX25519Key</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">return</span> subtle.<span class="hljs-title function_">generateKey</span>({
    <span class="hljs-attr">name</span>: <span class="hljs-string">'X25519'</span>,
  }, <span class="hljs-literal">true</span>, [<span class="hljs-string">'deriveKey'</span>]);
}</code> <button class="copy-button">copy</button></pre>
<h5>HMAC keys<span><a class="mark" href="#all_webcrypto_hmac-keys" id="all_webcrypto_hmac-keys">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_hmac_keys"></a></h5>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { subtle } = globalThis.<span class="hljs-property">crypto</span>;

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">generateHmacKey</span>(<span class="hljs-params">hash = <span class="hljs-string">'SHA-256'</span></span>) {
  <span class="hljs-keyword">const</span> key = <span class="hljs-keyword">await</span> subtle.<span class="hljs-title function_">generateKey</span>({
    <span class="hljs-attr">name</span>: <span class="hljs-string">'HMAC'</span>,
    hash,
  }, <span class="hljs-literal">true</span>, [<span class="hljs-string">'sign'</span>, <span class="hljs-string">'verify'</span>]);

  <span class="hljs-keyword">return</span> key;
}</code> <button class="copy-button">copy</button></pre>
<h5>RSA key pairs<span><a class="mark" href="#all_webcrypto_rsa-key-pairs" id="all_webcrypto_rsa-key-pairs">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_rsa_key_pairs"></a></h5>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { subtle } = globalThis.<span class="hljs-property">crypto</span>;
<span class="hljs-keyword">const</span> publicExponent = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>([<span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>]);

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">generateRsaKey</span>(<span class="hljs-params">modulusLength = <span class="hljs-number">2048</span>, hash = <span class="hljs-string">'SHA-256'</span></span>) {
  <span class="hljs-keyword">const</span> {
    publicKey,
    privateKey,
  } = <span class="hljs-keyword">await</span> subtle.<span class="hljs-title function_">generateKey</span>({
    <span class="hljs-attr">name</span>: <span class="hljs-string">'RSASSA-PKCS1-v1_5'</span>,
    modulusLength,
    publicExponent,
    hash,
  }, <span class="hljs-literal">true</span>, [<span class="hljs-string">'sign'</span>, <span class="hljs-string">'verify'</span>]);

  <span class="hljs-keyword">return</span> { publicKey, privateKey };
}</code> <button class="copy-button">copy</button></pre>
<h4>Encryption and decryption<span><a class="mark" href="#all_webcrypto_encryption-and-decryption" id="all_webcrypto_encryption-and-decryption">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_encryption_and_decryption"></a></h4>
<pre><code class="language-js"><span class="hljs-keyword">const</span> crypto = globalThis.<span class="hljs-property">crypto</span>;

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">aesEncrypt</span>(<span class="hljs-params">plaintext</span>) {
  <span class="hljs-keyword">const</span> ec = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TextEncoder</span>();
  <span class="hljs-keyword">const</span> key = <span class="hljs-keyword">await</span> <span class="hljs-title function_">generateAesKey</span>();
  <span class="hljs-keyword">const</span> iv = crypto.<span class="hljs-title function_">getRandomValues</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(<span class="hljs-number">16</span>));

  <span class="hljs-keyword">const</span> ciphertext = <span class="hljs-keyword">await</span> crypto.<span class="hljs-property">subtle</span>.<span class="hljs-title function_">encrypt</span>({
    <span class="hljs-attr">name</span>: <span class="hljs-string">'AES-CBC'</span>,
    iv,
  }, key, ec.<span class="hljs-title function_">encode</span>(plaintext));

  <span class="hljs-keyword">return</span> {
    key,
    iv,
    ciphertext,
  };
}

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">aesDecrypt</span>(<span class="hljs-params">ciphertext, key, iv</span>) {
  <span class="hljs-keyword">const</span> dec = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TextDecoder</span>();
  <span class="hljs-keyword">const</span> plaintext = <span class="hljs-keyword">await</span> crypto.<span class="hljs-property">subtle</span>.<span class="hljs-title function_">decrypt</span>({
    <span class="hljs-attr">name</span>: <span class="hljs-string">'AES-CBC'</span>,
    iv,
  }, key, ciphertext);

  <span class="hljs-keyword">return</span> dec.<span class="hljs-title function_">decode</span>(plaintext);
}</code> <button class="copy-button">copy</button></pre>
<h4>Exporting and importing keys<span><a class="mark" href="#all_webcrypto_exporting-and-importing-keys" id="all_webcrypto_exporting-and-importing-keys">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_exporting_and_importing_keys"></a></h4>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { subtle } = globalThis.<span class="hljs-property">crypto</span>;

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">generateAndExportHmacKey</span>(<span class="hljs-params">format = <span class="hljs-string">'jwk'</span>, hash = <span class="hljs-string">'SHA-512'</span></span>) {
  <span class="hljs-keyword">const</span> key = <span class="hljs-keyword">await</span> subtle.<span class="hljs-title function_">generateKey</span>({
    <span class="hljs-attr">name</span>: <span class="hljs-string">'HMAC'</span>,
    hash,
  }, <span class="hljs-literal">true</span>, [<span class="hljs-string">'sign'</span>, <span class="hljs-string">'verify'</span>]);

  <span class="hljs-keyword">return</span> subtle.<span class="hljs-title function_">exportKey</span>(format, key);
}

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">importHmacKey</span>(<span class="hljs-params">keyData, format = <span class="hljs-string">'jwk'</span>, hash = <span class="hljs-string">'SHA-512'</span></span>) {
  <span class="hljs-keyword">const</span> key = <span class="hljs-keyword">await</span> subtle.importKey(format, keyData, {
    <span class="hljs-attr">name</span>: <span class="hljs-string">'HMAC'</span>,
    hash,
  }, <span class="hljs-literal">true</span>, [<span class="hljs-string">'sign'</span>, <span class="hljs-string">'verify'</span>]);

  <span class="hljs-keyword">return</span> key;
}</code> <button class="copy-button">copy</button></pre>
<h4>Wrapping and unwrapping keys<span><a class="mark" href="#all_webcrypto_wrapping-and-unwrapping-keys" id="all_webcrypto_wrapping-and-unwrapping-keys">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_wrapping_and_unwrapping_keys"></a></h4>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { subtle } = globalThis.<span class="hljs-property">crypto</span>;

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">generateAndWrapHmacKey</span>(<span class="hljs-params">format = <span class="hljs-string">'jwk'</span>, hash = <span class="hljs-string">'SHA-512'</span></span>) {
  <span class="hljs-keyword">const</span> [
    key,
    wrappingKey,
  ] = <span class="hljs-keyword">await</span> <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">all</span>([
    subtle.<span class="hljs-title function_">generateKey</span>({
      <span class="hljs-attr">name</span>: <span class="hljs-string">'HMAC'</span>, hash,
    }, <span class="hljs-literal">true</span>, [<span class="hljs-string">'sign'</span>, <span class="hljs-string">'verify'</span>]),
    subtle.<span class="hljs-title function_">generateKey</span>({
      <span class="hljs-attr">name</span>: <span class="hljs-string">'AES-KW'</span>,
      <span class="hljs-attr">length</span>: <span class="hljs-number">256</span>,
    }, <span class="hljs-literal">true</span>, [<span class="hljs-string">'wrapKey'</span>, <span class="hljs-string">'unwrapKey'</span>]),
  ]);

  <span class="hljs-keyword">const</span> wrappedKey = <span class="hljs-keyword">await</span> subtle.<span class="hljs-title function_">wrapKey</span>(format, key, wrappingKey, <span class="hljs-string">'AES-KW'</span>);

  <span class="hljs-keyword">return</span> { wrappedKey, wrappingKey };
}

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">unwrapHmacKey</span>(<span class="hljs-params">
  wrappedKey,
  wrappingKey,
  format = <span class="hljs-string">'jwk'</span>,
  hash = <span class="hljs-string">'SHA-512'</span></span>) {

  <span class="hljs-keyword">const</span> key = <span class="hljs-keyword">await</span> subtle.<span class="hljs-title function_">unwrapKey</span>(
    format,
    wrappedKey,
    wrappingKey,
    <span class="hljs-string">'AES-KW'</span>,
    { <span class="hljs-attr">name</span>: <span class="hljs-string">'HMAC'</span>, hash },
    <span class="hljs-literal">true</span>,
    [<span class="hljs-string">'sign'</span>, <span class="hljs-string">'verify'</span>]);

  <span class="hljs-keyword">return</span> key;
}</code> <button class="copy-button">copy</button></pre>
<h4>Sign and verify<span><a class="mark" href="#all_webcrypto_sign-and-verify" id="all_webcrypto_sign-and-verify">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_sign_and_verify"></a></h4>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { subtle } = globalThis.<span class="hljs-property">crypto</span>;

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">sign</span>(<span class="hljs-params">key, data</span>) {
  <span class="hljs-keyword">const</span> ec = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TextEncoder</span>();
  <span class="hljs-keyword">const</span> signature =
    <span class="hljs-keyword">await</span> subtle.<span class="hljs-title function_">sign</span>(<span class="hljs-string">'RSASSA-PKCS1-v1_5'</span>, key, ec.<span class="hljs-title function_">encode</span>(data));
  <span class="hljs-keyword">return</span> signature;
}

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">verify</span>(<span class="hljs-params">key, signature, data</span>) {
  <span class="hljs-keyword">const</span> ec = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TextEncoder</span>();
  <span class="hljs-keyword">const</span> verified =
    <span class="hljs-keyword">await</span> subtle.<span class="hljs-title function_">verify</span>(
      <span class="hljs-string">'RSASSA-PKCS1-v1_5'</span>,
      key,
      signature,
      ec.<span class="hljs-title function_">encode</span>(data));
  <span class="hljs-keyword">return</span> verified;
}</code> <button class="copy-button">copy</button></pre>
<h4>Deriving bits and keys<span><a class="mark" href="#all_webcrypto_deriving-bits-and-keys" id="all_webcrypto_deriving-bits-and-keys">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_deriving_bits_and_keys"></a></h4>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { subtle } = globalThis.<span class="hljs-property">crypto</span>;

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">pbkdf2</span>(<span class="hljs-params">pass, salt, iterations = <span class="hljs-number">1000</span>, length = <span class="hljs-number">256</span></span>) {
  <span class="hljs-keyword">const</span> ec = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TextEncoder</span>();
  <span class="hljs-keyword">const</span> key = <span class="hljs-keyword">await</span> subtle.importKey(
    <span class="hljs-string">'raw'</span>,
    ec.<span class="hljs-title function_">encode</span>(pass),
    <span class="hljs-string">'PBKDF2'</span>,
    <span class="hljs-literal">false</span>,
    [<span class="hljs-string">'deriveBits'</span>]);
  <span class="hljs-keyword">const</span> bits = <span class="hljs-keyword">await</span> subtle.<span class="hljs-title function_">deriveBits</span>({
    <span class="hljs-attr">name</span>: <span class="hljs-string">'PBKDF2'</span>,
    <span class="hljs-attr">hash</span>: <span class="hljs-string">'SHA-512'</span>,
    <span class="hljs-attr">salt</span>: ec.<span class="hljs-title function_">encode</span>(salt),
    iterations,
  }, key, length);
  <span class="hljs-keyword">return</span> bits;
}

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">pbkdf2Key</span>(<span class="hljs-params">pass, salt, iterations = <span class="hljs-number">1000</span>, length = <span class="hljs-number">256</span></span>) {
  <span class="hljs-keyword">const</span> ec = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TextEncoder</span>();
  <span class="hljs-keyword">const</span> keyMaterial = <span class="hljs-keyword">await</span> subtle.importKey(
    <span class="hljs-string">'raw'</span>,
    ec.<span class="hljs-title function_">encode</span>(pass),
    <span class="hljs-string">'PBKDF2'</span>,
    <span class="hljs-literal">false</span>,
    [<span class="hljs-string">'deriveKey'</span>]);
  <span class="hljs-keyword">const</span> key = <span class="hljs-keyword">await</span> subtle.<span class="hljs-title function_">deriveKey</span>({
    <span class="hljs-attr">name</span>: <span class="hljs-string">'PBKDF2'</span>,
    <span class="hljs-attr">hash</span>: <span class="hljs-string">'SHA-512'</span>,
    <span class="hljs-attr">salt</span>: ec.<span class="hljs-title function_">encode</span>(salt),
    iterations,
  }, keyMaterial, {
    <span class="hljs-attr">name</span>: <span class="hljs-string">'AES-GCM'</span>,
    length,
  }, <span class="hljs-literal">true</span>, [<span class="hljs-string">'encrypt'</span>, <span class="hljs-string">'decrypt'</span>]);
  <span class="hljs-keyword">return</span> key;
}</code> <button class="copy-button">copy</button></pre>
<h4>Digest<span><a class="mark" href="#all_webcrypto_digest" id="all_webcrypto_digest">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_digest"></a></h4>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { subtle } = globalThis.<span class="hljs-property">crypto</span>;

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">digest</span>(<span class="hljs-params">data, algorithm = <span class="hljs-string">'SHA-512'</span></span>) {
  <span class="hljs-keyword">const</span> ec = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TextEncoder</span>();
  <span class="hljs-keyword">const</span> digest = <span class="hljs-keyword">await</span> subtle.<span class="hljs-title function_">digest</span>(algorithm, ec.<span class="hljs-title function_">encode</span>(data));
  <span class="hljs-keyword">return</span> digest;
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Algorithm matrix<span><a class="mark" href="#all_webcrypto_algorithm-matrix" id="all_webcrypto_algorithm-matrix">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_algorithm_matrix"></a></h3>
<p>The table details the algorithms supported by the Node.js Web Crypto API
implementation and the APIs supported for each:</p>
































































































































































































































































































































<table><thead><tr><th>Algorithm</th><th><code>generateKey</code></th><th><code>exportKey</code></th><th><code>importKey</code></th><th><code>encrypt</code></th><th><code>decrypt</code></th><th><code>wrapKey</code></th><th><code>unwrapKey</code></th><th><code>deriveBits</code></th><th><code>deriveKey</code></th><th><code>sign</code></th><th><code>verify</code></th><th><code>digest</code></th></tr></thead><tbody><tr><td><code>'RSASSA-PKCS1-v1_5'</code></td><td>✔</td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td><td></td></tr><tr><td><code>'RSA-PSS'</code></td><td>✔</td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td><td></td></tr><tr><td><code>'RSA-OAEP'</code></td><td>✔</td><td>✔</td><td>✔</td><td>✔</td><td>✔</td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td><td></td></tr><tr><td><code>'ECDSA'</code></td><td>✔</td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td><td></td></tr><tr><td><code>'Ed25519'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></td><td>✔</td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td><td></td></tr><tr><td><code>'Ed448'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-2" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></td><td>✔</td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td><td></td></tr><tr><td><code>'ECDH'</code></td><td>✔</td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td><td></td><td></td><td></td></tr><tr><td><code>'X25519'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-3" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></td><td>✔</td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td><td></td><td></td><td></td></tr><tr><td><code>'X448'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-4" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></td><td>✔</td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td><td></td><td></td><td></td></tr><tr><td><code>'AES-CTR'</code></td><td>✔</td><td>✔</td><td>✔</td><td>✔</td><td>✔</td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td><td></td></tr><tr><td><code>'AES-CBC'</code></td><td>✔</td><td>✔</td><td>✔</td><td>✔</td><td>✔</td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td><td></td></tr><tr><td><code>'AES-GCM'</code></td><td>✔</td><td>✔</td><td>✔</td><td>✔</td><td>✔</td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td><td></td></tr><tr><td><code>'AES-KW'</code></td><td>✔</td><td>✔</td><td>✔</td><td></td><td></td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td><td></td></tr><tr><td><code>'HMAC'</code></td><td>✔</td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td><td></td></tr><tr><td><code>'HKDF'</code></td><td></td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td><td></td><td></td><td></td></tr><tr><td><code>'PBKDF2'</code></td><td></td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td><td></td><td></td><td></td></tr><tr><td><code>'SHA-1'</code></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td>✔</td></tr><tr><td><code>'SHA-256'</code></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td>✔</td></tr><tr><td><code>'SHA-384'</code></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td>✔</td></tr><tr><td><code>'SHA-512'</code></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td>✔</td></tr></tbody></table>
</section><section><h3>Class: <code>Crypto</code><span><a class="mark" href="#all_webcrypto_class-crypto" id="all_webcrypto_class-crypto">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_crypto"></a></h3>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p><code>globalThis.crypto</code> is an instance of the <code>Crypto</code>
class. <code>Crypto</code> is a singleton that provides access to the remainder of the
crypto API.</p>
<h4><code>crypto.subtle</code><span><a class="mark" href="#all_webcrypto_cryptosubtle" id="all_webcrypto_cryptosubtle">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_crypto_subtle"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="#all_webcrypto_class-subtlecrypto" class="type">&#x3C;SubtleCrypto></a></li>
</ul>
<p>Provides access to the <code>SubtleCrypto</code> API.</p>
<h4><code>crypto.getRandomValues(typedArray)</code><span><a class="mark" href="#all_webcrypto_cryptogetrandomvaluestypedarray" id="all_webcrypto_cryptogetrandomvaluestypedarray">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_crypto_getrandomvalues_typedarray"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li><code>typedArray</code> <a href="#all_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></li>
<li>Returns: <a href="#all_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></li>
</ul>
<p>Generates cryptographically strong random values. The given <code>typedArray</code> is
filled with random values, and a reference to <code>typedArray</code> is returned.</p>
<p>The given <code>typedArray</code> must be an integer-based instance of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a>,
i.e. <code>Float32Array</code> and <code>Float64Array</code> are not accepted.</p>
<p>An error will be thrown if the given <code>typedArray</code> is larger than 65,536 bytes.</p>
<h4><code>crypto.randomUUID()</code><span><a class="mark" href="#all_webcrypto_cryptorandomuuid" id="all_webcrypto_cryptorandomuuid">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_crypto_randomuuid"></a></h4>
<div class="api_metadata">
<span>Added in: v16.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>Generates a random <a href="https://www.rfc-editor.org/rfc/rfc4122.txt">RFC 4122</a> version 4 UUID. The UUID is generated using a
cryptographic pseudorandom number generator.</p>
</section><section><h3>Class: <code>CryptoKey</code><span><a class="mark" href="#all_webcrypto_class-cryptokey" id="all_webcrypto_class-cryptokey">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_cryptokey"></a></h3>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<h4><code>cryptoKey.algorithm</code><span><a class="mark" href="#all_webcrypto_cryptokeyalgorithm" id="all_webcrypto_cryptokeyalgorithm">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_cryptokey_algorithm"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<!--lint disable maximum-line-length remark-lint-->
<ul>
<li>Type: <a href="#all_webcrypto_class-aeskeygenparams" class="type">&#x3C;AesKeyGenParams></a> | <a href="#all_webcrypto_class-rsahashedkeygenparams" class="type">&#x3C;RsaHashedKeyGenParams></a> | <a href="#all_webcrypto_class-eckeygenparams" class="type">&#x3C;EcKeyGenParams></a> | <a href="#all_webcrypto_class-hmackeygenparams" class="type">&#x3C;HmacKeyGenParams></a></li>
</ul>
<!--lint enable maximum-line-length remark-lint-->
<p>An object detailing the algorithm for which the key can be used along with
additional algorithm-specific parameters.</p>
<p>Read-only.</p>
<h4><code>cryptoKey.extractable</code><span><a class="mark" href="#all_webcrypto_cryptokeyextractable" id="all_webcrypto_cryptokeyextractable">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_cryptokey_extractable"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<p>When <code>true</code>, the <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></a> can be extracted using either
<code>subtleCrypto.exportKey()</code> or <code>subtleCrypto.wrapKey()</code>.</p>
<p>Read-only.</p>
<h4><code>cryptoKey.type</code><span><a class="mark" href="#all_webcrypto_cryptokeytype" id="all_webcrypto_cryptokeytype">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_cryptokey_type"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> One of <code>'secret'</code>, <code>'private'</code>, or <code>'public'</code>.</li>
</ul>
<p>A string identifying whether the key is a symmetric (<code>'secret'</code>) or
asymmetric (<code>'private'</code> or <code>'public'</code>) key.</p>
<h4><code>cryptoKey.usages</code><span><a class="mark" href="#all_webcrypto_cryptokeyusages" id="all_webcrypto_cryptokeyusages">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_cryptokey_usages"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a></li>
</ul>
<p>An array of strings identifying the operations for which the
key may be used.</p>
<p>The possible usages are:</p>
<ul>
<li><code>'encrypt'</code> - The key may be used to encrypt data.</li>
<li><code>'decrypt'</code> - The key may be used to decrypt data.</li>
<li><code>'sign'</code> - The key may be used to generate digital signatures.</li>
<li><code>'verify'</code> - The key may be used to verify digital signatures.</li>
<li><code>'deriveKey'</code> - The key may be used to derive a new key.</li>
<li><code>'deriveBits'</code> - The key may be used to derive bits.</li>
<li><code>'wrapKey'</code> - The key may be used to wrap another key.</li>
<li><code>'unwrapKey'</code> - The key may be used to unwrap another key.</li>
</ul>
<p>Valid key usages depend on the key algorithm (identified by
<code>cryptokey.algorithm.name</code>).</p>
































































































































































































<table><thead><tr><th>Key Type</th><th><code>'encrypt'</code></th><th><code>'decrypt'</code></th><th><code>'sign'</code></th><th><code>'verify'</code></th><th><code>'deriveKey'</code></th><th><code>'deriveBits'</code></th><th><code>'wrapKey'</code></th><th><code>'unwrapKey'</code></th></tr></thead><tbody><tr><td><code>'AES-CBC'</code></td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td></tr><tr><td><code>'AES-CTR'</code></td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td></tr><tr><td><code>'AES-GCM'</code></td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td></tr><tr><td><code>'AES-KW'</code></td><td></td><td></td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td></tr><tr><td><code>'ECDH'</code></td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td><td></td><td></td></tr><tr><td><code>'X25519'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-5" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td><td></td><td></td></tr><tr><td><code>'X448'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-6" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td><td></td><td></td></tr><tr><td><code>'ECDSA'</code></td><td></td><td></td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td></tr><tr><td><code>'Ed25519'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-7" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></td><td></td><td></td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td></tr><tr><td><code>'Ed448'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-8" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></td><td></td><td></td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td></tr><tr><td><code>'HDKF'</code></td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td><td></td><td></td></tr><tr><td><code>'HMAC'</code></td><td></td><td></td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td></tr><tr><td><code>'PBKDF2'</code></td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td><td></td><td></td></tr><tr><td><code>'RSA-OAEP'</code></td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td><td>✔</td><td>✔</td></tr><tr><td><code>'RSA-PSS'</code></td><td></td><td></td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td></tr><tr><td><code>'RSASSA-PKCS1-v1_5'</code></td><td></td><td></td><td>✔</td><td>✔</td><td></td><td></td><td></td><td></td></tr></tbody></table>
</section><section><h3>Class: <code>CryptoKeyPair</code><span><a class="mark" href="#all_webcrypto_class-cryptokeypair" id="all_webcrypto_class-cryptokeypair">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_cryptokeypair"></a></h3>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<p>The <code>CryptoKeyPair</code> is a simple dictionary object with <code>publicKey</code> and
<code>privateKey</code> properties, representing an asymmetric key pair.</p>
<h4><code>cryptoKeyPair.privateKey</code><span><a class="mark" href="#all_webcrypto_cryptokeypairprivatekey" id="all_webcrypto_cryptokeypairprivatekey">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_cryptokeypair_privatekey"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></a> A <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></a> whose <code>type</code> will be <code>'private'</code>.</li>
</ul>
<h4><code>cryptoKeyPair.publicKey</code><span><a class="mark" href="#all_webcrypto_cryptokeypairpublickey" id="all_webcrypto_cryptokeypairpublickey">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_cryptokeypair_publickey"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></a> A <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></a> whose <code>type</code> will be <code>'public'</code>.</li>
</ul>
</section><section><h3>Class: <code>SubtleCrypto</code><span><a class="mark" href="#all_webcrypto_class-subtlecrypto" id="all_webcrypto_class-subtlecrypto">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_subtlecrypto"></a></h3>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<h4><code>subtle.decrypt(algorithm, key, data)</code><span><a class="mark" href="#all_webcrypto_subtledecryptalgorithm-key-data" id="all_webcrypto_subtledecryptalgorithm-key-data">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_subtle_decrypt_algorithm_key_data"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li><code>algorithm</code>: <a href="#all_webcrypto_class-rsaoaepparams" class="type">&#x3C;RsaOaepParams></a> | <a href="#all_webcrypto_class-aesctrparams" class="type">&#x3C;AesCtrParams></a> | <a href="#all_webcrypto_class-aescbcparams" class="type">&#x3C;AesCbcParams></a> | <a href="#all_webcrypto_class-aesgcmparams" class="type">&#x3C;AesGcmParams></a></li>
<li><code>key</code>: <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></a></li>
<li><code>data</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/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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> Fulfills with an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a></li>
</ul>
<p>Using the method and parameters specified in <code>algorithm</code> and the keying
material provided by <code>key</code>, <code>subtle.decrypt()</code> attempts to decipher the
provided <code>data</code>. If successful, the returned promise will be resolved with
an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> containing the plaintext result.</p>
<p>The algorithms currently supported include:</p>
<ul>
<li><code>'RSA-OAEP'</code></li>
<li><code>'AES-CTR'</code></li>
<li><code>'AES-CBC'</code></li>
<li><code>'AES-GCM'</code></li>
</ul>
<h4><code>subtle.deriveBits(algorithm, baseKey[, length])</code><span><a class="mark" href="#all_webcrypto_subtlederivebitsalgorithm-basekey-length" id="all_webcrypto_subtlederivebitsalgorithm-basekey-length">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_subtle_derivebits_algorithm_basekey_length"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.17.0</td>
<td><p>The length parameter is now optional for <code>'ECDH'</code>, <code>'X25519'</code>, and <code>'X448'</code>.</p></td></tr>
<tr><td>v18.4.0, v16.17.0</td>
<td><p>Added <code>'X25519'</code>, and <code>'X448'</code> algorithms.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p><span>Added in: v15.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<!--lint disable maximum-line-length remark-lint-->
<ul>
<li><code>algorithm</code>: <a href="#all_webcrypto_class-algorithmidentifier" class="type">&#x3C;AlgorithmIdentifier></a> | <a href="#all_webcrypto_class-ecdhkeyderiveparams" class="type">&#x3C;EcdhKeyDeriveParams></a> | <a href="#all_webcrypto_class-hkdfparams" class="type">&#x3C;HkdfParams></a> | <a href="#all_webcrypto_class-pbkdf2params" class="type">&#x3C;Pbkdf2Params></a></li>
<li><code>baseKey</code>: <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></a></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> | <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>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> Fulfills with an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a></li>
</ul>
<!--lint enable maximum-line-length remark-lint-->
<p>Using the method and parameters specified in <code>algorithm</code> and the keying
material provided by <code>baseKey</code>, <code>subtle.deriveBits()</code> attempts to generate
<code>length</code> bits.</p>
<p>The Node.js implementation requires that <code>length</code>, when a number, is a multiple
of <code>8</code>.</p>
<p>When <code>length</code> is not provided or <code>null</code> the maximum number of bits for a given
algorithm is generated. This is allowed for the <code>'ECDH'</code>, <code>'X25519'</code>, and <code>'X448'</code>
algorithms, for other algorithms <code>length</code> is required to be a number.</p>
<p>If successful, the returned promise will be resolved with an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a>
containing the generated data.</p>
<p>The algorithms currently supported include:</p>
<ul>
<li><code>'ECDH'</code></li>
<li><code>'X25519'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-9" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></li>
<li><code>'X448'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-10" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></li>
<li><code>'HKDF'</code></li>
<li><code>'PBKDF2'</code></li>
</ul>
<h4><code>subtle.deriveKey(algorithm, baseKey, derivedKeyAlgorithm, extractable, keyUsages)</code><span><a class="mark" href="#all_webcrypto_subtlederivekeyalgorithm-basekey-derivedkeyalgorithm-extractable-keyusages" id="all_webcrypto_subtlederivekeyalgorithm-basekey-derivedkeyalgorithm-extractable-keyusages">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_subtle_derivekey_algorithm_basekey_derivedkeyalgorithm_extractable_keyusages"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.4.0, v16.17.0</td>
<td><p>Added <code>'X25519'</code>, and <code>'X448'</code> algorithms.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p><span>Added in: v15.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<!--lint disable maximum-line-length remark-lint-->
<ul>
<li><code>algorithm</code>: <a href="#all_webcrypto_class-algorithmidentifier" class="type">&#x3C;AlgorithmIdentifier></a> | <a href="#all_webcrypto_class-ecdhkeyderiveparams" class="type">&#x3C;EcdhKeyDeriveParams></a> | <a href="#all_webcrypto_class-hkdfparams" class="type">&#x3C;HkdfParams></a> | <a href="#all_webcrypto_class-pbkdf2params" class="type">&#x3C;Pbkdf2Params></a></li>
<li><code>baseKey</code>: <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></a></li>
<li><code>derivedKeyAlgorithm</code>: <a href="#all_webcrypto_class-hmackeygenparams" class="type">&#x3C;HmacKeyGenParams></a> | <a href="#all_webcrypto_class-aeskeygenparams" class="type">&#x3C;AesKeyGenParams></a></li>
<li><code>extractable</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
<li><code>keyUsages</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> See <a href="#all_webcrypto_cryptokeyusages">Key usages</a>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> Fulfills with a <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></a></li>
</ul>
<!--lint enable maximum-line-length remark-lint-->
<p>Using the method and parameters specified in <code>algorithm</code>, and the keying
material provided by <code>baseKey</code>, <code>subtle.deriveKey()</code> attempts to generate
a new <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></a> based on the method and parameters in <code>derivedKeyAlgorithm</code>.</p>
<p>Calling <code>subtle.deriveKey()</code> is equivalent to calling <code>subtle.deriveBits()</code> to
generate raw keying material, then passing the result into the
<code>subtle.importKey()</code> method using the <code>deriveKeyAlgorithm</code>, <code>extractable</code>, and
<code>keyUsages</code> parameters as input.</p>
<p>The algorithms currently supported include:</p>
<ul>
<li><code>'ECDH'</code></li>
<li><code>'X25519'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-11" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></li>
<li><code>'X448'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-12" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></li>
<li><code>'HKDF'</code></li>
<li><code>'PBKDF2'</code></li>
</ul>
<h4><code>subtle.digest(algorithm, data)</code><span><a class="mark" href="#all_webcrypto_subtledigestalgorithm-data" id="all_webcrypto_subtledigestalgorithm-data">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_subtle_digest_algorithm_data"></a></h4>
<div class="api_metadata">
<span>Added in: v15.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/Reference/Global_Objects/Object" class="type">&#x3C;Object></a></li>
<li><code>data</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/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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> Fulfills with an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a></li>
</ul>
<p>Using the method identified by <code>algorithm</code>, <code>subtle.digest()</code> attempts to
generate a digest of <code>data</code>. If successful, the returned promise is resolved
with an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> containing the computed digest.</p>
<p>If <code>algorithm</code> is provided as a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a>, it must be one of:</p>
<ul>
<li><code>'SHA-1'</code></li>
<li><code>'SHA-256'</code></li>
<li><code>'SHA-384'</code></li>
<li><code>'SHA-512'</code></li>
</ul>
<p>If <code>algorithm</code> is provided as an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>, it must have a <code>name</code> property
whose value is one of the above.</p>
<h4><code>subtle.encrypt(algorithm, key, data)</code><span><a class="mark" href="#all_webcrypto_subtleencryptalgorithm-key-data" id="all_webcrypto_subtleencryptalgorithm-key-data">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_subtle_encrypt_algorithm_key_data"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li><code>algorithm</code>: <a href="#all_webcrypto_class-rsaoaepparams" class="type">&#x3C;RsaOaepParams></a> | <a href="#all_webcrypto_class-aesctrparams" class="type">&#x3C;AesCtrParams></a> | <a href="#all_webcrypto_class-aescbcparams" class="type">&#x3C;AesCbcParams></a> | <a href="#all_webcrypto_class-aesgcmparams" class="type">&#x3C;AesGcmParams></a></li>
<li><code>key</code>: <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></a></li>
<li><code>data</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/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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> Fulfills with an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a></li>
</ul>
<p>Using the method and parameters specified by <code>algorithm</code> and the keying
material provided by <code>key</code>, <code>subtle.encrypt()</code> attempts to encipher <code>data</code>.
If successful, the returned promise is resolved with an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a>
containing the encrypted result.</p>
<p>The algorithms currently supported include:</p>
<ul>
<li><code>'RSA-OAEP'</code></li>
<li><code>'AES-CTR'</code></li>
<li><code>'AES-CBC'</code></li>
<li><code>'AES-GCM'</code></li>
</ul>
<h4><code>subtle.exportKey(format, key)</code><span><a class="mark" href="#all_webcrypto_subtleexportkeyformat-key" id="all_webcrypto_subtleexportkeyformat-key">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_subtle_exportkey_format_key"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.4.0, v16.17.0</td>
<td><p>Added <code>'Ed25519'</code>, <code>'Ed448'</code>, <code>'X25519'</code>, and <code>'X448'</code> algorithms.</p></td></tr>
<tr><td>v15.9.0</td>
<td><p>Removed <code>'NODE-DSA'</code> JWK export.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p><span>Added in: v15.0.0</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> Must be one of <code>'raw'</code>, <code>'pkcs8'</code>, <code>'spki'</code>, or <code>'jwk'</code>.</li>
<li><code>key</code>: <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> Fulfills with an <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/Object" class="type">&#x3C;Object></a>.</li>
</ul>
<p>Exports the given key into the specified format, if supported.</p>
<p>If the <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></a> is not extractable, the returned promise will reject.</p>
<p>When <code>format</code> is either <code>'pkcs8'</code> or <code>'spki'</code> and the export is successful,
the returned promise will be resolved with an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> containing the
exported key data.</p>
<p>When <code>format</code> is <code>'jwk'</code> and the export is successful, the returned promise
will be resolved with a JavaScript object conforming to the <a href="https://tools.ietf.org/html/rfc7517">JSON Web Key</a>
specification.</p>














































































































<table><thead><tr><th>Key Type</th><th><code>'spki'</code></th><th><code>'pkcs8'</code></th><th><code>'jwk'</code></th><th><code>'raw'</code></th></tr></thead><tbody><tr><td><code>'AES-CBC'</code></td><td></td><td></td><td>✔</td><td>✔</td></tr><tr><td><code>'AES-CTR'</code></td><td></td><td></td><td>✔</td><td>✔</td></tr><tr><td><code>'AES-GCM'</code></td><td></td><td></td><td>✔</td><td>✔</td></tr><tr><td><code>'AES-KW'</code></td><td></td><td></td><td>✔</td><td>✔</td></tr><tr><td><code>'ECDH'</code></td><td>✔</td><td>✔</td><td>✔</td><td>✔</td></tr><tr><td><code>'ECDSA'</code></td><td>✔</td><td>✔</td><td>✔</td><td>✔</td></tr><tr><td><code>'Ed25519'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-13" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></td><td>✔</td><td>✔</td><td>✔</td><td>✔</td></tr><tr><td><code>'Ed448'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-14" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></td><td>✔</td><td>✔</td><td>✔</td><td>✔</td></tr><tr><td><code>'HDKF'</code></td><td></td><td></td><td></td><td></td></tr><tr><td><code>'HMAC'</code></td><td></td><td></td><td>✔</td><td>✔</td></tr><tr><td><code>'PBKDF2'</code></td><td></td><td></td><td></td><td></td></tr><tr><td><code>'RSA-OAEP'</code></td><td>✔</td><td>✔</td><td>✔</td><td></td></tr><tr><td><code>'RSA-PSS'</code></td><td>✔</td><td>✔</td><td>✔</td><td></td></tr><tr><td><code>'RSASSA-PKCS1-v1_5'</code></td><td>✔</td><td>✔</td><td>✔</td><td></td></tr></tbody></table>
<h4><code>subtle.generateKey(algorithm, extractable, keyUsages)</code><span><a class="mark" href="#all_webcrypto_subtlegeneratekeyalgorithm-extractable-keyusages" id="all_webcrypto_subtlegeneratekeyalgorithm-extractable-keyusages">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_subtle_generatekey_algorithm_extractable_keyusages"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<!--lint disable maximum-line-length remark-lint-->
<ul>
<li><code>algorithm</code>: <a href="#all_webcrypto_class-algorithmidentifier" class="type">&#x3C;AlgorithmIdentifier></a> | <a href="#all_webcrypto_class-rsahashedkeygenparams" class="type">&#x3C;RsaHashedKeyGenParams></a> | <a href="#all_webcrypto_class-eckeygenparams" class="type">&#x3C;EcKeyGenParams></a> | <a href="#all_webcrypto_class-hmackeygenparams" class="type">&#x3C;HmacKeyGenParams></a> | <a href="#all_webcrypto_class-aeskeygenparams" class="type">&#x3C;AesKeyGenParams></a></li>
</ul>
<!--lint enable maximum-line-length remark-lint-->
<ul>
<li><code>extractable</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
<li><code>keyUsages</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> See <a href="#all_webcrypto_cryptokeyusages">Key usages</a>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> Fulfills with a <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></a> | <a href="#all_webcrypto_class-cryptokeypair" class="type">&#x3C;CryptoKeyPair></a></li>
</ul>
<p>Using the method and parameters provided in <code>algorithm</code>, <code>subtle.generateKey()</code>
attempts to generate new keying material. Depending the method used, the method
may generate either a single <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></a> or a <a href="#all_webcrypto_class-cryptokeypair" class="type">&#x3C;CryptoKeyPair></a>.</p>
<p>The <a href="#all_webcrypto_class-cryptokeypair" class="type">&#x3C;CryptoKeyPair></a> (public and private key) generating algorithms supported
include:</p>
<ul>
<li><code>'RSASSA-PKCS1-v1_5'</code></li>
<li><code>'RSA-PSS'</code></li>
<li><code>'RSA-OAEP'</code></li>
<li><code>'ECDSA'</code></li>
<li><code>'Ed25519'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-15" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></li>
<li><code>'Ed448'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-16" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></li>
<li><code>'ECDH'</code></li>
<li><code>'X25519'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-17" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></li>
<li><code>'X448'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-18" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></li>
</ul>
<p>The <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></a> (secret key) generating algorithms supported include:</p>
<ul>
<li><code>'HMAC'</code></li>
<li><code>'AES-CTR'</code></li>
<li><code>'AES-CBC'</code></li>
<li><code>'AES-GCM'</code></li>
<li><code>'AES-KW'</code></li>
</ul>
<h4><code>subtle.importKey(format, keyData, algorithm, extractable, keyUsages)</code><span><a class="mark" href="#all_webcrypto_subtleimportkeyformat-keydata-algorithm-extractable-keyusages" id="all_webcrypto_subtleimportkeyformat-keydata-algorithm-extractable-keyusages">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_subtle_importkey_format_keydata_algorithm_extractable_keyusages"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.4.0, v16.17.0</td>
<td><p>Added <code>'Ed25519'</code>, <code>'Ed448'</code>, <code>'X25519'</code>, and <code>'X448'</code> algorithms.</p></td></tr>
<tr><td>v15.9.0</td>
<td><p>Removed <code>'NODE-DSA'</code> JWK import.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p><span>Added in: v15.0.0</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> Must be one of <code>'raw'</code>, <code>'pkcs8'</code>, <code>'spki'</code>, or <code>'jwk'</code>.</li>
<li><code>keyData</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/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="#all_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></li>
</ul>
<!--lint disable maximum-line-length remark-lint-->
<ul>
<li><code>algorithm</code>: <a href="#all_webcrypto_class-algorithmidentifier" class="type">&#x3C;AlgorithmIdentifier></a> | <a href="#all_webcrypto_class-rsahashedimportparams" class="type">&#x3C;RsaHashedImportParams></a> | <a href="#all_webcrypto_class-eckeyimportparams" class="type">&#x3C;EcKeyImportParams></a> | <a href="#all_webcrypto_class-hmacimportparams" class="type">&#x3C;HmacImportParams></a></li>
</ul>
<!--lint enable maximum-line-length remark-lint-->
<ul>
<li><code>extractable</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
<li><code>keyUsages</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> See <a href="#all_webcrypto_cryptokeyusages">Key usages</a>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> Fulfills with a <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></a></li>
</ul>
<p>The <code>subtle.importKey()</code> method attempts to interpret the provided <code>keyData</code>
as the given <code>format</code> to create a <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></a> instance using the provided
<code>algorithm</code>, <code>extractable</code>, and <code>keyUsages</code> arguments. If the import is
successful, the returned promise will be resolved with the created <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></a>.</p>
<p>If importing a <code>'PBKDF2'</code> key, <code>extractable</code> must be <code>false</code>.</p>
<p>The algorithms currently supported include:</p>




























































































































<table><thead><tr><th>Key Type</th><th><code>'spki'</code></th><th><code>'pkcs8'</code></th><th><code>'jwk'</code></th><th><code>'raw'</code></th></tr></thead><tbody><tr><td><code>'AES-CBC'</code></td><td></td><td></td><td>✔</td><td>✔</td></tr><tr><td><code>'AES-CTR'</code></td><td></td><td></td><td>✔</td><td>✔</td></tr><tr><td><code>'AES-GCM'</code></td><td></td><td></td><td>✔</td><td>✔</td></tr><tr><td><code>'AES-KW'</code></td><td></td><td></td><td>✔</td><td>✔</td></tr><tr><td><code>'ECDH'</code></td><td>✔</td><td>✔</td><td>✔</td><td>✔</td></tr><tr><td><code>'X25519'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-19" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></td><td>✔</td><td>✔</td><td>✔</td><td>✔</td></tr><tr><td><code>'X448'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-20" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></td><td>✔</td><td>✔</td><td>✔</td><td>✔</td></tr><tr><td><code>'ECDSA'</code></td><td>✔</td><td>✔</td><td>✔</td><td>✔</td></tr><tr><td><code>'Ed25519'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-21" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></td><td>✔</td><td>✔</td><td>✔</td><td>✔</td></tr><tr><td><code>'Ed448'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-22" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></td><td>✔</td><td>✔</td><td>✔</td><td>✔</td></tr><tr><td><code>'HDKF'</code></td><td></td><td></td><td></td><td>✔</td></tr><tr><td><code>'HMAC'</code></td><td></td><td></td><td>✔</td><td>✔</td></tr><tr><td><code>'PBKDF2'</code></td><td></td><td></td><td></td><td>✔</td></tr><tr><td><code>'RSA-OAEP'</code></td><td>✔</td><td>✔</td><td>✔</td><td></td></tr><tr><td><code>'RSA-PSS'</code></td><td>✔</td><td>✔</td><td>✔</td><td></td></tr><tr><td><code>'RSASSA-PKCS1-v1_5'</code></td><td>✔</td><td>✔</td><td>✔</td><td></td></tr></tbody></table>
<h4><code>subtle.sign(algorithm, key, data)</code><span><a class="mark" href="#all_webcrypto_subtlesignalgorithm-key-data" id="all_webcrypto_subtlesignalgorithm-key-data">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_subtle_sign_algorithm_key_data"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.4.0, v16.17.0</td>
<td><p>Added <code>'Ed25519'</code>, and <code>'Ed448'</code> algorithms.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p><span>Added in: v15.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<!--lint disable maximum-line-length remark-lint-->
<ul>
<li><code>algorithm</code>: <a href="#all_webcrypto_class-algorithmidentifier" class="type">&#x3C;AlgorithmIdentifier></a> | <a href="#all_webcrypto_class-rsapssparams" class="type">&#x3C;RsaPssParams></a> | <a href="#all_webcrypto_class-ecdsaparams" class="type">&#x3C;EcdsaParams></a> | <a href="#all_webcrypto_class-ed448params" class="type">&#x3C;Ed448Params></a></li>
<li><code>key</code>: <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></a></li>
<li><code>data</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/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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> Fulfills with an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a></li>
</ul>
<!--lint enable maximum-line-length remark-lint-->
<p>Using the method and parameters given by <code>algorithm</code> and the keying material
provided by <code>key</code>, <code>subtle.sign()</code> attempts to generate a cryptographic
signature of <code>data</code>. If successful, the returned promise is resolved with
an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> containing the generated signature.</p>
<p>The algorithms currently supported include:</p>
<ul>
<li><code>'RSASSA-PKCS1-v1_5'</code></li>
<li><code>'RSA-PSS'</code></li>
<li><code>'ECDSA'</code></li>
<li><code>'Ed25519'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-23" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></li>
<li><code>'Ed448'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-24" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></li>
<li><code>'HMAC'</code></li>
</ul>
<h4><code>subtle.unwrapKey(format, wrappedKey, unwrappingKey, unwrapAlgo, unwrappedKeyAlgo, extractable, keyUsages)</code><span><a class="mark" href="#all_webcrypto_subtleunwrapkeyformat-wrappedkey-unwrappingkey-unwrapalgo-unwrappedkeyalgo-extractable-keyusages" id="all_webcrypto_subtleunwrapkeyformat-wrappedkey-unwrappingkey-unwrapalgo-unwrappedkeyalgo-extractable-keyusages">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_subtle_unwrapkey_format_wrappedkey_unwrappingkey_unwrapalgo_unwrappedkeyalgo_extractable_keyusages"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</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> Must be one of <code>'raw'</code>, <code>'pkcs8'</code>, <code>'spki'</code>, or <code>'jwk'</code>.</li>
<li><code>wrappedKey</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/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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a></li>
<li><code>unwrappingKey</code>: <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></a></li>
</ul>
<!--lint disable maximum-line-length remark-lint-->
<ul>
<li><code>unwrapAlgo</code>: <a href="#all_webcrypto_class-algorithmidentifier" class="type">&#x3C;AlgorithmIdentifier></a> | <a href="#all_webcrypto_class-rsaoaepparams" class="type">&#x3C;RsaOaepParams></a> | <a href="#all_webcrypto_class-aesctrparams" class="type">&#x3C;AesCtrParams></a> | <a href="#all_webcrypto_class-aescbcparams" class="type">&#x3C;AesCbcParams></a> | <a href="#all_webcrypto_class-aesgcmparams" class="type">&#x3C;AesGcmParams></a></li>
<li><code>unwrappedKeyAlgo</code>: <a href="#all_webcrypto_class-algorithmidentifier" class="type">&#x3C;AlgorithmIdentifier></a> | <a href="#all_webcrypto_class-rsahashedimportparams" class="type">&#x3C;RsaHashedImportParams></a> | <a href="#all_webcrypto_class-eckeyimportparams" class="type">&#x3C;EcKeyImportParams></a> | <a href="#all_webcrypto_class-hmacimportparams" class="type">&#x3C;HmacImportParams></a></li>
</ul>
<!--lint enable maximum-line-length remark-lint-->
<ul>
<li><code>extractable</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
<li><code>keyUsages</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string[]></a> See <a href="#all_webcrypto_cryptokeyusages">Key usages</a>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> Fulfills with a <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></a></li>
</ul>
<p>In cryptography, "wrapping a key" refers to exporting and then encrypting the
keying material. The <code>subtle.unwrapKey()</code> method attempts to decrypt a wrapped
key and create a <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></a> instance. It is equivalent to calling
<code>subtle.decrypt()</code> first on the encrypted key data (using the <code>wrappedKey</code>,
<code>unwrapAlgo</code>, and <code>unwrappingKey</code> arguments as input) then passing the results
in to the <code>subtle.importKey()</code> method using the <code>unwrappedKeyAlgo</code>,
<code>extractable</code>, and <code>keyUsages</code> arguments as inputs. If successful, the returned
promise is resolved with a <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></a> object.</p>
<p>The wrapping algorithms currently supported include:</p>
<ul>
<li><code>'RSA-OAEP'</code></li>
<li><code>'AES-CTR'</code></li>
<li><code>'AES-CBC'</code></li>
<li><code>'AES-GCM'</code></li>
<li><code>'AES-KW'</code></li>
</ul>
<p>The unwrapped key algorithms supported include:</p>
<ul>
<li><code>'RSASSA-PKCS1-v1_5'</code></li>
<li><code>'RSA-PSS'</code></li>
<li><code>'RSA-OAEP'</code></li>
<li><code>'ECDSA'</code></li>
<li><code>'Ed25519'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-25" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></li>
<li><code>'Ed448'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-26" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></li>
<li><code>'ECDH'</code></li>
<li><code>'X25519'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-27" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></li>
<li><code>'X448'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-28" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></li>
<li><code>'HMAC'</code></li>
<li><code>'AES-CTR'</code></li>
<li><code>'AES-CBC'</code></li>
<li><code>'AES-GCM'</code></li>
<li><code>'AES-KW'</code></li>
</ul>
<h4><code>subtle.verify(algorithm, key, signature, data)</code><span><a class="mark" href="#all_webcrypto_subtleverifyalgorithm-key-signature-data" id="all_webcrypto_subtleverifyalgorithm-key-signature-data">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_subtle_verify_algorithm_key_signature_data"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.4.0, v16.17.0</td>
<td><p>Added <code>'Ed25519'</code>, and <code>'Ed448'</code> algorithms.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p><span>Added in: v15.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<!--lint disable maximum-line-length remark-lint-->
<ul>
<li><code>algorithm</code>: <a href="#all_webcrypto_class-algorithmidentifier" class="type">&#x3C;AlgorithmIdentifier></a> | <a href="#all_webcrypto_class-rsapssparams" class="type">&#x3C;RsaPssParams></a> | <a href="#all_webcrypto_class-ecdsaparams" class="type">&#x3C;EcdsaParams></a> | <a href="#all_webcrypto_class-ed448params" class="type">&#x3C;Ed448Params></a></li>
<li><code>key</code>: <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></a></li>
<li><code>signature</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/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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a></li>
<li><code>data</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/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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> Fulfills with a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a></li>
</ul>
<!--lint enable maximum-line-length remark-lint-->
<p>Using the method and parameters given in <code>algorithm</code> and the keying material
provided by <code>key</code>, <code>subtle.verify()</code> attempts to verify that <code>signature</code> is
a valid cryptographic signature of <code>data</code>. The returned promise is resolved
with either <code>true</code> or <code>false</code>.</p>
<p>The algorithms currently supported include:</p>
<ul>
<li><code>'RSASSA-PKCS1-v1_5'</code></li>
<li><code>'RSA-PSS'</code></li>
<li><code>'ECDSA'</code></li>
<li><code>'Ed25519'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-29" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></li>
<li><code>'Ed448'</code> <span class="experimental-inline"></span><sup><a href="#all_webcrypto_user-content-fn-1" id="all_webcrypto_user-content-fnref-1-30" data-footnote-ref="" aria-describedby="footnote-label">1</a></sup></li>
<li><code>'HMAC'</code></li>
</ul>
<h4><code>subtle.wrapKey(format, key, wrappingKey, wrapAlgo)</code><span><a class="mark" href="#all_webcrypto_subtlewrapkeyformat-key-wrappingkey-wrapalgo" id="all_webcrypto_subtlewrapkeyformat-key-wrappingkey-wrapalgo">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_subtle_wrapkey_format_key_wrappingkey_wrapalgo"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<!--lint disable maximum-line-length remark-lint-->
<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> Must be one of <code>'raw'</code>, <code>'pkcs8'</code>, <code>'spki'</code>, or <code>'jwk'</code>.</li>
<li><code>key</code>: <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></a></li>
<li><code>wrappingKey</code>: <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></a></li>
<li><code>wrapAlgo</code>: <a href="#all_webcrypto_class-algorithmidentifier" class="type">&#x3C;AlgorithmIdentifier></a> | <a href="#all_webcrypto_class-rsaoaepparams" class="type">&#x3C;RsaOaepParams></a> | <a href="#all_webcrypto_class-aesctrparams" class="type">&#x3C;AesCtrParams></a> | <a href="#all_webcrypto_class-aescbcparams" class="type">&#x3C;AesCbcParams></a> | <a href="#all_webcrypto_class-aesgcmparams" class="type">&#x3C;AesGcmParams></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> Fulfills with an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a></li>
</ul>
<!--lint enable maximum-line-length remark-lint-->
<p>In cryptography, "wrapping a key" refers to exporting and then encrypting the
keying material. The <code>subtle.wrapKey()</code> method exports the keying material into
the format identified by <code>format</code>, then encrypts it using the method and
parameters specified by <code>wrapAlgo</code> and the keying material provided by
<code>wrappingKey</code>. It is the equivalent to calling <code>subtle.exportKey()</code> using
<code>format</code> and <code>key</code> as the arguments, then passing the result to the
<code>subtle.encrypt()</code> method using <code>wrappingKey</code> and <code>wrapAlgo</code> as inputs. If
successful, the returned promise will be resolved with an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a>
containing the encrypted key data.</p>
<p>The wrapping algorithms currently supported include:</p>
<ul>
<li><code>'RSA-OAEP'</code></li>
<li><code>'AES-CTR'</code></li>
<li><code>'AES-CBC'</code></li>
<li><code>'AES-GCM'</code></li>
<li><code>'AES-KW'</code></li>
</ul>
</section><section><h3>Algorithm parameters<span><a class="mark" href="#all_webcrypto_algorithm-parameters" id="all_webcrypto_algorithm-parameters">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_algorithm_parameters"></a></h3>
<p>The algorithm parameter objects define the methods and parameters used by
the various <a href="#all_webcrypto_class-subtlecrypto" class="type">&#x3C;SubtleCrypto></a> methods. While described here as "classes", they
are simple JavaScript dictionary objects.</p>
<h4>Class: <code>AlgorithmIdentifier</code><span><a class="mark" href="#all_webcrypto_class-algorithmidentifier" id="all_webcrypto_class-algorithmidentifier">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_algorithmidentifier"></a></h4>
<div class="api_metadata">
<span>Added in: v18.4.0, v16.17.0</span>
</div>
<h5><code>algorithmIdentifier.name</code><span><a class="mark" href="#all_webcrypto_algorithmidentifiername" id="all_webcrypto_algorithmidentifiername">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_algorithmidentifier_name"></a></h5>
<div class="api_metadata">
<span>Added in: v18.4.0, v16.17.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a></li>
</ul>
<h4>Class: <code>AesCbcParams</code><span><a class="mark" href="#all_webcrypto_class-aescbcparams" id="all_webcrypto_class-aescbcparams">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_aescbcparams"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<h5><code>aesCbcParams.iv</code><span><a class="mark" href="#all_webcrypto_aescbcparamsiv" id="all_webcrypto_aescbcparamsiv">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_aescbcparams_iv"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <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/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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a></li>
</ul>
<p>Provides the initialization vector. It must be exactly 16-bytes in length
and should be unpredictable and cryptographically random.</p>
<h5><code>aesCbcParams.name</code><span><a class="mark" href="#all_webcrypto_aescbcparamsname" id="all_webcrypto_aescbcparamsname">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_aescbcparams_name"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Must be <code>'AES-CBC'</code>.</li>
</ul>
<h4>Class: <code>AesCtrParams</code><span><a class="mark" href="#all_webcrypto_class-aesctrparams" id="all_webcrypto_class-aesctrparams">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_aesctrparams"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<h5><code>aesCtrParams.counter</code><span><a class="mark" href="#all_webcrypto_aesctrparamscounter" id="all_webcrypto_aesctrparamscounter">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_aesctrparams_counter"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <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/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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a></li>
</ul>
<p>The initial value of the counter block. This must be exactly 16 bytes long.</p>
<p>The <code>AES-CTR</code> method uses the rightmost <code>length</code> bits of the block as the
counter and the remaining bits as the nonce.</p>
<h5><code>aesCtrParams.length</code><span><a class="mark" href="#all_webcrypto_aesctrparamslength" id="all_webcrypto_aesctrparamslength">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_aesctrparams_length"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The number of bits in the <code>aesCtrParams.counter</code> that are
to be used as the counter.</li>
</ul>
<h5><code>aesCtrParams.name</code><span><a class="mark" href="#all_webcrypto_aesctrparamsname" id="all_webcrypto_aesctrparamsname">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_aesctrparams_name"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Must be <code>'AES-CTR'</code>.</li>
</ul>
<h4>Class: <code>AesGcmParams</code><span><a class="mark" href="#all_webcrypto_class-aesgcmparams" id="all_webcrypto_class-aesgcmparams">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_aesgcmparams"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<h5><code>aesGcmParams.additionalData</code><span><a class="mark" href="#all_webcrypto_aesgcmparamsadditionaldata" id="all_webcrypto_aesgcmparamsadditionaldata">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_aesgcmparams_additionaldata"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <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/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="#all_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></li>
</ul>
<p>With the AES-GCM method, the <code>additionalData</code> is extra input that is not
encrypted but is included in the authentication of the data. The use of
<code>additionalData</code> is optional.</p>
<h5><code>aesGcmParams.iv</code><span><a class="mark" href="#all_webcrypto_aesgcmparamsiv" id="all_webcrypto_aesgcmparamsiv">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_aesgcmparams_iv"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <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/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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a></li>
</ul>
<p>The initialization vector must be unique for every encryption operation using a
given key.</p>
<p>Ideally, this is a deterministic 12-byte value that is computed in such a way
that it is guaranteed to be unique across all invocations that use the same key.
Alternatively, the initialization vector may consist of at least 12
cryptographically random bytes. For more information on constructing
initialization vectors for AES-GCM, refer to Section 8 of <a href="https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf">NIST SP 800-38D</a>.</p>
<h5><code>aesGcmParams.name</code><span><a class="mark" href="#all_webcrypto_aesgcmparamsname" id="all_webcrypto_aesgcmparamsname">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_aesgcmparams_name"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Must be <code>'AES-GCM'</code>.</li>
</ul>
<h5><code>aesGcmParams.tagLength</code><span><a class="mark" href="#all_webcrypto_aesgcmparamstaglength" id="all_webcrypto_aesgcmparamstaglength">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_aesgcmparams_taglength"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The size in bits of the generated authentication tag.
This values must be one of <code>32</code>, <code>64</code>, <code>96</code>, <code>104</code>, <code>112</code>, <code>120</code>, or
<code>128</code>. <strong>Default:</strong> <code>128</code>.</li>
</ul>
<h4>Class: <code>AesKeyGenParams</code><span><a class="mark" href="#all_webcrypto_class-aeskeygenparams" id="all_webcrypto_class-aeskeygenparams">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_aeskeygenparams"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<h5><code>aesKeyGenParams.length</code><span><a class="mark" href="#all_webcrypto_aeskeygenparamslength" id="all_webcrypto_aeskeygenparamslength">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_aeskeygenparams_length"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>The length of the AES key to be generated. This must be either <code>128</code>, <code>192</code>,
or <code>256</code>.</p>
<h5><code>aesKeyGenParams.name</code><span><a class="mark" href="#all_webcrypto_aeskeygenparamsname" id="all_webcrypto_aeskeygenparamsname">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_aeskeygenparams_name"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <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>'AES-CBC'</code>, <code>'AES-CTR'</code>, <code>'AES-GCM'</code>, or
<code>'AES-KW'</code></li>
</ul>
<h4>Class: <code>EcdhKeyDeriveParams</code><span><a class="mark" href="#all_webcrypto_class-ecdhkeyderiveparams" id="all_webcrypto_class-ecdhkeyderiveparams">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_ecdhkeyderiveparams"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<h5><code>ecdhKeyDeriveParams.name</code><span><a class="mark" href="#all_webcrypto_ecdhkeyderiveparamsname" id="all_webcrypto_ecdhkeyderiveparamsname">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_ecdhkeyderiveparams_name"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Must be <code>'ECDH'</code>, <code>'X25519'</code>, or <code>'X448'</code>.</li>
</ul>
<h5><code>ecdhKeyDeriveParams.public</code><span><a class="mark" href="#all_webcrypto_ecdhkeyderiveparamspublic" id="all_webcrypto_ecdhkeyderiveparamspublic">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_ecdhkeyderiveparams_public"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></a></li>
</ul>
<p>ECDH key derivation operates by taking as input one parties private key and
another parties public key -- using both to generate a common shared secret.
The <code>ecdhKeyDeriveParams.public</code> property is set to the other parties public
key.</p>
<h4>Class: <code>EcdsaParams</code><span><a class="mark" href="#all_webcrypto_class-ecdsaparams" id="all_webcrypto_class-ecdsaparams">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_ecdsaparams"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<h5><code>ecdsaParams.hash</code><span><a class="mark" href="#all_webcrypto_ecdsaparamshash" id="all_webcrypto_ecdsaparamshash">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_ecdsaparams_hash"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <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>
<p>If represented as a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a>, the value must be one of:</p>
<ul>
<li><code>'SHA-1'</code></li>
<li><code>'SHA-256'</code></li>
<li><code>'SHA-384'</code></li>
<li><code>'SHA-512'</code></li>
</ul>
<p>If represented as an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>, the object must have a <code>name</code> property
whose value is one of the above listed values.</p>
<h5><code>ecdsaParams.name</code><span><a class="mark" href="#all_webcrypto_ecdsaparamsname" id="all_webcrypto_ecdsaparamsname">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_ecdsaparams_name"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Must be <code>'ECDSA'</code>.</li>
</ul>
<h4>Class: <code>EcKeyGenParams</code><span><a class="mark" href="#all_webcrypto_class-eckeygenparams" id="all_webcrypto_class-eckeygenparams">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_eckeygenparams"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<h5><code>ecKeyGenParams.name</code><span><a class="mark" href="#all_webcrypto_eckeygenparamsname" id="all_webcrypto_eckeygenparamsname">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_eckeygenparams_name"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <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>'ECDSA'</code> or <code>'ECDH'</code>.</li>
</ul>
<h5><code>ecKeyGenParams.namedCurve</code><span><a class="mark" href="#all_webcrypto_eckeygenparamsnamedcurve" id="all_webcrypto_eckeygenparamsnamedcurve">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_eckeygenparams_namedcurve"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <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>'P-256'</code>, <code>'P-384'</code>, <code>'P-521'</code>.</li>
</ul>
<h4>Class: <code>EcKeyImportParams</code><span><a class="mark" href="#all_webcrypto_class-eckeyimportparams" id="all_webcrypto_class-eckeyimportparams">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_eckeyimportparams"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<h5><code>ecKeyImportParams.name</code><span><a class="mark" href="#all_webcrypto_eckeyimportparamsname" id="all_webcrypto_eckeyimportparamsname">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_eckeyimportparams_name"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <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>'ECDSA'</code> or <code>'ECDH'</code>.</li>
</ul>
<h5><code>ecKeyImportParams.namedCurve</code><span><a class="mark" href="#all_webcrypto_eckeyimportparamsnamedcurve" id="all_webcrypto_eckeyimportparamsnamedcurve">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_eckeyimportparams_namedcurve"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <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>'P-256'</code>, <code>'P-384'</code>, <code>'P-521'</code>.</li>
</ul>
<h4>Class: <code>Ed448Params</code><span><a class="mark" href="#all_webcrypto_class-ed448params" id="all_webcrypto_class-ed448params">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_ed448params"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<h5><code>ed448Params.name</code><span><a class="mark" href="#all_webcrypto_ed448paramsname" id="all_webcrypto_ed448paramsname">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_ed448params_name"></a></h5>
<div class="api_metadata">
<span>Added in: v18.4.0, v16.17.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Must be <code>'Ed448'</code>.</li>
</ul>
<h5><code>ed448Params.context</code><span><a class="mark" href="#all_webcrypto_ed448paramscontext" id="all_webcrypto_ed448paramscontext">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_ed448params_context"></a></h5>
<div class="api_metadata">
<span>Added in: v18.4.0, v16.17.0</span>
</div>
<ul>
<li>Type: <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/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="#all_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></li>
</ul>
<p>The <code>context</code> member represents the optional context data to associate with
the message.
The Node.js Web Crypto API implementation only supports zero-length context
which is equivalent to not providing context at all.</p>
<h4>Class: <code>HkdfParams</code><span><a class="mark" href="#all_webcrypto_class-hkdfparams" id="all_webcrypto_class-hkdfparams">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_hkdfparams"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<h5><code>hkdfParams.hash</code><span><a class="mark" href="#all_webcrypto_hkdfparamshash" id="all_webcrypto_hkdfparamshash">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_hkdfparams_hash"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <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>
<p>If represented as a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a>, the value must be one of:</p>
<ul>
<li><code>'SHA-1'</code></li>
<li><code>'SHA-256'</code></li>
<li><code>'SHA-384'</code></li>
<li><code>'SHA-512'</code></li>
</ul>
<p>If represented as an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>, the object must have a <code>name</code> property
whose value is one of the above listed values.</p>
<h5><code>hkdfParams.info</code><span><a class="mark" href="#all_webcrypto_hkdfparamsinfo" id="all_webcrypto_hkdfparamsinfo">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_hkdfparams_info"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <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/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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a></li>
</ul>
<p>Provides application-specific contextual input to the HKDF algorithm.
This can be zero-length but must be provided.</p>
<h5><code>hkdfParams.name</code><span><a class="mark" href="#all_webcrypto_hkdfparamsname" id="all_webcrypto_hkdfparamsname">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_hkdfparams_name"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Must be <code>'HKDF'</code>.</li>
</ul>
<h5><code>hkdfParams.salt</code><span><a class="mark" href="#all_webcrypto_hkdfparamssalt" id="all_webcrypto_hkdfparamssalt">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_hkdfparams_salt"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <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/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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a></li>
</ul>
<p>The salt value significantly improves the strength of the HKDF algorithm.
It should be random or pseudorandom and should be the same length as the
output of the digest function (for instance, if using <code>'SHA-256'</code> as the
digest, the salt should be 256-bits of random data).</p>
<h4>Class: <code>HmacImportParams</code><span><a class="mark" href="#all_webcrypto_class-hmacimportparams" id="all_webcrypto_class-hmacimportparams">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_hmacimportparams"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<h5><code>hmacImportParams.hash</code><span><a class="mark" href="#all_webcrypto_hmacimportparamshash" id="all_webcrypto_hmacimportparamshash">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_hmacimportparams_hash"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <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>
<p>If represented as a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a>, the value must be one of:</p>
<ul>
<li><code>'SHA-1'</code></li>
<li><code>'SHA-256'</code></li>
<li><code>'SHA-384'</code></li>
<li><code>'SHA-512'</code></li>
</ul>
<p>If represented as an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>, the object must have a <code>name</code> property
whose value is one of the above listed values.</p>
<h5><code>hmacImportParams.length</code><span><a class="mark" href="#all_webcrypto_hmacimportparamslength" id="all_webcrypto_hmacimportparamslength">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_hmacimportparams_length"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>The optional number of bits in the HMAC key. This is optional and should
be omitted for most cases.</p>
<h5><code>hmacImportParams.name</code><span><a class="mark" href="#all_webcrypto_hmacimportparamsname" id="all_webcrypto_hmacimportparamsname">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_hmacimportparams_name"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Must be <code>'HMAC'</code>.</li>
</ul>
<h4>Class: <code>HmacKeyGenParams</code><span><a class="mark" href="#all_webcrypto_class-hmackeygenparams" id="all_webcrypto_class-hmackeygenparams">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_hmackeygenparams"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<h5><code>hmacKeyGenParams.hash</code><span><a class="mark" href="#all_webcrypto_hmackeygenparamshash" id="all_webcrypto_hmackeygenparamshash">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_hmackeygenparams_hash"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <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>
<p>If represented as a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a>, the value must be one of:</p>
<ul>
<li><code>'SHA-1'</code></li>
<li><code>'SHA-256'</code></li>
<li><code>'SHA-384'</code></li>
<li><code>'SHA-512'</code></li>
</ul>
<p>If represented as an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>, the object must have a <code>name</code> property
whose value is one of the above listed values.</p>
<h5><code>hmacKeyGenParams.length</code><span><a class="mark" href="#all_webcrypto_hmackeygenparamslength" id="all_webcrypto_hmackeygenparamslength">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_hmackeygenparams_length"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <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 bits to generate for the HMAC key. If omitted,
the length will be determined by the hash algorithm used.
This is optional and should be omitted for most cases.</p>
<h5><code>hmacKeyGenParams.name</code><span><a class="mark" href="#all_webcrypto_hmackeygenparamsname" id="all_webcrypto_hmackeygenparamsname">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_hmackeygenparams_name"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Must be <code>'HMAC'</code>.</li>
</ul>
<h4>Class: <code>Pbkdf2Params</code><span><a class="mark" href="#all_webcrypto_class-pbkdf2params" id="all_webcrypto_class-pbkdf2params">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_pbkdf2params"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<h5><code>pbkdb2Params.hash</code><span><a class="mark" href="#all_webcrypto_pbkdb2paramshash" id="all_webcrypto_pbkdb2paramshash">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_pbkdb2params_hash"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <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>
<p>If represented as a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a>, the value must be one of:</p>
<ul>
<li><code>'SHA-1'</code></li>
<li><code>'SHA-256'</code></li>
<li><code>'SHA-384'</code></li>
<li><code>'SHA-512'</code></li>
</ul>
<p>If represented as an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>, the object must have a <code>name</code> property
whose value is one of the above listed values.</p>
<h5><code>pbkdf2Params.iterations</code><span><a class="mark" href="#all_webcrypto_pbkdf2paramsiterations" id="all_webcrypto_pbkdf2paramsiterations">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_pbkdf2params_iterations"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <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 iterations the PBKDF2 algorithm should make when deriving bits.</p>
<h5><code>pbkdf2Params.name</code><span><a class="mark" href="#all_webcrypto_pbkdf2paramsname" id="all_webcrypto_pbkdf2paramsname">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_pbkdf2params_name"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Must be <code>'PBKDF2'</code>.</li>
</ul>
<h5><code>pbkdf2Params.salt</code><span><a class="mark" href="#all_webcrypto_pbkdf2paramssalt" id="all_webcrypto_pbkdf2paramssalt">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_pbkdf2params_salt"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <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/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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a></li>
</ul>
<p>Should be at least 16 random or pseudorandom bytes.</p>
<h4>Class: <code>RsaHashedImportParams</code><span><a class="mark" href="#all_webcrypto_class-rsahashedimportparams" id="all_webcrypto_class-rsahashedimportparams">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_rsahashedimportparams"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<h5><code>rsaHashedImportParams.hash</code><span><a class="mark" href="#all_webcrypto_rsahashedimportparamshash" id="all_webcrypto_rsahashedimportparamshash">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_rsahashedimportparams_hash"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <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>
<p>If represented as a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a>, the value must be one of:</p>
<ul>
<li><code>'SHA-1'</code></li>
<li><code>'SHA-256'</code></li>
<li><code>'SHA-384'</code></li>
<li><code>'SHA-512'</code></li>
</ul>
<p>If represented as an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>, the object must have a <code>name</code> property
whose value is one of the above listed values.</p>
<h5><code>rsaHashedImportParams.name</code><span><a class="mark" href="#all_webcrypto_rsahashedimportparamsname" id="all_webcrypto_rsahashedimportparamsname">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_rsahashedimportparams_name"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <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>'RSASSA-PKCS1-v1_5'</code>, <code>'RSA-PSS'</code>, or
<code>'RSA-OAEP'</code>.</li>
</ul>
<h4>Class: <code>RsaHashedKeyGenParams</code><span><a class="mark" href="#all_webcrypto_class-rsahashedkeygenparams" id="all_webcrypto_class-rsahashedkeygenparams">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_rsahashedkeygenparams"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<h5><code>rsaHashedKeyGenParams.hash</code><span><a class="mark" href="#all_webcrypto_rsahashedkeygenparamshash" id="all_webcrypto_rsahashedkeygenparamshash">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_rsahashedkeygenparams_hash"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <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>
<p>If represented as a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a>, the value must be one of:</p>
<ul>
<li><code>'SHA-1'</code></li>
<li><code>'SHA-256'</code></li>
<li><code>'SHA-384'</code></li>
<li><code>'SHA-512'</code></li>
</ul>
<p>If represented as an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>, the object must have a <code>name</code> property
whose value is one of the above listed values.</p>
<h5><code>rsaHashedKeyGenParams.modulusLength</code><span><a class="mark" href="#all_webcrypto_rsahashedkeygenparamsmoduluslength" id="all_webcrypto_rsahashedkeygenparamsmoduluslength">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_rsahashedkeygenparams_moduluslength"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>The length in bits of the RSA modulus. As a best practice, this should be
at least <code>2048</code>.</p>
<h5><code>rsaHashedKeyGenParams.name</code><span><a class="mark" href="#all_webcrypto_rsahashedkeygenparamsname" id="all_webcrypto_rsahashedkeygenparamsname">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_rsahashedkeygenparams_name"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <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>'RSASSA-PKCS1-v1_5'</code>, <code>'RSA-PSS'</code>, or
<code>'RSA-OAEP'</code>.</li>
</ul>
<h5><code>rsaHashedKeyGenParams.publicExponent</code><span><a class="mark" href="#all_webcrypto_rsahashedkeygenparamspublicexponent" id="all_webcrypto_rsahashedkeygenparamspublicexponent">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_rsahashedkeygenparams_publicexponent"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type">&#x3C;Uint8Array></a></li>
</ul>
<p>The RSA public exponent. This must be a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type">&#x3C;Uint8Array></a> containing a big-endian,
unsigned integer that must fit within 32-bits. The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array" class="type">&#x3C;Uint8Array></a> may contain an
arbitrary number of leading zero-bits. The value must be a prime number. Unless
there is reason to use a different value, use <code>new Uint8Array([1, 0, 1])</code>
(65537) as the public exponent.</p>
<h4>Class: <code>RsaOaepParams</code><span><a class="mark" href="#all_webcrypto_class-rsaoaepparams" id="all_webcrypto_class-rsaoaepparams">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_rsaoaepparams"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<h5><code>rsaOaepParams.label</code><span><a class="mark" href="#all_webcrypto_rsaoaepparamslabel" id="all_webcrypto_rsaoaepparamslabel">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_rsaoaepparams_label"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <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/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="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a></li>
</ul>
<p>An additional collection of bytes that will not be encrypted, but will be bound
to the generated ciphertext.</p>
<p>The <code>rsaOaepParams.label</code> parameter is optional.</p>
<h5><code>rsaOaepParams.name</code><span><a class="mark" href="#all_webcrypto_rsaoaepparamsname" id="all_webcrypto_rsaoaepparamsname">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_rsaoaepparams_name"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> must be <code>'RSA-OAEP'</code>.</li>
</ul>
<h4>Class: <code>RsaPssParams</code><span><a class="mark" href="#all_webcrypto_class-rsapssparams" id="all_webcrypto_class-rsapssparams">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_class_rsapssparams"></a></h4>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<h5><code>rsaPssParams.name</code><span><a class="mark" href="#all_webcrypto_rsapssparamsname" id="all_webcrypto_rsapssparamsname">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_rsapssparams_name"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> Must be <code>'RSA-PSS'</code>.</li>
</ul>
<h5><code>rsaPssParams.saltLength</code><span><a class="mark" href="#all_webcrypto_rsapssparamssaltlength" id="all_webcrypto_rsapssparamssaltlength">#</a></span><a aria-hidden="true" class="legacy" id="webcrypto_rsapssparams_saltlength"></a></h5>
<div class="api_metadata">
<span>Added in: v15.0.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>The length (in bytes) of the random salt to use.</p>
<section data-footnotes="" class="footnotes"><h3 class="sr-only" id="footnote-label">Footnotes</h3>
<ol>
<li id="all_webcrypto_user-content-fn-1">
<p>An experimental implementation of
<a href="https://wicg.github.io/webcrypto-secure-curves/">Secure Curves in the Web Cryptography API</a> as of 30 August 2023 <a href="#all_webcrypto_user-content-fnref-1" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩</a> <a href="#all_webcrypto_user-content-fnref-1-2" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>2</sup></a> <a href="#all_webcrypto_user-content-fnref-1-3" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>3</sup></a> <a href="#all_webcrypto_user-content-fnref-1-4" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>4</sup></a> <a href="#all_webcrypto_user-content-fnref-1-5" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>5</sup></a> <a href="#all_webcrypto_user-content-fnref-1-6" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>6</sup></a> <a href="#all_webcrypto_user-content-fnref-1-7" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>7</sup></a> <a href="#all_webcrypto_user-content-fnref-1-8" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>8</sup></a> <a href="#all_webcrypto_user-content-fnref-1-9" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>9</sup></a> <a href="#all_webcrypto_user-content-fnref-1-10" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>10</sup></a> <a href="#all_webcrypto_user-content-fnref-1-11" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>11</sup></a> <a href="#all_webcrypto_user-content-fnref-1-12" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>12</sup></a> <a href="#all_webcrypto_user-content-fnref-1-13" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>13</sup></a> <a href="#all_webcrypto_user-content-fnref-1-14" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>14</sup></a> <a href="#all_webcrypto_user-content-fnref-1-15" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>15</sup></a> <a href="#all_webcrypto_user-content-fnref-1-16" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>16</sup></a> <a href="#all_webcrypto_user-content-fnref-1-17" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>17</sup></a> <a href="#all_webcrypto_user-content-fnref-1-18" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>18</sup></a> <a href="#all_webcrypto_user-content-fnref-1-19" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>19</sup></a> <a href="#all_webcrypto_user-content-fnref-1-20" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>20</sup></a> <a href="#all_webcrypto_user-content-fnref-1-21" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>21</sup></a> <a href="#all_webcrypto_user-content-fnref-1-22" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>22</sup></a> <a href="#all_webcrypto_user-content-fnref-1-23" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>23</sup></a> <a href="#all_webcrypto_user-content-fnref-1-24" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>24</sup></a> <a href="#all_webcrypto_user-content-fnref-1-25" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>25</sup></a> <a href="#all_webcrypto_user-content-fnref-1-26" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>26</sup></a> <a href="#all_webcrypto_user-content-fnref-1-27" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>27</sup></a> <a href="#all_webcrypto_user-content-fnref-1-28" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>28</sup></a> <a href="#all_webcrypto_user-content-fnref-1-29" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>29</sup></a> <a href="#all_webcrypto_user-content-fnref-1-30" data-footnote-backref="" class="data-footnote-backref" aria-label="Back to content">↩<sup>30</sup></a></p>
</li>
</ol>
</section></section>
        </section>
<section><h2>Web Streams API<span><a class="mark" href="#all_webstreams_web-streams-api" id="all_webstreams_web-streams-api">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_web_streams_api"></a></h2>

<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>Use of this API no longer emit a runtime warning.</p></td></tr>
<tr><td>v16.5.0</td>
<td><p><span>Added in: v16.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental.</div><p></p>
<p>An implementation of the <a href="https://streams.spec.whatwg.org/">WHATWG Streams Standard</a>.</p>
<section><h3>Overview<span><a class="mark" href="#all_webstreams_overview" id="all_webstreams_overview">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_overview"></a></h3>
<p>The <a href="https://streams.spec.whatwg.org/">WHATWG Streams Standard</a> (or "web streams") defines an API for handling
streaming data. It is similar to the Node.js <a href="stream.html">Streams</a> API but emerged later
and has become the "standard" API for streaming data across many JavaScript
environments.</p>
<p>There are three primary types of objects:</p>
<ul>
<li><code>ReadableStream</code> - Represents a source of streaming data.</li>
<li><code>WritableStream</code> - Represents a destination for streaming data.</li>
<li><code>TransformStream</code> - Represents an algorithm for transforming streaming data.</li>
</ul>
<h4>Example <code>ReadableStream</code><span><a class="mark" href="#all_webstreams_example-readablestream" id="all_webstreams_example-readablestream">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_example_readablestream"></a></h4>
<p>This example creates a simple <code>ReadableStream</code> that pushes the current
<code>performance.now()</code> timestamp once every second forever. An async iterable
is used to read the data from the stream.</p>

<pre class="with-17-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> {
  <span class="hljs-title class_">ReadableStream</span>,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/web'</span>;

<span class="hljs-keyword">import</span> {
  <span class="hljs-built_in">setInterval</span> <span class="hljs-keyword">as</span> every,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:timers/promises'</span>;

<span class="hljs-keyword">import</span> {
  performance,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:perf_hooks'</span>;

<span class="hljs-keyword">const</span> <span class="hljs-variable constant_">SECOND</span> = <span class="hljs-number">1000</span>;

<span class="hljs-keyword">const</span> stream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ReadableStream</span>({
  <span class="hljs-keyword">async</span> <span class="hljs-title function_">start</span>(<span class="hljs-params">controller</span>) {
    <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> _ <span class="hljs-keyword">of</span> <span class="hljs-title function_">every</span>(<span class="hljs-variable constant_">SECOND</span>))
      controller.<span class="hljs-title function_">enqueue</span>(performance.<span class="hljs-title function_">now</span>());
  },
});

<span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> value <span class="hljs-keyword">of</span> stream)
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(value);</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
  <span class="hljs-title class_">ReadableStream</span>,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/web'</span>);

<span class="hljs-keyword">const</span> {
  <span class="hljs-attr">setInterval</span>: every,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:timers/promises'</span>);

<span class="hljs-keyword">const</span> {
  performance,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:perf_hooks'</span>);

<span class="hljs-keyword">const</span> <span class="hljs-variable constant_">SECOND</span> = <span class="hljs-number">1000</span>;

<span class="hljs-keyword">const</span> stream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ReadableStream</span>({
  <span class="hljs-keyword">async</span> <span class="hljs-title function_">start</span>(<span class="hljs-params">controller</span>) {
    <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> _ <span class="hljs-keyword">of</span> <span class="hljs-title function_">every</span>(<span class="hljs-variable constant_">SECOND</span>))
      controller.<span class="hljs-title function_">enqueue</span>(performance.<span class="hljs-title function_">now</span>());
  },
});

(<span class="hljs-keyword">async</span> () => {
  <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> value <span class="hljs-keyword">of</span> stream)
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(value);
})();</code><button class="copy-button">copy</button></pre>
</section><section><h3>API<span><a class="mark" href="#all_webstreams_api" id="all_webstreams_api">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_api"></a></h3>
<h4>Class: <code>ReadableStream</code><span><a class="mark" href="#all_webstreams_class-readablestream" id="all_webstreams_class-readablestream">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_class_readablestream"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>This class is now exposed on the global object.</p></td></tr>
<tr><td>v16.5.0</td>
<td><p><span>Added in: v16.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<h5><code>new ReadableStream([underlyingSource [, strategy]])</code><span><a class="mark" href="#all_webstreams_new-readablestreamunderlyingsource--strategy" id="all_webstreams_new-readablestreamunderlyingsource--strategy">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_new_readablestream_underlyingsource_strategy"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<!--lint disable maximum-line-length remark-lint-->
<ul>
<li><code>underlyingSource</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>start</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> A user-defined function that is invoked immediately when
the <code>ReadableStream</code> is created.
<ul>
<li><code>controller</code> <a href="#all_webstreams_class-readablestreamdefaultcontroller" class="type">&#x3C;ReadableStreamDefaultController></a> | <a href="#all_webstreams_class-readablebytestreamcontroller" class="type">&#x3C;ReadableByteStreamController></a></li>
<li>Returns: <code>undefined</code> or a promise fulfilled with <code>undefined</code>.</li>
</ul>
</li>
<li><code>pull</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> A user-defined function that is called repeatedly when the
<code>ReadableStream</code> internal queue is not full. The operation may be sync or
async. If async, the function will not be called again until the previously
returned promise is fulfilled.
<ul>
<li><code>controller</code> <a href="#all_webstreams_class-readablestreamdefaultcontroller" class="type">&#x3C;ReadableStreamDefaultController></a> | <a href="#all_webstreams_class-readablebytestreamcontroller" class="type">&#x3C;ReadableByteStreamController></a></li>
<li>Returns: A promise fulfilled with <code>undefined</code>.</li>
</ul>
</li>
<li><code>cancel</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> A user-defined function that is called when the
<code>ReadableStream</code> is canceled.
<ul>
<li><code>reason</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 promise fulfilled with <code>undefined</code>.</li>
</ul>
</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>'bytes'</code> or <code>undefined</code>.</li>
<li><code>autoAllocateChunkSize</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> Used only when <code>type</code> is equal to
<code>'bytes'</code>. When set to a non-zero value a view buffer is automatically
allocated to <code>ReadableByteStreamController.byobRequest</code>. When not set
one must use stream's internal queues to transfer data via the default
reader <code>ReadableStreamDefaultReader</code>.</li>
</ul>
</li>
<li><code>strategy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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 internal queue size before backpressure
is applied.</li>
<li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> A user-defined function used to identify the size of each
chunk of data.
<ul>
<li><code>chunk</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#Number_type" class="type">&#x3C;number></a></li>
</ul>
</li>
</ul>
</li>
</ul>
<!--lint enable maximum-line-length remark-lint-->
<h5><code>readableStream.locked</code><span><a class="mark" href="#all_webstreams_readablestreamlocked" id="all_webstreams_readablestreamlocked">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestream_locked"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Type: <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> if there is an active reader for this
<a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a>.</li>
</ul>
<p>The <code>readableStream.locked</code> property is <code>false</code> by default, and is
switched to <code>true</code> while there is an active reader consuming the
stream's data.</p>
<h5><code>readableStream.cancel([reason])</code><span><a class="mark" href="#all_webstreams_readablestreamcancelreason" id="all_webstreams_readablestreamcancelreason">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestream_cancel_reason"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>reason</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 promise fulfilled with <code>undefined</code> once cancelation has
been completed.</li>
</ul>
<h5><code>readableStream.getReader([options])</code><span><a class="mark" href="#all_webstreams_readablestreamgetreaderoptions" id="all_webstreams_readablestreamgetreaderoptions">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestream_getreader_options"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>mode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type">&#x3C;string></a> <code>'byob'</code> or <code>undefined</code></li>
</ul>
</li>
<li>Returns: <a href="#all_webstreams_class-readablestreamdefaultreader" class="type">&#x3C;ReadableStreamDefaultReader></a> | <a href="#all_webstreams_class-readablestreambyobreader" class="type">&#x3C;ReadableStreamBYOBReader></a></li>
</ul>

<pre class="with-54-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">ReadableStream</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/web'</span>;

<span class="hljs-keyword">const</span> stream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ReadableStream</span>();

<span class="hljs-keyword">const</span> reader = stream.<span class="hljs-title function_">getReader</span>();

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-keyword">await</span> reader.<span class="hljs-title function_">read</span>());</code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">ReadableStream</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/web'</span>);

<span class="hljs-keyword">const</span> stream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ReadableStream</span>();

<span class="hljs-keyword">const</span> reader = stream.<span class="hljs-title function_">getReader</span>();

reader.<span class="hljs-title function_">read</span>().<span class="hljs-title function_">then</span>(<span class="hljs-variable language_">console</span>.<span class="hljs-property">log</span>);</code><button class="copy-button">copy</button></pre>
<p>Causes the <code>readableStream.locked</code> to be <code>true</code>.</p>
<h5><code>readableStream.pipeThrough(transform[, options])</code><span><a class="mark" href="#all_webstreams_readablestreampipethroughtransform-options" id="all_webstreams_readablestreampipethroughtransform-options">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestream_pipethrough_transform_options"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>transform</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>readable</code> <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a> The <code>ReadableStream</code> to which
<code>transform.writable</code> will push the potentially modified data
it receives from this <code>ReadableStream</code>.</li>
<li><code>writable</code> <a href="#all_webstreams_class-writablestream" class="type">&#x3C;WritableStream></a> The <code>WritableStream</code> to which this
<code>ReadableStream</code>'s data will be written.</li>
</ul>
</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>
<ul>
<li><code>preventAbort</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>, errors in this <code>ReadableStream</code>
will not cause <code>transform.writable</code> to be aborted.</li>
<li><code>preventCancel</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>, errors in the destination
<code>transform.writable</code> do not cause this <code>ReadableStream</code> to be
canceled.</li>
<li><code>preventClose</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>, closing this <code>ReadableStream</code>
does not cause <code>transform.writable</code> to be closed.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> Allows the transfer of data to be canceled
using an <a href="#all_globals_class-abortcontroller" class="type">&#x3C;AbortController></a>.</li>
</ul>
</li>
<li>Returns: <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a> From <code>transform.readable</code>.</li>
</ul>
<p>Connects this <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a> to the pair of <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a> and
<a href="#all_webstreams_class-writablestream" class="type">&#x3C;WritableStream></a> provided in the <code>transform</code> argument such that the
data from this <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a> is written in to <code>transform.writable</code>,
possibly transformed, then pushed to <code>transform.readable</code>. Once the
pipeline is configured, <code>transform.readable</code> is returned.</p>
<p>Causes the <code>readableStream.locked</code> to be <code>true</code> while the pipe operation
is active.</p>

<pre class="with-17-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> {
  <span class="hljs-title class_">ReadableStream</span>,
  <span class="hljs-title class_">TransformStream</span>,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/web'</span>;

<span class="hljs-keyword">const</span> stream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ReadableStream</span>({
  <span class="hljs-title function_">start</span>(<span class="hljs-params">controller</span>) {
    controller.<span class="hljs-title function_">enqueue</span>(<span class="hljs-string">'a'</span>);
  },
});

<span class="hljs-keyword">const</span> transform = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TransformStream</span>({
  <span class="hljs-title function_">transform</span>(<span class="hljs-params">chunk, controller</span>) {
    controller.<span class="hljs-title function_">enqueue</span>(chunk.<span class="hljs-title function_">toUpperCase</span>());
  },
});

<span class="hljs-keyword">const</span> transformedStream = stream.<span class="hljs-title function_">pipeThrough</span>(transform);

<span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> transformedStream)
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk);
  <span class="hljs-comment">// Prints: A</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
  <span class="hljs-title class_">ReadableStream</span>,
  <span class="hljs-title class_">TransformStream</span>,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/web'</span>);

<span class="hljs-keyword">const</span> stream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ReadableStream</span>({
  <span class="hljs-title function_">start</span>(<span class="hljs-params">controller</span>) {
    controller.<span class="hljs-title function_">enqueue</span>(<span class="hljs-string">'a'</span>);
  },
});

<span class="hljs-keyword">const</span> transform = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TransformStream</span>({
  <span class="hljs-title function_">transform</span>(<span class="hljs-params">chunk, controller</span>) {
    controller.<span class="hljs-title function_">enqueue</span>(chunk.<span class="hljs-title function_">toUpperCase</span>());
  },
});

<span class="hljs-keyword">const</span> transformedStream = stream.<span class="hljs-title function_">pipeThrough</span>(transform);

(<span class="hljs-keyword">async</span> () => {
  <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> transformedStream)
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk);
    <span class="hljs-comment">// Prints: A</span>
})();</code><button class="copy-button">copy</button></pre>
<h5><code>readableStream.pipeTo(destination[, options])</code><span><a class="mark" href="#all_webstreams_readablestreampipetodestination-options" id="all_webstreams_readablestreampipetodestination-options">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestream_pipeto_destination_options"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>destination</code> <a href="#all_webstreams_class-writablestream" class="type">&#x3C;WritableStream></a> A <a href="#all_webstreams_class-writablestream" class="type">&#x3C;WritableStream></a> to which this
<code>ReadableStream</code>'s data will be written.</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>
<ul>
<li><code>preventAbort</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>, errors in this <code>ReadableStream</code>
will not cause <code>destination</code> to be aborted.</li>
<li><code>preventCancel</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>, errors in the <code>destination</code>
will not cause this <code>ReadableStream</code> to be canceled.</li>
<li><code>preventClose</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>, closing this <code>ReadableStream</code>
does not cause <code>destination</code> to be closed.</li>
<li><code>signal</code> <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> Allows the transfer of data to be canceled
using an <a href="#all_globals_class-abortcontroller" class="type">&#x3C;AbortController></a>.</li>
</ul>
</li>
<li>Returns: A promise fulfilled with <code>undefined</code></li>
</ul>
<p>Causes the <code>readableStream.locked</code> to be <code>true</code> while the pipe operation
is active.</p>
<h5><code>readableStream.tee()</code><span><a class="mark" href="#all_webstreams_readablestreamtee" id="all_webstreams_readablestreamtee">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestream_tee"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.10.0, v16.18.0</td>
<td><p>Support teeing a readable byte stream.</p></td></tr>
<tr><td>v16.5.0</td>
<td><p><span>Added in: v16.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>Returns: <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream[]></a></li>
</ul>
<p>Returns a pair of new <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a> instances to which this
<code>ReadableStream</code>'s data will be forwarded. Each will receive the
same data.</p>
<p>Causes the <code>readableStream.locked</code> to be <code>true</code>.</p>
<h5><code>readableStream.values([options])</code><span><a class="mark" href="#all_webstreams_readablestreamvaluesoptions" id="all_webstreams_readablestreamvaluesoptions">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestream_values_options"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>preventCancel</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>, prevents the <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a>
from being closed when the async iterator abruptly terminates.
<strong>Default</strong>: <code>false</code>.</li>
</ul>
</li>
</ul>
<p>Creates and returns an async iterator usable for consuming this
<code>ReadableStream</code>'s data.</p>
<p>Causes the <code>readableStream.locked</code> to be <code>true</code> while the async iterator
is active.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> stream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ReadableStream</span>(<span class="hljs-title function_">getSomeSource</span>());

<span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> stream.<span class="hljs-title function_">values</span>({ <span class="hljs-attr">preventCancel</span>: <span class="hljs-literal">true</span> }))
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(chunk).<span class="hljs-title function_">toString</span>());</code> <button class="copy-button">copy</button></pre>
<h5>Async Iteration<span><a class="mark" href="#all_webstreams_async-iteration" id="all_webstreams_async-iteration">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_async_iteration"></a></h5>
<p>The <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a> object supports the async iterator protocol using
<code>for await</code> syntax.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> stream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ReadableStream</span>(<span class="hljs-title function_">getSomeSource</span>());

<span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> stream)
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(chunk).<span class="hljs-title function_">toString</span>());</code> <button class="copy-button">copy</button></pre>
<p>The async iterator will consume the <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a> until it terminates.</p>
<p>By default, if the async iterator exits early (via either a <code>break</code>,
<code>return</code>, or a <code>throw</code>), the <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a> will be closed. To prevent
automatic closing of the <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a>, use the <code>readableStream.values()</code>
method to acquire the async iterator and set the <code>preventCancel</code> option to
<code>true</code>.</p>
<p>The <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a> must not be locked (that is, it must not have an existing
active reader). During the async iteration, the <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a> will be locked.</p>
<h5>Transferring with <code>postMessage()</code><span><a class="mark" href="#all_webstreams_transferring-with-postmessage" id="all_webstreams_transferring-with-postmessage">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_transferring_with_postmessage"></a></h5>
<p>A <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a> instance can be transferred using a <a href="#all_worker_threads_class-messageport" class="type">&#x3C;MessagePort></a>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> stream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ReadableStream</span>(<span class="hljs-title function_">getReadableSourceSomehow</span>());

<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();

port1.<span class="hljs-property">onmessage</span> = <span class="hljs-function">(<span class="hljs-params">{ data }</span>) =></span> {
  data.<span class="hljs-title function_">getReader</span>().<span class="hljs-title function_">read</span>().<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">chunk</span>) =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk);
  });
};

port2.<span class="hljs-title function_">postMessage</span>(stream, [stream]);</code> <button class="copy-button">copy</button></pre>
<h4><code>ReadableStream.from(iterable)</code><span><a class="mark" href="#all_webstreams_readablestreamfromiterable" id="all_webstreams_readablestreamfromiterable">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestream_from_iterable"></a></h4>
<div class="api_metadata">
<span>Added in: v20.6.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.</li>
</ul>
<p>A utility method that creates a new <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a> from an iterable.</p>

<pre class="with-54-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { <span class="hljs-title class_">ReadableStream</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/web'</span>;

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>* <span class="hljs-title function_">asyncIterableGenerator</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">yield</span> <span class="hljs-string">'a'</span>;
  <span class="hljs-keyword">yield</span> <span class="hljs-string">'b'</span>;
  <span class="hljs-keyword">yield</span> <span class="hljs-string">'c'</span>;
}

<span class="hljs-keyword">const</span> stream = <span class="hljs-title class_">ReadableStream</span>.<span class="hljs-title function_">from</span>(<span class="hljs-title function_">asyncIterableGenerator</span>());

<span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> stream)
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk); <span class="hljs-comment">// Prints: 'a', 'b', 'c'</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">ReadableStream</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/web'</span>);

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span>* <span class="hljs-title function_">asyncIterableGenerator</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">yield</span> <span class="hljs-string">'a'</span>;
  <span class="hljs-keyword">yield</span> <span class="hljs-string">'b'</span>;
  <span class="hljs-keyword">yield</span> <span class="hljs-string">'c'</span>;
}

(<span class="hljs-keyword">async</span> () => {
  <span class="hljs-keyword">const</span> stream = <span class="hljs-title class_">ReadableStream</span>.<span class="hljs-title function_">from</span>(<span class="hljs-title function_">asyncIterableGenerator</span>());

  <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> stream)
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk); <span class="hljs-comment">// Prints: 'a', 'b', 'c'</span>
})();</code><button class="copy-button">copy</button></pre>
<h4>Class: <code>ReadableStreamDefaultReader</code><span><a class="mark" href="#all_webstreams_class-readablestreamdefaultreader" id="all_webstreams_class-readablestreamdefaultreader">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_class_readablestreamdefaultreader"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>This class is now exposed on the global object.</p></td></tr>
<tr><td>v16.5.0</td>
<td><p><span>Added in: v16.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>By default, calling <code>readableStream.getReader()</code> with no arguments
will return an instance of <code>ReadableStreamDefaultReader</code>. The default
reader treats the chunks of data passed through the stream as opaque
values, which allows the <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a> to work with generally any
JavaScript value.</p>
<h5><code>new ReadableStreamDefaultReader(stream)</code><span><a class="mark" href="#all_webstreams_new-readablestreamdefaultreaderstream" id="all_webstreams_new-readablestreamdefaultreaderstream">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_new_readablestreamdefaultreader_stream"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>stream</code> <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a></li>
</ul>
<p>Creates a new <a href="#all_webstreams_class-readablestreamdefaultreader" class="type">&#x3C;ReadableStreamDefaultReader></a> that is locked to the
given <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a>.</p>
<h5><code>readableStreamDefaultReader.cancel([reason])</code><span><a class="mark" href="#all_webstreams_readablestreamdefaultreadercancelreason" id="all_webstreams_readablestreamdefaultreadercancelreason">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestreamdefaultreader_cancel_reason"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>reason</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 promise fulfilled with <code>undefined</code>.</li>
</ul>
<p>Cancels the <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a> and returns a promise that is fulfilled
when the underlying stream has been canceled.</p>
<h5><code>readableStreamDefaultReader.closed</code><span><a class="mark" href="#all_webstreams_readablestreamdefaultreaderclosed" id="all_webstreams_readablestreamdefaultreaderclosed">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestreamdefaultreader_closed"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> Fulfilled with <code>undefined</code> when the associated
<a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a> is closed or rejected if the stream errors or the reader's
lock is released before the stream finishes closing.</li>
</ul>
<h5><code>readableStreamDefaultReader.read()</code><span><a class="mark" href="#all_webstreams_readablestreamdefaultreaderread" id="all_webstreams_readablestreamdefaultreaderread">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestreamdefaultreader_read"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Returns: A promise fulfilled with an object:
<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>done</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>Requests the next chunk of data from the underlying <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a>
and returns a promise that is fulfilled with the data once it is
available.</p>
<h5><code>readableStreamDefaultReader.releaseLock()</code><span><a class="mark" href="#all_webstreams_readablestreamdefaultreaderreleaselock" id="all_webstreams_readablestreamdefaultreaderreleaselock">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestreamdefaultreader_releaselock"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<p>Releases this reader's lock on the underlying <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a>.</p>
<h4>Class: <code>ReadableStreamBYOBReader</code><span><a class="mark" href="#all_webstreams_class-readablestreambyobreader" id="all_webstreams_class-readablestreambyobreader">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_class_readablestreambyobreader"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>This class is now exposed on the global object.</p></td></tr>
<tr><td>v16.5.0</td>
<td><p><span>Added in: v16.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>The <code>ReadableStreamBYOBReader</code> is an alternative consumer for
byte-oriented <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a>s (those that are created with
<code>underlyingSource.type</code> set equal to <code>'bytes'</code> when the
<code>ReadableStream</code> was created).</p>
<p>The <code>BYOB</code> is short for "bring your own buffer". This is a
pattern that allows for more efficient reading of byte-oriented
data that avoids extraneous copying.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> {
  open,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:fs/promises'</span>;

<span class="hljs-keyword">import</span> {
  <span class="hljs-title class_">ReadableStream</span>,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/web'</span>;

<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">class</span> <span class="hljs-title class_">Source</span> {
  type = <span class="hljs-string">'bytes'</span>;
  autoAllocateChunkSize = <span class="hljs-number">1024</span>;

  <span class="hljs-keyword">async</span> <span class="hljs-title function_">start</span>(<span class="hljs-params">controller</span>) {
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">file</span> = <span class="hljs-keyword">await</span> <span class="hljs-title function_">open</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>));
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">controller</span> = controller;
  }

  <span class="hljs-keyword">async</span> <span class="hljs-title function_">pull</span>(<span class="hljs-params">controller</span>) {
    <span class="hljs-keyword">const</span> view = controller.<span class="hljs-property">byobRequest</span>?.<span class="hljs-property">view</span>;
    <span class="hljs-keyword">const</span> {
      bytesRead,
    } = <span class="hljs-keyword">await</span> <span class="hljs-variable language_">this</span>.<span class="hljs-property">file</span>.<span class="hljs-title function_">read</span>({
      <span class="hljs-attr">buffer</span>: view,
      <span class="hljs-attr">offset</span>: view.<span class="hljs-property">byteOffset</span>,
      <span class="hljs-attr">length</span>: view.<span class="hljs-property">byteLength</span>,
    });

    <span class="hljs-keyword">if</span> (bytesRead === <span class="hljs-number">0</span>) {
      <span class="hljs-keyword">await</span> <span class="hljs-variable language_">this</span>.<span class="hljs-property">file</span>.<span class="hljs-title function_">close</span>();
      <span class="hljs-variable language_">this</span>.<span class="hljs-property">controller</span>.<span class="hljs-title function_">close</span>();
    }
    controller.<span class="hljs-property">byobRequest</span>.<span class="hljs-title function_">respond</span>(bytesRead);
  }
}

<span class="hljs-keyword">const</span> stream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ReadableStream</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Source</span>());

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">read</span>(<span class="hljs-params">stream</span>) {
  <span class="hljs-keyword">const</span> reader = stream.<span class="hljs-title function_">getReader</span>({ <span class="hljs-attr">mode</span>: <span class="hljs-string">'byob'</span> });

  <span class="hljs-keyword">const</span> chunks = [];
  <span class="hljs-keyword">let</span> result;
  <span class="hljs-keyword">do</span> {
    result = <span class="hljs-keyword">await</span> reader.<span class="hljs-title function_">read</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">alloc</span>(<span class="hljs-number">100</span>));
    <span class="hljs-keyword">if</span> (result.<span class="hljs-property">value</span> !== <span class="hljs-literal">undefined</span>)
      chunks.<span class="hljs-title function_">push</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(result.<span class="hljs-property">value</span>));
  } <span class="hljs-keyword">while</span> (!result.<span class="hljs-property">done</span>);

  <span class="hljs-keyword">return</span> <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">concat</span>(chunks);
}

<span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> <span class="hljs-title function_">read</span>(stream);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(data).<span class="hljs-title function_">toString</span>());</code> <button class="copy-button">copy</button></pre>
<h5><code>new ReadableStreamBYOBReader(stream)</code><span><a class="mark" href="#all_webstreams_new-readablestreambyobreaderstream" id="all_webstreams_new-readablestreambyobreaderstream">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_new_readablestreambyobreader_stream"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>stream</code> <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a></li>
</ul>
<p>Creates a new <code>ReadableStreamBYOBReader</code> that is locked to the
given <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a>.</p>
<h5><code>readableStreamBYOBReader.cancel([reason])</code><span><a class="mark" href="#all_webstreams_readablestreambyobreadercancelreason" id="all_webstreams_readablestreambyobreadercancelreason">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestreambyobreader_cancel_reason"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>reason</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 promise fulfilled with <code>undefined</code>.</li>
</ul>
<p>Cancels the <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a> and returns a promise that is fulfilled
when the underlying stream has been canceled.</p>
<h5><code>readableStreamBYOBReader.closed</code><span><a class="mark" href="#all_webstreams_readablestreambyobreaderclosed" id="all_webstreams_readablestreambyobreaderclosed">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestreambyobreader_closed"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> Fulfilled with <code>undefined</code> when the associated
<a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a> is closed or rejected if the stream errors or the reader's
lock is released before the stream finishes closing.</li>
</ul>
<h5><code>readableStreamBYOBReader.read(view[, options])</code><span><a class="mark" href="#all_webstreams_readablestreambyobreaderreadview-options" id="all_webstreams_readablestreambyobreaderreadview-options">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestreambyobreader_read_view_options"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.17.0</td>
<td><p>Added <code>min</code> option.</p></td></tr>
<tr><td>v16.5.0</td>
<td><p><span>Added in: v16.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>view</code> <a href="#all_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>
<ul>
<li><code>min</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> When set, the returned promise will only be
fulfilled as soon as <code>min</code> number of elements are available.
When not set, the promise fulfills when at least one element
is available.</li>
</ul>
</li>
<li>Returns: A promise fulfilled with an object:
<ul>
<li><code>value</code> <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>done</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>Requests the next chunk of data from the underlying <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a>
and returns a promise that is fulfilled with the data once it is
available.</p>
<p>Do not pass a pooled <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> object instance in to this method.
Pooled <code>Buffer</code> objects are created using <code>Buffer.allocUnsafe()</code>,
or <code>Buffer.from()</code>, or are often returned by various <code>node:fs</code> module
callbacks. These types of <code>Buffer</code>s use a shared underlying
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer" class="type">&#x3C;ArrayBuffer></a> object that contains all of the data from all of
the pooled <code>Buffer</code> instances. When a <code>Buffer</code>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray" class="type">&#x3C;TypedArray></a>,
or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView" class="type">&#x3C;DataView></a> is passed in to <code>readableStreamBYOBReader.read()</code>,
the view's underlying <code>ArrayBuffer</code> is <em>detached</em>, invalidating
all existing views that may exist on that <code>ArrayBuffer</code>. This
can have disastrous consequences for your application.</p>
<h5><code>readableStreamBYOBReader.releaseLock()</code><span><a class="mark" href="#all_webstreams_readablestreambyobreaderreleaselock" id="all_webstreams_readablestreambyobreaderreleaselock">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestreambyobreader_releaselock"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<p>Releases this reader's lock on the underlying <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a>.</p>
<h4>Class: <code>ReadableStreamDefaultController</code><span><a class="mark" href="#all_webstreams_class-readablestreamdefaultcontroller" id="all_webstreams_class-readablestreamdefaultcontroller">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_class_readablestreamdefaultcontroller"></a></h4>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<p>Every <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a> has a controller that is responsible for
the internal state and management of the stream's queue. The
<code>ReadableStreamDefaultController</code> is the default controller
implementation for <code>ReadableStream</code>s that are not byte-oriented.</p>
<h5><code>readableStreamDefaultController.close()</code><span><a class="mark" href="#all_webstreams_readablestreamdefaultcontrollerclose" id="all_webstreams_readablestreamdefaultcontrollerclose">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestreamdefaultcontroller_close"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<p>Closes the <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a> to which this controller is associated.</p>
<h5><code>readableStreamDefaultController.desiredSize</code><span><a class="mark" href="#all_webstreams_readablestreamdefaultcontrollerdesiredsize" id="all_webstreams_readablestreamdefaultcontrollerdesiredsize">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestreamdefaultcontroller_desiredsize"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Type: <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 amount of data remaining to fill the <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a>'s
queue.</p>
<h5><code>readableStreamDefaultController.enqueue([chunk])</code><span><a class="mark" href="#all_webstreams_readablestreamdefaultcontrollerenqueuechunk" id="all_webstreams_readablestreamdefaultcontrollerenqueuechunk">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestreamdefaultcontroller_enqueue_chunk"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>chunk</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
</ul>
<p>Appends a new chunk of data to the <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a>'s queue.</p>
<h5><code>readableStreamDefaultController.error([error])</code><span><a class="mark" href="#all_webstreams_readablestreamdefaultcontrollererrorerror" id="all_webstreams_readablestreamdefaultcontrollererrorerror">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestreamdefaultcontroller_error_error"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
</ul>
<p>Signals an error that causes the <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a> to error and close.</p>
<h4>Class: <code>ReadableByteStreamController</code><span><a class="mark" href="#all_webstreams_class-readablebytestreamcontroller" id="all_webstreams_class-readablebytestreamcontroller">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_class_readablebytestreamcontroller"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.10.0</td>
<td><p>Support handling a BYOB pull request from a released reader.</p></td></tr>
<tr><td>v16.5.0</td>
<td><p><span>Added in: v16.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Every <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a> has a controller that is responsible for
the internal state and management of the stream's queue. The
<code>ReadableByteStreamController</code> is for byte-oriented <code>ReadableStream</code>s.</p>
<h5><code>readableByteStreamController.byobRequest</code><span><a class="mark" href="#all_webstreams_readablebytestreamcontrollerbyobrequest" id="all_webstreams_readablebytestreamcontrollerbyobrequest">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablebytestreamcontroller_byobrequest"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Type: <a href="#all_webstreams_class-readablestreambyobrequest" class="type">&#x3C;ReadableStreamBYOBRequest></a></li>
</ul>
<h5><code>readableByteStreamController.close()</code><span><a class="mark" href="#all_webstreams_readablebytestreamcontrollerclose" id="all_webstreams_readablebytestreamcontrollerclose">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablebytestreamcontroller_close"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<p>Closes the <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a> to which this controller is associated.</p>
<h5><code>readableByteStreamController.desiredSize</code><span><a class="mark" href="#all_webstreams_readablebytestreamcontrollerdesiredsize" id="all_webstreams_readablebytestreamcontrollerdesiredsize">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablebytestreamcontroller_desiredsize"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Type: <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 amount of data remaining to fill the <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a>'s
queue.</p>
<h5><code>readableByteStreamController.enqueue(chunk)</code><span><a class="mark" href="#all_webstreams_readablebytestreamcontrollerenqueuechunk" id="all_webstreams_readablebytestreamcontrollerenqueuechunk">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablebytestreamcontroller_enqueue_chunk"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>chunk</code>: <a href="#all_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>Appends a new chunk of data to the <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a>'s queue.</p>
<h5><code>readableByteStreamController.error([error])</code><span><a class="mark" href="#all_webstreams_readablebytestreamcontrollererrorerror" id="all_webstreams_readablebytestreamcontrollererrorerror">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablebytestreamcontroller_error_error"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
</ul>
<p>Signals an error that causes the <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a> to error and close.</p>
<h4>Class: <code>ReadableStreamBYOBRequest</code><span><a class="mark" href="#all_webstreams_class-readablestreambyobrequest" id="all_webstreams_class-readablestreambyobrequest">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_class_readablestreambyobrequest"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>This class is now exposed on the global object.</p></td></tr>
<tr><td>v16.5.0</td>
<td><p><span>Added in: v16.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>When using <code>ReadableByteStreamController</code> in byte-oriented
streams, and when using the <code>ReadableStreamBYOBReader</code>,
the <code>readableByteStreamController.byobRequest</code> property
provides access to a <code>ReadableStreamBYOBRequest</code> instance
that represents the current read request. The object
is used to gain access to the <code>ArrayBuffer</code>/<code>TypedArray</code>
that has been provided for the read request to fill,
and provides methods for signaling that the data has
been provided.</p>
<h5><code>readableStreamBYOBRequest.respond(bytesWritten)</code><span><a class="mark" href="#all_webstreams_readablestreambyobrequestrespondbyteswritten" id="all_webstreams_readablestreambyobrequestrespondbyteswritten">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestreambyobrequest_respond_byteswritten"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>bytesWritten</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>Signals that a <code>bytesWritten</code> number of bytes have been written
to <code>readableStreamBYOBRequest.view</code>.</p>
<h5><code>readableStreamBYOBRequest.respondWithNewView(view)</code><span><a class="mark" href="#all_webstreams_readablestreambyobrequestrespondwithnewviewview" id="all_webstreams_readablestreambyobrequestrespondwithnewviewview">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestreambyobrequest_respondwithnewview_view"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>view</code> <a href="#all_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>Signals that the request has been fulfilled with bytes written
to a new <code>Buffer</code>, <code>TypedArray</code>, or <code>DataView</code>.</p>
<h5><code>readableStreamBYOBRequest.view</code><span><a class="mark" href="#all_webstreams_readablestreambyobrequestview" id="all_webstreams_readablestreambyobrequestview">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_readablestreambyobrequest_view"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Type: <a href="#all_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>
<h4>Class: <code>WritableStream</code><span><a class="mark" href="#all_webstreams_class-writablestream" id="all_webstreams_class-writablestream">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_class_writablestream"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>This class is now exposed on the global object.</p></td></tr>
<tr><td>v16.5.0</td>
<td><p><span>Added in: v16.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>The <code>WritableStream</code> is a destination to which stream data is sent.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> {
  <span class="hljs-title class_">WritableStream</span>,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/web'</span>;

<span class="hljs-keyword">const</span> stream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WritableStream</span>({
  <span class="hljs-title function_">write</span>(<span class="hljs-params">chunk</span>) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(chunk);
  },
});

<span class="hljs-keyword">await</span> stream.<span class="hljs-title function_">getWriter</span>().<span class="hljs-title function_">write</span>(<span class="hljs-string">'Hello World'</span>);</code> <button class="copy-button">copy</button></pre>
<h5><code>new WritableStream([underlyingSink[, strategy]])</code><span><a class="mark" href="#all_webstreams_new-writablestreamunderlyingsink-strategy" id="all_webstreams_new-writablestreamunderlyingsink-strategy">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_new_writablestream_underlyingsink_strategy"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>underlyingSink</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>start</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> A user-defined function that is invoked immediately when
the <code>WritableStream</code> is created.
<ul>
<li><code>controller</code> <a href="#all_webstreams_class-writablestreamdefaultcontroller" class="type">&#x3C;WritableStreamDefaultController></a></li>
<li>Returns: <code>undefined</code> or a promise fulfilled with <code>undefined</code>.</li>
</ul>
</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> A user-defined function that is invoked when a chunk of
data has been written to the <code>WritableStream</code>.
<ul>
<li><code>chunk</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li><code>controller</code> <a href="#all_webstreams_class-writablestreamdefaultcontroller" class="type">&#x3C;WritableStreamDefaultController></a></li>
<li>Returns: A promise fulfilled with <code>undefined</code>.</li>
</ul>
</li>
<li><code>close</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> A user-defined function that is called when the
<code>WritableStream</code> is closed.
<ul>
<li>Returns: A promise fulfilled with <code>undefined</code>.</li>
</ul>
</li>
<li><code>abort</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> A user-defined function that is called to abruptly close
the <code>WritableStream</code>.
<ul>
<li><code>reason</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 promise fulfilled with <code>undefined</code>.</li>
</ul>
</li>
<li><code>type</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> The <code>type</code> option is reserved for future use and <em>must</em> be
undefined.</li>
</ul>
</li>
<li><code>strategy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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 internal queue size before backpressure
is applied.</li>
<li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> A user-defined function used to identify the size of each
chunk of data.
<ul>
<li><code>chunk</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#Number_type" class="type">&#x3C;number></a></li>
</ul>
</li>
</ul>
</li>
</ul>
<h5><code>writableStream.abort([reason])</code><span><a class="mark" href="#all_webstreams_writablestreamabortreason" id="all_webstreams_writablestreamabortreason">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_writablestream_abort_reason"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>reason</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 promise fulfilled with <code>undefined</code>.</li>
</ul>
<p>Abruptly terminates the <code>WritableStream</code>. All queued writes will be
canceled with their associated promises rejected.</p>
<h5><code>writableStream.close()</code><span><a class="mark" href="#all_webstreams_writablestreamclose" id="all_webstreams_writablestreamclose">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_writablestream_close"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Returns: A promise fulfilled with <code>undefined</code>.</li>
</ul>
<p>Closes the <code>WritableStream</code> when no additional writes are expected.</p>
<h5><code>writableStream.getWriter()</code><span><a class="mark" href="#all_webstreams_writablestreamgetwriter" id="all_webstreams_writablestreamgetwriter">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_writablestream_getwriter"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Returns: <a href="#all_webstreams_class-writablestreamdefaultwriter" class="type">&#x3C;WritableStreamDefaultWriter></a></li>
</ul>
<p>Creates and returns a new writer instance that can be used to write
data into the <code>WritableStream</code>.</p>
<h5><code>writableStream.locked</code><span><a class="mark" href="#all_webstreams_writablestreamlocked" id="all_webstreams_writablestreamlocked">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_writablestream_locked"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Type: <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>writableStream.locked</code> property is <code>false</code> by default, and is
switched to <code>true</code> while there is an active writer attached to this
<code>WritableStream</code>.</p>
<h5>Transferring with postMessage()<span><a class="mark" href="#all_webstreams_transferring-with-postmessage_1" id="all_webstreams_transferring-with-postmessage_1">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_transferring_with_postmessage_1"></a></h5>
<p>A <a href="#all_webstreams_class-writablestream" class="type">&#x3C;WritableStream></a> instance can be transferred using a <a href="#all_worker_threads_class-messageport" class="type">&#x3C;MessagePort></a>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> stream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">WritableStream</span>(<span class="hljs-title function_">getWritableSinkSomehow</span>());

<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();

port1.<span class="hljs-property">onmessage</span> = <span class="hljs-function">(<span class="hljs-params">{ data }</span>) =></span> {
  data.<span class="hljs-title function_">getWriter</span>().<span class="hljs-title function_">write</span>(<span class="hljs-string">'hello'</span>);
};

port2.<span class="hljs-title function_">postMessage</span>(stream, [stream]);</code> <button class="copy-button">copy</button></pre>
<h4>Class: <code>WritableStreamDefaultWriter</code><span><a class="mark" href="#all_webstreams_class-writablestreamdefaultwriter" id="all_webstreams_class-writablestreamdefaultwriter">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_class_writablestreamdefaultwriter"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>This class is now exposed on the global object.</p></td></tr>
<tr><td>v16.5.0</td>
<td><p><span>Added in: v16.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<h5><code>new WritableStreamDefaultWriter(stream)</code><span><a class="mark" href="#all_webstreams_new-writablestreamdefaultwriterstream" id="all_webstreams_new-writablestreamdefaultwriterstream">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_new_writablestreamdefaultwriter_stream"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>stream</code> <a href="#all_webstreams_class-writablestream" class="type">&#x3C;WritableStream></a></li>
</ul>
<p>Creates a new <code>WritableStreamDefaultWriter</code> that is locked to the given
<code>WritableStream</code>.</p>
<h5><code>writableStreamDefaultWriter.abort([reason])</code><span><a class="mark" href="#all_webstreams_writablestreamdefaultwriterabortreason" id="all_webstreams_writablestreamdefaultwriterabortreason">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_writablestreamdefaultwriter_abort_reason"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>reason</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 promise fulfilled with <code>undefined</code>.</li>
</ul>
<p>Abruptly terminates the <code>WritableStream</code>. All queued writes will be
canceled with their associated promises rejected.</p>
<h5><code>writableStreamDefaultWriter.close()</code><span><a class="mark" href="#all_webstreams_writablestreamdefaultwriterclose" id="all_webstreams_writablestreamdefaultwriterclose">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_writablestreamdefaultwriter_close"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Returns: A promise fulfilled with <code>undefined</code>.</li>
</ul>
<p>Closes the <code>WritableStream</code> when no additional writes are expected.</p>
<h5><code>writableStreamDefaultWriter.closed</code><span><a class="mark" href="#all_webstreams_writablestreamdefaultwriterclosed" id="all_webstreams_writablestreamdefaultwriterclosed">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_writablestreamdefaultwriter_closed"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> Fulfilled with <code>undefined</code> when the associated
<a href="#all_webstreams_class-writablestream" class="type">&#x3C;WritableStream></a> is closed or rejected if the stream errors or the writer's
lock is released before the stream finishes closing.</li>
</ul>
<h5><code>writableStreamDefaultWriter.desiredSize</code><span><a class="mark" href="#all_webstreams_writablestreamdefaultwriterdesiredsize" id="all_webstreams_writablestreamdefaultwriterdesiredsize">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_writablestreamdefaultwriter_desiredsize"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>The amount of data required to fill the <a href="#all_webstreams_class-writablestream" class="type">&#x3C;WritableStream></a>'s queue.</p>
<h5><code>writableStreamDefaultWriter.ready</code><span><a class="mark" href="#all_webstreams_writablestreamdefaultwriterready" id="all_webstreams_writablestreamdefaultwriterready">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_writablestreamdefaultwriter_ready"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> Fulfilled with <code>undefined</code> when the writer is ready
to be used.</li>
</ul>
<h5><code>writableStreamDefaultWriter.releaseLock()</code><span><a class="mark" href="#all_webstreams_writablestreamdefaultwriterreleaselock" id="all_webstreams_writablestreamdefaultwriterreleaselock">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_writablestreamdefaultwriter_releaselock"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<p>Releases this writer's lock on the underlying <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a>.</p>
<h5><code>writableStreamDefaultWriter.write([chunk])</code><span><a class="mark" href="#all_webstreams_writablestreamdefaultwriterwritechunk" id="all_webstreams_writablestreamdefaultwriterwritechunk">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_writablestreamdefaultwriter_write_chunk"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>chunk</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 promise fulfilled with <code>undefined</code>.</li>
</ul>
<p>Appends a new chunk of data to the <a href="#all_webstreams_class-writablestream" class="type">&#x3C;WritableStream></a>'s queue.</p>
<h4>Class: <code>WritableStreamDefaultController</code><span><a class="mark" href="#all_webstreams_class-writablestreamdefaultcontroller" id="all_webstreams_class-writablestreamdefaultcontroller">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_class_writablestreamdefaultcontroller"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>This class is now exposed on the global object.</p></td></tr>
<tr><td>v16.5.0</td>
<td><p><span>Added in: v16.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>The <code>WritableStreamDefaultController</code> manages the <a href="#all_webstreams_class-writablestream" class="type">&#x3C;WritableStream></a>'s
internal state.</p>
<h5><code>writableStreamDefaultController.error([error])</code><span><a class="mark" href="#all_webstreams_writablestreamdefaultcontrollererrorerror" id="all_webstreams_writablestreamdefaultcontrollererrorerror">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_writablestreamdefaultcontroller_error_error"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>error</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
</ul>
<p>Called by user-code to signal that an error has occurred while processing
the <code>WritableStream</code> data. When called, the <a href="#all_webstreams_class-writablestream" class="type">&#x3C;WritableStream></a> will be aborted,
with currently pending writes canceled.</p>
<h5><code>writableStreamDefaultController.signal</code><span><a class="mark" href="#all_webstreams_writablestreamdefaultcontrollersignal" id="all_webstreams_writablestreamdefaultcontrollersignal">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_writablestreamdefaultcontroller_signal"></a></h5>
<ul>
<li>Type: <a href="#all_globals_class-abortsignal" class="type">&#x3C;AbortSignal></a> An <code>AbortSignal</code> that can be used to cancel pending
write or close operations when a <a href="#all_webstreams_class-writablestream" class="type">&#x3C;WritableStream></a> is aborted.</li>
</ul>
<h4>Class: <code>TransformStream</code><span><a class="mark" href="#all_webstreams_class-transformstream" id="all_webstreams_class-transformstream">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_class_transformstream"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>This class is now exposed on the global object.</p></td></tr>
<tr><td>v16.5.0</td>
<td><p><span>Added in: v16.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>A <code>TransformStream</code> consists of a <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a> and a <a href="#all_webstreams_class-writablestream" class="type">&#x3C;WritableStream></a> that
are connected such that the data written to the <code>WritableStream</code> is received,
and potentially transformed, before being pushed into the <code>ReadableStream</code>'s
queue.</p>
<pre><code class="language-js mjs"><span class="hljs-keyword">import</span> {
  <span class="hljs-title class_">TransformStream</span>,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/web'</span>;

<span class="hljs-keyword">const</span> transform = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TransformStream</span>({
  <span class="hljs-title function_">transform</span>(<span class="hljs-params">chunk, controller</span>) {
    controller.<span class="hljs-title function_">enqueue</span>(chunk.<span class="hljs-title function_">toUpperCase</span>());
  },
});

<span class="hljs-keyword">await</span> <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">all</span>([
  transform.<span class="hljs-property">writable</span>.<span class="hljs-title function_">getWriter</span>().<span class="hljs-title function_">write</span>(<span class="hljs-string">'A'</span>),
  transform.<span class="hljs-property">readable</span>.<span class="hljs-title function_">getReader</span>().<span class="hljs-title function_">read</span>(),
]);</code> <button class="copy-button">copy</button></pre>
<h5><code>new TransformStream([transformer[, writableStrategy[, readableStrategy]]])</code><span><a class="mark" href="#all_webstreams_new-transformstreamtransformer-writablestrategy-readablestrategy" id="all_webstreams_new-transformstreamtransformer-writablestrategy-readablestrategy">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_new_transformstream_transformer_writablestrategy_readablestrategy"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>transformer</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>start</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> A user-defined function that is invoked immediately when
the <code>TransformStream</code> is created.
<ul>
<li><code>controller</code> <a href="#all_webstreams_class-transformstreamdefaultcontroller" class="type">&#x3C;TransformStreamDefaultController></a></li>
<li>Returns: <code>undefined</code> or a promise fulfilled with <code>undefined</code></li>
</ul>
</li>
<li><code>transform</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> A user-defined function that receives, and
potentially modifies, a chunk of data written to <code>transformStream.writable</code>,
before forwarding that on to <code>transformStream.readable</code>.
<ul>
<li><code>chunk</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
<li><code>controller</code> <a href="#all_webstreams_class-transformstreamdefaultcontroller" class="type">&#x3C;TransformStreamDefaultController></a></li>
<li>Returns: A promise fulfilled with <code>undefined</code>.</li>
</ul>
</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> A user-defined function that is called immediately before
the writable side of the <code>TransformStream</code> is closed, signaling the end of
the transformation process.
<ul>
<li><code>controller</code> <a href="#all_webstreams_class-transformstreamdefaultcontroller" class="type">&#x3C;TransformStreamDefaultController></a></li>
<li>Returns: A promise fulfilled with <code>undefined</code>.</li>
</ul>
</li>
<li><code>readableType</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> the <code>readableType</code> option is reserved for future use
and <em>must</em> be <code>undefined</code>.</li>
<li><code>writableType</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> the <code>writableType</code> option is reserved for future use
and <em>must</em> be <code>undefined</code>.</li>
</ul>
</li>
<li><code>writableStrategy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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 internal queue size before backpressure
is applied.</li>
<li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> A user-defined function used to identify the size of each
chunk of data.
<ul>
<li><code>chunk</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#Number_type" class="type">&#x3C;number></a></li>
</ul>
</li>
</ul>
</li>
<li><code>readableStrategy</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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 internal queue size before backpressure
is applied.</li>
<li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> A user-defined function used to identify the size of each
chunk of data.
<ul>
<li><code>chunk</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#Number_type" class="type">&#x3C;number></a></li>
</ul>
</li>
</ul>
</li>
</ul>
<h5><code>transformStream.readable</code><span><a class="mark" href="#all_webstreams_transformstreamreadable" id="all_webstreams_transformstreamreadable">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_transformstream_readable"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Type: <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a></li>
</ul>
<h5><code>transformStream.writable</code><span><a class="mark" href="#all_webstreams_transformstreamwritable" id="all_webstreams_transformstreamwritable">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_transformstream_writable"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Type: <a href="#all_webstreams_class-writablestream" class="type">&#x3C;WritableStream></a></li>
</ul>
<h5>Transferring with postMessage()<span><a class="mark" href="#all_webstreams_transferring-with-postmessage_2" id="all_webstreams_transferring-with-postmessage_2">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_transferring_with_postmessage_2"></a></h5>
<p>A <a href="#all_webstreams_class-transformstream" class="type">&#x3C;TransformStream></a> instance can be transferred using a <a href="#all_worker_threads_class-messageport" class="type">&#x3C;MessagePort></a>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> stream = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TransformStream</span>();

<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();

port1.<span class="hljs-property">onmessage</span> = <span class="hljs-function">(<span class="hljs-params">{ data }</span>) =></span> {
  <span class="hljs-keyword">const</span> { writable, readable } = data;
  <span class="hljs-comment">// ...</span>
};

port2.<span class="hljs-title function_">postMessage</span>(stream, [stream]);</code> <button class="copy-button">copy</button></pre>
<h4>Class: <code>TransformStreamDefaultController</code><span><a class="mark" href="#all_webstreams_class-transformstreamdefaultcontroller" id="all_webstreams_class-transformstreamdefaultcontroller">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_class_transformstreamdefaultcontroller"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>This class is now exposed on the global object.</p></td></tr>
<tr><td>v16.5.0</td>
<td><p><span>Added in: v16.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>The <code>TransformStreamDefaultController</code> manages the internal state
of the <code>TransformStream</code>.</p>
<h5><code>transformStreamDefaultController.desiredSize</code><span><a class="mark" href="#all_webstreams_transformstreamdefaultcontrollerdesiredsize" id="all_webstreams_transformstreamdefaultcontrollerdesiredsize">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_transformstreamdefaultcontroller_desiredsize"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<p>The amount of data required to fill the readable side's queue.</p>
<h5><code>transformStreamDefaultController.enqueue([chunk])</code><span><a class="mark" href="#all_webstreams_transformstreamdefaultcontrollerenqueuechunk" id="all_webstreams_transformstreamdefaultcontrollerenqueuechunk">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_transformstreamdefaultcontroller_enqueue_chunk"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>chunk</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
</ul>
<p>Appends a chunk of data to the readable side's queue.</p>
<h5><code>transformStreamDefaultController.error([reason])</code><span><a class="mark" href="#all_webstreams_transformstreamdefaultcontrollererrorreason" id="all_webstreams_transformstreamdefaultcontrollererrorreason">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_transformstreamdefaultcontroller_error_reason"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>reason</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a></li>
</ul>
<p>Signals to both the readable and writable side that an error has occurred
while processing the transform data, causing both sides to be abruptly
closed.</p>
<h5><code>transformStreamDefaultController.terminate()</code><span><a class="mark" href="#all_webstreams_transformstreamdefaultcontrollerterminate" id="all_webstreams_transformstreamdefaultcontrollerterminate">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_transformstreamdefaultcontroller_terminate"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<p>Closes the readable side of the transport and causes the writable side
to be abruptly closed with an error.</p>
<h4>Class: <code>ByteLengthQueuingStrategy</code><span><a class="mark" href="#all_webstreams_class-bytelengthqueuingstrategy" id="all_webstreams_class-bytelengthqueuingstrategy">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_class_bytelengthqueuingstrategy"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>This class is now exposed on the global object.</p></td></tr>
<tr><td>v16.5.0</td>
<td><p><span>Added in: v16.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<h5><code>new ByteLengthQueuingStrategy(init)</code><span><a class="mark" href="#all_webstreams_new-bytelengthqueuingstrategyinit" id="all_webstreams_new-bytelengthqueuingstrategyinit">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_new_bytelengthqueuingstrategy_init"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>init</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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></li>
</ul>
</li>
</ul>
<h5><code>byteLengthQueuingStrategy.highWaterMark</code><span><a class="mark" href="#all_webstreams_bytelengthqueuingstrategyhighwatermark" id="all_webstreams_bytelengthqueuingstrategyhighwatermark">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_bytelengthqueuingstrategy_highwatermark"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<h5><code>byteLengthQueuingStrategy.size</code><span><a class="mark" href="#all_webstreams_bytelengthqueuingstrategysize" id="all_webstreams_bytelengthqueuingstrategysize">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_bytelengthqueuingstrategy_size"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<ul>
<li><code>chunk</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#Number_type" class="type">&#x3C;number></a></li>
</ul>
</li>
</ul>
<h4>Class: <code>CountQueuingStrategy</code><span><a class="mark" href="#all_webstreams_class-countqueuingstrategy" id="all_webstreams_class-countqueuingstrategy">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_class_countqueuingstrategy"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>This class is now exposed on the global object.</p></td></tr>
<tr><td>v16.5.0</td>
<td><p><span>Added in: v16.5.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<h5><code>new CountQueuingStrategy(init)</code><span><a class="mark" href="#all_webstreams_new-countqueuingstrategyinit" id="all_webstreams_new-countqueuingstrategyinit">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_new_countqueuingstrategy_init"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li><code>init</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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></li>
</ul>
</li>
</ul>
<h5><code>countQueuingStrategy.highWaterMark</code><span><a class="mark" href="#all_webstreams_countqueuingstrategyhighwatermark" id="all_webstreams_countqueuingstrategyhighwatermark">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_countqueuingstrategy_highwatermark"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
</ul>
<h5><code>countQueuingStrategy.size</code><span><a class="mark" href="#all_webstreams_countqueuingstrategysize" id="all_webstreams_countqueuingstrategysize">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_countqueuingstrategy_size"></a></h5>
<div class="api_metadata">
<span>Added in: v16.5.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a>
<ul>
<li><code>chunk</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#Number_type" class="type">&#x3C;number></a></li>
</ul>
</li>
</ul>
<h4>Class: <code>TextEncoderStream</code><span><a class="mark" href="#all_webstreams_class-textencoderstream" id="all_webstreams_class-textencoderstream">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_class_textencoderstream"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>This class is now exposed on the global object.</p></td></tr>
<tr><td>v16.6.0</td>
<td><p><span>Added in: v16.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<h5><code>new TextEncoderStream()</code><span><a class="mark" href="#all_webstreams_new-textencoderstream" id="all_webstreams_new-textencoderstream">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_new_textencoderstream"></a></h5>
<div class="api_metadata">
<span>Added in: v16.6.0</span>
</div>
<p>Creates a new <code>TextEncoderStream</code> instance.</p>
<h5><code>textEncoderStream.encoding</code><span><a class="mark" href="#all_webstreams_textencoderstreamencoding" id="all_webstreams_textencoderstreamencoding">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_textencoderstream_encoding"></a></h5>
<div class="api_metadata">
<span>Added in: v16.6.0</span>
</div>
<ul>
<li>Type: <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>TextEncoderStream</code> instance.</p>
<h5><code>textEncoderStream.readable</code><span><a class="mark" href="#all_webstreams_textencoderstreamreadable" id="all_webstreams_textencoderstreamreadable">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_textencoderstream_readable"></a></h5>
<div class="api_metadata">
<span>Added in: v16.6.0</span>
</div>
<ul>
<li>Type: <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a></li>
</ul>
<h5><code>textEncoderStream.writable</code><span><a class="mark" href="#all_webstreams_textencoderstreamwritable" id="all_webstreams_textencoderstreamwritable">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_textencoderstream_writable"></a></h5>
<div class="api_metadata">
<span>Added in: v16.6.0</span>
</div>
<ul>
<li>Type: <a href="#all_webstreams_class-writablestream" class="type">&#x3C;WritableStream></a></li>
</ul>
<h4>Class: <code>TextDecoderStream</code><span><a class="mark" href="#all_webstreams_class-textdecoderstream" id="all_webstreams_class-textdecoderstream">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_class_textdecoderstream"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>This class is now exposed on the global object.</p></td></tr>
<tr><td>v16.6.0</td>
<td><p><span>Added in: v16.6.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<h5><code>new TextDecoderStream([encoding[, options]])</code><span><a class="mark" href="#all_webstreams_new-textdecoderstreamencoding-options" id="all_webstreams_new-textdecoderstreamencoding-options">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_new_textdecoderstream_encoding_options"></a></h5>
<div class="api_metadata">
<span>Added in: v16.6.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> Identifies the <code>encoding</code> that this <code>TextDecoder</code> instance
supports. <strong>Default:</strong> <code>'utf-8'</code>.</li>
<li><code>options</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<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.</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>TextDecoderStream</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 a new <code>TextDecoderStream</code> instance.</p>
<h5><code>textDecoderStream.encoding</code><span><a class="mark" href="#all_webstreams_textdecoderstreamencoding" id="all_webstreams_textdecoderstreamencoding">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_textdecoderstream_encoding"></a></h5>
<div class="api_metadata">
<span>Added in: v16.6.0</span>
</div>
<ul>
<li>Type: <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>TextDecoderStream</code> instance.</p>
<h5><code>textDecoderStream.fatal</code><span><a class="mark" href="#all_webstreams_textdecoderstreamfatal" id="all_webstreams_textdecoderstreamfatal">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_textdecoderstream_fatal"></a></h5>
<div class="api_metadata">
<span>Added in: v16.6.0</span>
</div>
<ul>
<li>Type: <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>
<h5><code>textDecoderStream.ignoreBOM</code><span><a class="mark" href="#all_webstreams_textdecoderstreamignorebom" id="all_webstreams_textdecoderstreamignorebom">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_textdecoderstream_ignorebom"></a></h5>
<div class="api_metadata">
<span>Added in: v16.6.0</span>
</div>
<ul>
<li>Type: <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>
<h5><code>textDecoderStream.readable</code><span><a class="mark" href="#all_webstreams_textdecoderstreamreadable" id="all_webstreams_textdecoderstreamreadable">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_textdecoderstream_readable"></a></h5>
<div class="api_metadata">
<span>Added in: v16.6.0</span>
</div>
<ul>
<li>Type: <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a></li>
</ul>
<h5><code>textDecoderStream.writable</code><span><a class="mark" href="#all_webstreams_textdecoderstreamwritable" id="all_webstreams_textdecoderstreamwritable">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_textdecoderstream_writable"></a></h5>
<div class="api_metadata">
<span>Added in: v16.6.0</span>
</div>
<ul>
<li>Type: <a href="#all_webstreams_class-writablestream" class="type">&#x3C;WritableStream></a></li>
</ul>
<h4>Class: <code>CompressionStream</code><span><a class="mark" href="#all_webstreams_class-compressionstream" id="all_webstreams_class-compressionstream">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_class_compressionstream"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>This class is now exposed on the global object.</p></td></tr>
<tr><td>v17.0.0</td>
<td><p><span>Added in: v17.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<h5><code>new CompressionStream(format)</code><span><a class="mark" href="#all_webstreams_new-compressionstreamformat" id="all_webstreams_new-compressionstreamformat">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_new_compressionstream_format"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.12.0</td>
<td><p>format now accepts <code>deflate-raw</code> value.</p></td></tr>
<tr><td>v17.0.0</td>
<td><p><span>Added in: v17.0.0</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> One of <code>'deflate'</code>, <code>'deflate-raw'</code>, or <code>'gzip'</code>.</li>
</ul>
<h5><code>compressionStream.readable</code><span><a class="mark" href="#all_webstreams_compressionstreamreadable" id="all_webstreams_compressionstreamreadable">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_compressionstream_readable"></a></h5>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<ul>
<li>Type: <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a></li>
</ul>
<h5><code>compressionStream.writable</code><span><a class="mark" href="#all_webstreams_compressionstreamwritable" id="all_webstreams_compressionstreamwritable">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_compressionstream_writable"></a></h5>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<ul>
<li>Type: <a href="#all_webstreams_class-writablestream" class="type">&#x3C;WritableStream></a></li>
</ul>
<h4>Class: <code>DecompressionStream</code><span><a class="mark" href="#all_webstreams_class-decompressionstream" id="all_webstreams_class-decompressionstream">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_class_decompressionstream"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>This class is now exposed on the global object.</p></td></tr>
<tr><td>v17.0.0</td>
<td><p><span>Added in: v17.0.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<h5><code>new DecompressionStream(format)</code><span><a class="mark" href="#all_webstreams_new-decompressionstreamformat" id="all_webstreams_new-decompressionstreamformat">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_new_decompressionstream_format"></a></h5>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v20.12.0</td>
<td><p>format now accepts <code>deflate-raw</code> value.</p></td></tr>
<tr><td>v17.0.0</td>
<td><p><span>Added in: v17.0.0</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> One of <code>'deflate'</code>, <code>'deflate-raw'</code>, or <code>'gzip'</code>.</li>
</ul>
<h5><code>decompressionStream.readable</code><span><a class="mark" href="#all_webstreams_decompressionstreamreadable" id="all_webstreams_decompressionstreamreadable">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_decompressionstream_readable"></a></h5>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<ul>
<li>Type: <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a></li>
</ul>
<h5><code>decompressionStream.writable</code><span><a class="mark" href="#all_webstreams_decompressionstreamwritable" id="all_webstreams_decompressionstreamwritable">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_decompressionstream_writable"></a></h5>
<div class="api_metadata">
<span>Added in: v17.0.0</span>
</div>
<ul>
<li>Type: <a href="#all_webstreams_class-writablestream" class="type">&#x3C;WritableStream></a></li>
</ul>
<h4>Utility Consumers<span><a class="mark" href="#all_webstreams_utility-consumers" id="all_webstreams_utility-consumers">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_utility_consumers"></a></h4>
<div class="api_metadata">
<span>Added in: v16.7.0</span>
</div>
<p>The utility consumer functions provide common options for consuming
streams.</p>
<p>They are accessed using:</p>

<pre class="with-14-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> {
  arrayBuffer,
  blob,
  buffer,
  json,
  text,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/consumers'</span>;</code><code class="language-js cjs"><span class="hljs-keyword">const</span> {
  arrayBuffer,
  blob,
  buffer,
  json,
  text,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/consumers'</span>);</code><button class="copy-button">copy</button></pre>
<h5><code>streamConsumers.arrayBuffer(stream)</code><span><a class="mark" href="#all_webstreams_streamconsumersarraybufferstream" id="all_webstreams_streamconsumersarraybufferstream">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_streamconsumers_arraybuffer_stream"></a></h5>
<div class="api_metadata">
<span>Added in: v16.7.0</span>
</div>
<ul>
<li><code>stream</code> <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a> | <a href="#all_stream_class-streamreadable" class="type">&#x3C;stream.Readable></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterator-interface" class="type">&#x3C;AsyncIterator></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> Fulfills with an <code>ArrayBuffer</code> containing the full
contents of the stream.</li>
</ul>

<pre class="with-57-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { arrayBuffer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/consumers'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">TextEncoder</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:util'</span>;

<span class="hljs-keyword">const</span> encoder = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TextEncoder</span>();
<span class="hljs-keyword">const</span> dataArray = encoder.<span class="hljs-title function_">encode</span>(<span class="hljs-string">'hello world from consumers!'</span>);

<span class="hljs-keyword">const</span> readable = <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>(dataArray);
<span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> <span class="hljs-title function_">arrayBuffer</span>(readable);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`from readable: <span class="hljs-subst">${data.byteLength}</span>`</span>);
<span class="hljs-comment">// Prints: from readable: 76</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { arrayBuffer } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/consumers'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Readable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">TextEncoder</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);

<span class="hljs-keyword">const</span> encoder = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TextEncoder</span>();
<span class="hljs-keyword">const</span> dataArray = encoder.<span class="hljs-title function_">encode</span>(<span class="hljs-string">'hello world from consumers!'</span>);
<span class="hljs-keyword">const</span> readable = <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>(dataArray);
<span class="hljs-title function_">arrayBuffer</span>(readable).<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`from readable: <span class="hljs-subst">${data.byteLength}</span>`</span>);
  <span class="hljs-comment">// Prints: from readable: 76</span>
});</code><button class="copy-button">copy</button></pre>
<h5><code>streamConsumers.blob(stream)</code><span><a class="mark" href="#all_webstreams_streamconsumersblobstream" id="all_webstreams_streamconsumersblobstream">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_streamconsumers_blob_stream"></a></h5>
<div class="api_metadata">
<span>Added in: v16.7.0</span>
</div>
<ul>
<li><code>stream</code> <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a> | <a href="#all_stream_class-streamreadable" class="type">&#x3C;stream.Readable></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterator-interface" class="type">&#x3C;AsyncIterator></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> Fulfills with a <a href="#all_buffer_class-blob" class="type">&#x3C;Blob></a> containing the full contents
of the stream.</li>
</ul>

<pre class="with-50-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { blob } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/consumers'</span>;

<span class="hljs-keyword">const</span> dataBlob = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Blob</span>([<span class="hljs-string">'hello world from consumers!'</span>]);

<span class="hljs-keyword">const</span> readable = dataBlob.<span class="hljs-title function_">stream</span>();
<span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> <span class="hljs-title function_">blob</span>(readable);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`from readable: <span class="hljs-subst">${data.size}</span>`</span>);
<span class="hljs-comment">// Prints: from readable: 27</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { blob } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/consumers'</span>);

<span class="hljs-keyword">const</span> dataBlob = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Blob</span>([<span class="hljs-string">'hello world from consumers!'</span>]);

<span class="hljs-keyword">const</span> readable = dataBlob.<span class="hljs-title function_">stream</span>();
<span class="hljs-title function_">blob</span>(readable).<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`from readable: <span class="hljs-subst">${data.size}</span>`</span>);
  <span class="hljs-comment">// Prints: from readable: 27</span>
});</code><button class="copy-button">copy</button></pre>
<h5><code>streamConsumers.buffer(stream)</code><span><a class="mark" href="#all_webstreams_streamconsumersbufferstream" id="all_webstreams_streamconsumersbufferstream">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_streamconsumers_buffer_stream"></a></h5>
<div class="api_metadata">
<span>Added in: v16.7.0</span>
</div>
<ul>
<li><code>stream</code> <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a> | <a href="#all_stream_class-streamreadable" class="type">&#x3C;stream.Readable></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterator-interface" class="type">&#x3C;AsyncIterator></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> Fulfills with a <a href="#all_buffer_class-buffer" class="type">&#x3C;Buffer></a> containing the full
contents of the stream.</li>
</ul>

<pre class="with-52-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { buffer } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/consumers'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">const</span> dataBuffer = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'hello world from consumers!'</span>);

<span class="hljs-keyword">const</span> readable = <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>(dataBuffer);
<span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> <span class="hljs-title function_">buffer</span>(readable);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`from readable: <span class="hljs-subst">${data.length}</span>`</span>);
<span class="hljs-comment">// Prints: from readable: 27</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { buffer } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/consumers'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Readable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">const</span> dataBuffer = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'hello world from consumers!'</span>);

<span class="hljs-keyword">const</span> readable = <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>(dataBuffer);
<span class="hljs-title function_">buffer</span>(readable).<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`from readable: <span class="hljs-subst">${data.length}</span>`</span>);
  <span class="hljs-comment">// Prints: from readable: 27</span>
});</code><button class="copy-button">copy</button></pre>
<h5><code>streamConsumers.json(stream)</code><span><a class="mark" href="#all_webstreams_streamconsumersjsonstream" id="all_webstreams_streamconsumersjsonstream">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_streamconsumers_json_stream"></a></h5>
<div class="api_metadata">
<span>Added in: v16.7.0</span>
</div>
<ul>
<li><code>stream</code> <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a> | <a href="#all_stream_class-streamreadable" class="type">&#x3C;stream.Readable></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterator-interface" class="type">&#x3C;AsyncIterator></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> Fulfills with the contents of the stream parsed as a
UTF-8 encoded string that is then passed through <code>JSON.parse()</code>.</li>
</ul>

<pre class="with-50-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { json } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/consumers'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;

<span class="hljs-keyword">const</span> items = <span class="hljs-title class_">Array</span>.<span class="hljs-title function_">from</span>(
  {
    <span class="hljs-attr">length</span>: <span class="hljs-number">100</span>,
  },
  <span class="hljs-function">() =></span> ({
    <span class="hljs-attr">message</span>: <span class="hljs-string">'hello world from consumers!'</span>,
  }),
);

<span class="hljs-keyword">const</span> readable = <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(items));
<span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> <span class="hljs-title function_">json</span>(readable);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`from readable: <span class="hljs-subst">${data.length}</span>`</span>);
<span class="hljs-comment">// Prints: from readable: 100</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { json } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/consumers'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Readable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);

<span class="hljs-keyword">const</span> items = <span class="hljs-title class_">Array</span>.<span class="hljs-title function_">from</span>(
  {
    <span class="hljs-attr">length</span>: <span class="hljs-number">100</span>,
  },
  <span class="hljs-function">() =></span> ({
    <span class="hljs-attr">message</span>: <span class="hljs-string">'hello world from consumers!'</span>,
  }),
);

<span class="hljs-keyword">const</span> readable = <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>(<span class="hljs-title class_">JSON</span>.<span class="hljs-title function_">stringify</span>(items));
<span class="hljs-title function_">json</span>(readable).<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`from readable: <span class="hljs-subst">${data.length}</span>`</span>);
  <span class="hljs-comment">// Prints: from readable: 100</span>
});</code><button class="copy-button">copy</button></pre>
<h5><code>streamConsumers.text(stream)</code><span><a class="mark" href="#all_webstreams_streamconsumerstextstream" id="all_webstreams_streamconsumerstextstream">#</a></span><a aria-hidden="true" class="legacy" id="webstreams_streamconsumers_text_stream"></a></h5>
<div class="api_metadata">
<span>Added in: v16.7.0</span>
</div>
<ul>
<li><code>stream</code> <a href="#all_webstreams_class-readablestream" class="type">&#x3C;ReadableStream></a> | <a href="#all_stream_class-streamreadable" class="type">&#x3C;stream.Readable></a> | <a href="https://tc39.github.io/ecma262/#sec-asynciterator-interface" class="type">&#x3C;AsyncIterator></a></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" class="type">&#x3C;Promise></a> Fulfills with the contents of the stream parsed as a
UTF-8 encoded string.</li>
</ul>

<pre class="with-50-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> { text } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream/consumers'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Readable</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:stream'</span>;

<span class="hljs-keyword">const</span> readable = <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'Hello world from consumers!'</span>);
<span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> <span class="hljs-title function_">text</span>(readable);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`from readable: <span class="hljs-subst">${data.length}</span>`</span>);
<span class="hljs-comment">// Prints: from readable: 27</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> { text } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream/consumers'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Readable</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);

<span class="hljs-keyword">const</span> readable = <span class="hljs-title class_">Readable</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'Hello world from consumers!'</span>);
<span class="hljs-title function_">text</span>(readable).<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">data</span>) =></span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`from readable: <span class="hljs-subst">${data.length}</span>`</span>);
  <span class="hljs-comment">// Prints: from readable: 27</span>
});</code><button class="copy-button">copy</button></pre></section>
        </section>
<section><h2>Worker threads<span><a class="mark" href="#all_worker_threads_worker-threads" id="all_worker_threads_worker-threads">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_threads"></a></h2>

<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/worker_threads.js">lib/worker_threads.js</a></p>
<p>The <code>node:worker_threads</code> module enables the use of threads that execute
JavaScript in parallel. To access it:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> worker = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);</code> <button class="copy-button">copy</button></pre>
<p>Workers (threads) are useful for performing CPU-intensive JavaScript operations.
They do not help much with I/O-intensive work. The Node.js 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"><span class="hljs-keyword">const</span> {
  <span class="hljs-title class_">Worker</span>, isMainThread, parentPort, workerData,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);

<span class="hljs-keyword">if</span> (isMainThread) {
  <span class="hljs-variable language_">module</span>.<span class="hljs-property">exports</span> = <span class="hljs-keyword">function</span> <span class="hljs-title function_">parseJSAsync</span>(<span class="hljs-params">script</span>) {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =></span> {
      <span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename, {
        <span class="hljs-attr">workerData</span>: script,
      });
      worker.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, resolve);
      worker.<span class="hljs-title function_">on</span>(<span class="hljs-string">'error'</span>, reject);
      worker.<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">(<span class="hljs-params">code</span>) =></span> {
        <span class="hljs-keyword">if</span> (code !== <span class="hljs-number">0</span>)
          <span class="hljs-title function_">reject</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">`Worker stopped with exit code <span class="hljs-subst">${code}</span>`</span>));
      });
    });
  };
} <span class="hljs-keyword">else</span> {
  <span class="hljs-keyword">const</span> { parse } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'some-js-parsing-library'</span>);
  <span class="hljs-keyword">const</span> script = workerData;
  parentPort.<span class="hljs-title function_">postMessage</span>(<span class="hljs-title function_">parse</span>(script));
}</code> <button class="copy-button">copy</button></pre>
<p>The above example spawns a Worker thread for each <code>parseJSAsync()</code> call. In
practice, use a pool of Workers 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="#all_async_hooks_class-asyncresource"><code>AsyncResource</code></a> API to inform
diagnostic tools (e.g. to provide asynchronous stack traces) about the
correlation between tasks and their outcomes. See
<a href="#all_async_context_using-asyncresource-for-a-worker-thread-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="#all_worker_threads_new-workerfilename-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>
<section><h3><code>worker.getEnvironmentData(key)</code><span><a class="mark" href="#all_worker_threads_workergetenvironmentdatakey" id="all_worker_threads_workergetenvironmentdatakey">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_getenvironmentdata_key"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.5.0, v16.15.0</td>
<td><p>No longer experimental.</p></td></tr>
<tr><td>v15.12.0, v14.18.0</td>
<td><p><span>Added in: v15.12.0, v14.18.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> Any arbitrary, cloneable JavaScript value that can be used as a
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map" class="type">&#x3C;Map></a> key.</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>Within a worker thread, <code>worker.getEnvironmentData()</code> returns a clone
of data passed to the spawning thread's <code>worker.setEnvironmentData()</code>.
Every new <code>Worker</code> receives its own copy of the environment data
automatically.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> {
  <span class="hljs-title class_">Worker</span>,
  isMainThread,
  setEnvironmentData,
  getEnvironmentData,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);

<span class="hljs-keyword">if</span> (isMainThread) {
  <span class="hljs-title function_">setEnvironmentData</span>(<span class="hljs-string">'Hello'</span>, <span class="hljs-string">'World!'</span>);
  <span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">getEnvironmentData</span>(<span class="hljs-string">'Hello'</span>));  <span class="hljs-comment">// Prints 'World!'.</span>
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>worker.isMainThread</code><span><a class="mark" href="#all_worker_threads_workerismainthread" id="all_worker_threads_workerismainthread">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_ismainthread"></a></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#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="#all_worker_threads_class-worker"><code>Worker</code></a> thread.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Worker</span>, isMainThread } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);

<span class="hljs-keyword">if</span> (isMainThread) {
  <span class="hljs-comment">// This re-loads the current file inside a Worker instance.</span>
  <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Inside Worker!'</span>);
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(isMainThread);  <span class="hljs-comment">// Prints 'false'.</span>
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>worker.markAsUntransferable(object)</code><span><a class="mark" href="#all_worker_threads_workermarkasuntransferableobject" id="all_worker_threads_workermarkasuntransferableobject">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_markasuntransferable_object"></a></h3>
<div class="api_metadata">
<span>Added in: v14.5.0, v12.19.0</span>
</div>
<p>Mark an object as not transferable. If <code>object</code> occurs in the transfer list of
a <a href="#all_worker_threads_portpostmessagevalue-transferlist"><code>port.postMessage()</code></a> call, it is ignored.</p>
<p>In particular, this makes sense for objects that can be cloned, rather than
transferred, and which are used by other objects on the sending side.
For example, Node.js marks the <code>ArrayBuffer</code>s it uses for its
<a href="#all_buffer_static-method-bufferallocunsafesize"><code>Buffer</code> pool</a> with this.</p>
<p>This operation cannot be undone.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MessageChannel</span>, markAsUntransferable } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);

<span class="hljs-keyword">const</span> pooledBuffer = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>(<span class="hljs-number">8</span>);
<span class="hljs-keyword">const</span> typedArray1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(pooledBuffer);
<span class="hljs-keyword">const</span> typedArray2 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Float64Array</span>(pooledBuffer);

<span class="hljs-title function_">markAsUntransferable</span>(pooledBuffer);

<span class="hljs-keyword">const</span> { port1 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
port1.<span class="hljs-title function_">postMessage</span>(typedArray1, [ typedArray1.<span class="hljs-property">buffer</span> ]);

<span class="hljs-comment">// The following line prints the contents of typedArray1 -- it still owns</span>
<span class="hljs-comment">// its memory and has been cloned, not transferred. Without</span>
<span class="hljs-comment">// `markAsUntransferable()`, this would print an empty Uint8Array.</span>
<span class="hljs-comment">// typedArray2 is intact as well.</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(typedArray1);
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(typedArray2);</code> <button class="copy-button">copy</button></pre>
<p>There is no equivalent to this API in browsers.</p>
</section><section><h3><code>worker.moveMessagePortToContext(port, contextifiedSandbox)</code><span><a class="mark" href="#all_worker_threads_workermovemessageporttocontextport-contextifiedsandbox" id="all_worker_threads_workermovemessageporttocontextport-contextifiedsandbox">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_movemessageporttocontext_port_contextifiedsandbox"></a></h3>
<div class="api_metadata">
<span>Added in: v11.13.0</span>
</div>
<ul>
<li>
<p><code>port</code> <a href="#all_worker_threads_class-messageport" class="type">&#x3C;MessagePort></a> The message port to transfer.</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="#all_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="#all_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 is rendered unusable, and the returned <code>MessagePort</code> instance
takes its place.</p>
<p>The returned <code>MessagePort</code> is an object in the target context and
inherits 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 are also created in the target context
and inherit from its global <code>Object</code> class.</p>
<p>However, the created <code>MessagePort</code> no longer inherits from
<a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget"><code>EventTarget</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>
</section><section><h3><code>worker.parentPort</code><span><a class="mark" href="#all_worker_threads_workerparentport" id="all_worker_threads_workerparentport">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_parentport"></a></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="#all_worker_threads_class-messageport" class="type">&#x3C;MessagePort></a></li>
</ul>
<p>If this thread is a <a href="#all_worker_threads_class-worker"><code>Worker</code></a>, this is a <a href="#all_worker_threads_class-messageport"><code>MessagePort</code></a>
allowing communication with the parent thread. Messages sent using
<code>parentPort.postMessage()</code> are available in the parent thread
using <code>worker.on('message')</code>, and messages sent from the parent thread
using <code>worker.postMessage()</code> are available in this thread using
<code>parentPort.on('message')</code>.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Worker</span>, isMainThread, parentPort } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);

<span class="hljs-keyword">if</span> (isMainThread) {
  <span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename);
  worker.<span class="hljs-title function_">once</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(message);  <span class="hljs-comment">// Prints 'Hello, world!'.</span>
  });
  worker.<span class="hljs-title function_">postMessage</span>(<span class="hljs-string">'Hello, world!'</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-comment">// When a message from the parent thread is received, send it back:</span>
  parentPort.<span class="hljs-title function_">once</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> {
    parentPort.<span class="hljs-title function_">postMessage</span>(message);
  });
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>worker.receiveMessageOnPort(port)</code><span><a class="mark" href="#all_worker_threads_workerreceivemessageonportport" id="all_worker_threads_workerreceivemessageonportport">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_receivemessageonport_port"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.12.0</td>
<td><p>The port argument can also refer to a <code>BroadcastChannel</code> now.</p></td></tr>
<tr><td>v12.3.0</td>
<td><p><span>Added in: v12.3.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li>
<p><code>port</code> <a href="#all_worker_threads_class-messageport" class="type">&#x3C;MessagePort></a> | <a href="#all_worker_threads_class-broadcastchannel-extends-eventtarget" class="type">&#x3C;BroadcastChannel></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"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MessageChannel</span>, receiveMessageOnPort } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
port1.<span class="hljs-title function_">postMessage</span>({ <span class="hljs-attr">hello</span>: <span class="hljs-string">'world'</span> });

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">receiveMessageOnPort</span>(port2));
<span class="hljs-comment">// Prints: { message: { hello: 'world' } }</span>
<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-title function_">receiveMessageOnPort</span>(port2));
<span class="hljs-comment">// Prints: undefined</span></code> <button class="copy-button">copy</button></pre>
<p>When this function is used, no <code>'message'</code> event is emitted and the
<code>onmessage</code> listener is not invoked.</p>
</section><section><h3><code>worker.resourceLimits</code><span><a class="mark" href="#all_worker_threads_workerresourcelimits" id="all_worker_threads_workerresourcelimits">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_resourcelimits"></a></h3>
<div class="api_metadata">
<span>Added in: v13.2.0, 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>
<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>
<li><code>stackSizeMb</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="#all_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>
</section><section><h3><code>worker.SHARE_ENV</code><span><a class="mark" href="#all_worker_threads_workershare_env" id="all_worker_threads_workershare_env">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_share_env"></a></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#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="#all_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"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Worker</span>, <span class="hljs-variable constant_">SHARE_ENV</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
<span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(<span class="hljs-string">'process.env.SET_IN_WORKER = "foo"'</span>, { <span class="hljs-attr">eval</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">env</span>: <span class="hljs-variable constant_">SHARE_ENV</span> })
  .<span class="hljs-title function_">on</span>(<span class="hljs-string">'exit'</span>, <span class="hljs-function">() =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(process.<span class="hljs-property">env</span>.<span class="hljs-property">SET_IN_WORKER</span>);  <span class="hljs-comment">// Prints 'foo'.</span>
  });</code> <button class="copy-button">copy</button></pre>
</section><section><h3><code>worker.setEnvironmentData(key[, value])</code><span><a class="mark" href="#all_worker_threads_workersetenvironmentdatakey-value" id="all_worker_threads_workersetenvironmentdatakey-value">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_setenvironmentdata_key_value"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v17.5.0, v16.15.0</td>
<td><p>No longer experimental.</p></td></tr>
<tr><td>v15.12.0, v14.18.0</td>
<td><p><span>Added in: v15.12.0, v14.18.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<ul>
<li><code>key</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> Any arbitrary, cloneable JavaScript value that can be used as a
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map" class="type">&#x3C;Map></a> key.</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> Any arbitrary, cloneable JavaScript value that will be cloned
and passed automatically to all new <code>Worker</code> instances. If <code>value</code> is passed
as <code>undefined</code>, any previously set value for the <code>key</code> will be deleted.</li>
</ul>
<p>The <code>worker.setEnvironmentData()</code> API sets the content of
<code>worker.getEnvironmentData()</code> in the current thread and all new <code>Worker</code>
instances spawned from the current context.</p>
</section><section><h3><code>worker.threadId</code><span><a class="mark" href="#all_worker_threads_workerthreadid" id="all_worker_threads_workerthreadid">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_threadid"></a></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 current thread. On the corresponding worker object
(if there is any), it is available as <a href="#all_worker_threads_workerthreadid_1"><code>worker.threadId</code></a>.
This value is unique for each <a href="#all_worker_threads_class-worker"><code>Worker</code></a> instance inside a single process.</p>
</section><section><h3><code>worker.workerData</code><span><a class="mark" href="#all_worker_threads_workerworkerdata" id="all_worker_threads_workerworkerdata">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_workerdata"></a></h3>
<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="#all_worker_threads_portpostmessagevalue-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"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Worker</span>, isMainThread, workerData } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);

<span class="hljs-keyword">if</span> (isMainThread) {
  <span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename, { <span class="hljs-attr">workerData</span>: <span class="hljs-string">'Hello, world!'</span> });
} <span class="hljs-keyword">else</span> {
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(workerData);  <span class="hljs-comment">// Prints 'Hello, world!'.</span>
}</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>BroadcastChannel extends EventTarget</code><span><a class="mark" href="#all_worker_threads_class-broadcastchannel-extends-eventtarget" id="all_worker_threads_class-broadcastchannel-extends-eventtarget">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_class_broadcastchannel_extends_eventtarget"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v18.0.0</td>
<td><p>No longer experimental.</p></td></tr>
<tr><td>v15.4.0</td>
<td><p><span>Added in: v15.4.0</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Instances of <code>BroadcastChannel</code> allow asynchronous one-to-many communication
with all other <code>BroadcastChannel</code> instances bound to the same channel name.</p>
<pre><code class="language-js"><span class="hljs-meta">'use strict'</span>;

<span class="hljs-keyword">const</span> {
  isMainThread,
  <span class="hljs-title class_">BroadcastChannel</span>,
  <span class="hljs-title class_">Worker</span>,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);

<span class="hljs-keyword">const</span> bc = <span class="hljs-keyword">new</span> <span class="hljs-title class_">BroadcastChannel</span>(<span class="hljs-string">'hello'</span>);

<span class="hljs-keyword">if</span> (isMainThread) {
  <span class="hljs-keyword">let</span> c = <span class="hljs-number">0</span>;
  bc.<span class="hljs-property">onmessage</span> = <span class="hljs-function">(<span class="hljs-params">event</span>) =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(event.<span class="hljs-property">data</span>);
    <span class="hljs-keyword">if</span> (++c === <span class="hljs-number">10</span>) bc.<span class="hljs-title function_">close</span>();
  };
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> n = <span class="hljs-number">0</span>; n &#x3C; <span class="hljs-number">10</span>; n++)
    <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename);
} <span class="hljs-keyword">else</span> {
  bc.<span class="hljs-title function_">postMessage</span>(<span class="hljs-string">'hello from every worker'</span>);
  bc.<span class="hljs-title function_">close</span>();
}</code> <button class="copy-button">copy</button></pre>
<h4><code>new BroadcastChannel(name)</code><span><a class="mark" href="#all_worker_threads_new-broadcastchannelname" id="all_worker_threads_new-broadcastchannelname">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_new_broadcastchannel_name"></a></h4>
<div class="api_metadata">
<span>Added in: v15.4.0</span>
</div>
<ul>
<li><code>name</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Data_types" class="type">&#x3C;any></a> The name of the channel to connect to. Any JavaScript value
that can be converted to a string using <code>`${name}`</code> is permitted.</li>
</ul>
<h4><code>broadcastChannel.close()</code><span><a class="mark" href="#all_worker_threads_broadcastchannelclose" id="all_worker_threads_broadcastchannelclose">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_broadcastchannel_close"></a></h4>
<div class="api_metadata">
<span>Added in: v15.4.0</span>
</div>
<p>Closes the <code>BroadcastChannel</code> connection.</p>
<h4><code>broadcastChannel.onmessage</code><span><a class="mark" href="#all_worker_threads_broadcastchannelonmessage" id="all_worker_threads_broadcastchannelonmessage">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_broadcastchannel_onmessage"></a></h4>
<div class="api_metadata">
<span>Added in: v15.4.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Invoked with a single <code>MessageEvent</code> argument
when a message is received.</li>
</ul>
<h4><code>broadcastChannel.onmessageerror</code><span><a class="mark" href="#all_worker_threads_broadcastchannelonmessageerror" id="all_worker_threads_broadcastchannelonmessageerror">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_broadcastchannel_onmessageerror"></a></h4>
<div class="api_metadata">
<span>Added in: v15.4.0</span>
</div>
<ul>
<li>Type: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type">&#x3C;Function></a> Invoked with a received message cannot be
deserialized.</li>
</ul>
<h4><code>broadcastChannel.postMessage(message)</code><span><a class="mark" href="#all_worker_threads_broadcastchannelpostmessagemessage" id="all_worker_threads_broadcastchannelpostmessagemessage">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_broadcastchannel_postmessage_message"></a></h4>
<div class="api_metadata">
<span>Added in: v15.4.0</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> Any cloneable JavaScript value.</li>
</ul>
<h4><code>broadcastChannel.ref()</code><span><a class="mark" href="#all_worker_threads_broadcastchannelref" id="all_worker_threads_broadcastchannelref">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_broadcastchannel_ref"></a></h4>
<div class="api_metadata">
<span>Added in: v15.4.0</span>
</div>
<p>Opposite of <code>unref()</code>. Calling <code>ref()</code> on a previously <code>unref()</code>ed
BroadcastChannel does <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
has no effect.</p>
<h4><code>broadcastChannel.unref()</code><span><a class="mark" href="#all_worker_threads_broadcastchannelunref" id="all_worker_threads_broadcastchannelunref">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_broadcastchannel_unref"></a></h4>
<div class="api_metadata">
<span>Added in: v15.4.0</span>
</div>
<p>Calling <code>unref()</code> on a BroadcastChannel allows the thread to exit if this
is the only active handle in the event system. If the BroadcastChannel is
already <code>unref()</code>ed calling <code>unref()</code> again has no effect.</p>
</section><section><h3>Class: <code>MessageChannel</code><span><a class="mark" href="#all_worker_threads_class-messagechannel" id="all_worker_threads_class-messagechannel">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_class_messagechannel"></a></h3>
<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="#all_worker_threads_class-messageport"><code>MessagePort</code></a> instances.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MessageChannel</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);

<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
port1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'received'</span>, message));
port2.<span class="hljs-title function_">postMessage</span>({ <span class="hljs-attr">foo</span>: <span class="hljs-string">'bar'</span> });
<span class="hljs-comment">// Prints: received { foo: 'bar' } from the `port1.on('message')` listener</span></code> <button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>MessagePort</code><span><a class="mark" href="#all_worker_threads_class-messageport" id="all_worker_threads_class-messageport">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_class_messageport"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.7.0</td>
<td><p>This class now inherits from <code>EventTarget</code> rather than from <code>EventEmitter</code>.</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>Extends: <a href="#all_events_class-eventtarget" class="type">&#x3C;EventTarget></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="#all_worker_threads_class-worker"><code>Worker</code></a>s.</p>
<p>This implementation matches <a href="https://developer.mozilla.org/en-US/docs/Web/API/MessagePort">browser <code>MessagePort</code></a>s.</p>
<h4>Event: <code>'close'</code><span><a class="mark" href="#all_worker_threads_event-close" id="all_worker_threads_event-close">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_event_close"></a></h4>
<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"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MessageChannel</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();

<span class="hljs-comment">// Prints:</span>
<span class="hljs-comment">//   foobar</span>
<span class="hljs-comment">//   closed!</span>
port2.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(message));
port2.<span class="hljs-title function_">on</span>(<span class="hljs-string">'close'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'closed!'</span>));

port1.<span class="hljs-title function_">postMessage</span>(<span class="hljs-string">'foobar'</span>);
port1.<span class="hljs-title function_">close</span>();</code> <button class="copy-button">copy</button></pre>
<h4>Event: <code>'message'</code><span><a class="mark" href="#all_worker_threads_event-message" id="all_worker_threads_event-message">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_event_message"></a></h4>
<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="#all_worker_threads_portpostmessagevalue-transferlist"><code>port.postMessage()</code></a>.</p>
<p>Listeners on this event receive a clone of the <code>value</code> parameter as passed
to <code>postMessage()</code> and no further arguments.</p>
<h4>Event: <code>'messageerror'</code><span><a class="mark" href="#all_worker_threads_event-messageerror" id="all_worker_threads_event-messageerror">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_event_messageerror"></a></h4>
<div class="api_metadata">
<span>Added in: v14.5.0, v12.19.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 Error object</li>
</ul>
<p>The <code>'messageerror'</code> event is emitted when deserializing a message failed.</p>
<p>Currently, this event is emitted when there is an error occurring while
instantiating the posted JS object on the receiving end. Such situations
are rare, but can happen, for instance, when certain Node.js API objects
are received in a <code>vm.Context</code> (where Node.js APIs are currently
unavailable).</p>
<h4><code>port.close()</code><span><a class="mark" href="#all_worker_threads_portclose" id="all_worker_threads_portclose">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_port_close"></a></h4>
<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="#all_worker_threads_event-close"><code>'close'</code> event</a> is emitted on both <code>MessagePort</code> instances that
are part of the channel.</p>
<h4><code>port.postMessage(value[, transferList])</code><span><a class="mark" href="#all_worker_threads_portpostmessagevalue-transferlist" id="all_worker_threads_portpostmessagevalue-transferlist">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_port_postmessage_value_transferlist"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v15.6.0</td>
<td><p>Added <code>X509Certificate</code> to the list of cloneable types.</p></td></tr>
<tr><td>v15.0.0</td>
<td><p>Added <code>CryptoKey</code> to the list of cloneable types.</p></td></tr>
<tr><td>v15.14.0, v14.18.0</td>
<td><p>Add 'BlockList' to the list of cloneable types.</p></td></tr>
<tr><td>v15.9.0, v14.18.0</td>
<td><p>Add 'Histogram' types to the list of cloneable types.</p></td></tr>
<tr><td>v14.5.0, v12.19.0</td>
<td><p>Added <code>KeyObject</code> to the list of cloneable types.</p></td></tr>
<tr><td>v14.5.0, v12.19.0</td>
<td><p>Added <code>FileHandle</code> to the list of transferable types.</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>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> is 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:
<ul>
<li><a href="#all_webcrypto_class-cryptokey" class="type">&#x3C;CryptoKey></a>s,</li>
<li><a href="#all_fs_class-filehandle" class="type">&#x3C;FileHandle></a>s,</li>
<li><a href="#all_perf_hooks_class-histogram" class="type">&#x3C;Histogram></a>s,</li>
<li><a href="#all_crypto_class-keyobject" class="type">&#x3C;KeyObject></a>s,</li>
<li><a href="#all_worker_threads_class-messageport" class="type">&#x3C;MessagePort></a>s,</li>
<li><a href="#all_net_class-netblocklist" class="type">&#x3C;net.BlockList></a>s,</li>
<li><a href="#all_net_class-netsocketaddress" class="type">&#x3C;net.SocketAddress></a>es,</li>
<li><a href="#all_crypto_class-x509certificate" class="type">&#x3C;X509Certificate></a>s.</li>
</ul>
</li>
</ul>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MessageChannel</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();

port1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(message));

<span class="hljs-keyword">const</span> circularData = {};
circularData.<span class="hljs-property">foo</span> = circularData;
<span class="hljs-comment">// Prints: { foo: [Circular] }</span>
port2.<span class="hljs-title function_">postMessage</span>(circularData);</code> <button class="copy-button">copy</button></pre>
<p><code>transferList</code> may be a list of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a>, <a href="#all_worker_threads_class-messageport"><code>MessagePort</code></a>, and
<a href="#all_fs_class-filehandle"><code>FileHandle</code></a> objects.
After transferring, they are not 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 are 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"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">MessageChannel</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();

port1.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(message));

<span class="hljs-keyword">const</span> uint8Array = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>([ <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span> ]);
<span class="hljs-comment">// This posts a copy of `uint8Array`:</span>
port2.<span class="hljs-title function_">postMessage</span>(uint8Array);
<span class="hljs-comment">// This does not copy data, but renders `uint8Array` unusable:</span>
port2.<span class="hljs-title function_">postMessage</span>(uint8Array, [ uint8Array.<span class="hljs-property">buffer</span> ]);

<span class="hljs-comment">// The memory for the `sharedUint8Array` is accessible from both the</span>
<span class="hljs-comment">// original and the copy received by `.on('message')`:</span>
<span class="hljs-keyword">const</span> sharedUint8Array = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">SharedArrayBuffer</span>(<span class="hljs-number">4</span>));
port2.<span class="hljs-title function_">postMessage</span>(sharedUint8Array);

<span class="hljs-comment">// This transfers a freshly created message port to the receiver.</span>
<span class="hljs-comment">// This can be used, for example, to create communication channels between</span>
<span class="hljs-comment">// multiple `Worker` threads that are children of the same parent thread.</span>
<span class="hljs-keyword">const</span> otherChannel = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
port2.<span class="hljs-title function_">postMessage</span>({ <span class="hljs-attr">port</span>: otherChannel.<span class="hljs-property">port1</span> }, [ otherChannel.<span class="hljs-property">port1</span> ]);</code> <button class="copy-button">copy</button></pre>
<p>The message object is 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="#all_v8_serialization-api">serialization API of the <code>node:v8</code> module</a>.</p>
<h5>Considerations when transferring TypedArrays and Buffers<span><a class="mark" href="#all_worker_threads_considerations-when-transferring-typedarrays-and-buffers" id="all_worker_threads_considerations-when-transferring-typedarrays-and-buffers">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_considerations_when_transferring_typedarrays_and_buffers"></a></h5>
<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 causes 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"><span class="hljs-keyword">const</span> ab = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayBuffer</span>(<span class="hljs-number">10</span>);

<span class="hljs-keyword">const</span> u1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint8Array</span>(ab);
<span class="hljs-keyword">const</span> u2 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Uint16Array</span>(ab);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(u2.<span class="hljs-property">length</span>);  <span class="hljs-comment">// prints 5</span>

port.<span class="hljs-title function_">postMessage</span>(u1, [u1.<span class="hljs-property">buffer</span>]);

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(u2.<span class="hljs-property">length</span>);  <span class="hljs-comment">// prints 0</span></code> <button class="copy-button">copy</button></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>An <code>ArrayBuffer</code> can be marked with <a href="#all_worker_threads_workermarkasuntransferableobject"><code>markAsUntransferable()</code></a> to indicate
that it should always be cloned and never transferred.</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.allocUnsafe()</code>),
transferring them is not possible and they are always 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="#all_buffer_static-method-bufferallocunsafesize"><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 renders all other existing views of
those <code>ArrayBuffer</code>s unusable.</p>
<h5>Considerations when cloning objects with prototypes, classes, and accessors<span><a class="mark" href="#all_worker_threads_considerations-when-cloning-objects-with-prototypes-classes-and-accessors" id="all_worker_threads_considerations-when-cloning-objects-with-prototypes-classes-and-accessors">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_considerations_when_cloning_objects_with_prototypes_classes_and_accessors"></a></h5>
<p>Because object cloning uses the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm">HTML structured clone algorithm</a>,
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, and instances of JavaScript
classes will be cloned as plain JavaScript objects.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> b = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">'b'</span>);

<span class="hljs-keyword">class</span> <span class="hljs-title class_">Foo</span> {
  #a = <span class="hljs-number">1</span>;
  <span class="hljs-title function_">constructor</span>(<span class="hljs-params"></span>) {
    <span class="hljs-variable language_">this</span>[b] = <span class="hljs-number">2</span>;
    <span class="hljs-variable language_">this</span>.<span class="hljs-property">c</span> = <span class="hljs-number">3</span>;
  }

  <span class="hljs-keyword">get</span> <span class="hljs-title function_">d</span>() { <span class="hljs-keyword">return</span> <span class="hljs-number">4</span>; }
}

<span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();

port1.<span class="hljs-property">onmessage</span> = <span class="hljs-function">(<span class="hljs-params">{ data }</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data);

port2.<span class="hljs-title function_">postMessage</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Foo</span>());

<span class="hljs-comment">// Prints: { c: 3 }</span></code> <button class="copy-button">copy</button></pre>
<p>This limitation extends to many built-in objects, such as the global <code>URL</code>
object:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { port1, port2 } = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();

port1.<span class="hljs-property">onmessage</span> = <span class="hljs-function">(<span class="hljs-params">{ data }</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(data);

port2.<span class="hljs-title function_">postMessage</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-string">'https://example.org'</span>));

<span class="hljs-comment">// Prints: { }</span></code> <button class="copy-button">copy</button></pre>
<h4><code>port.hasRef()</code><span><a class="mark" href="#all_worker_threads_porthasref" id="all_worker_threads_porthasref">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_port_hasref"></a></h4>
<div class="api_metadata">
<span>Added in: v18.1.0, v16.17.0</span>
</div>
<p></p><div class="api_stability api_stability_1"><a href="#all_documentation_stability-index">Stability: 1</a> - Experimental</div><p></p>
<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>MessagePort</code> object will keep the Node.js event loop active.</p>
<h4><code>port.ref()</code><span><a class="mark" href="#all_worker_threads_portref" id="all_worker_threads_portref">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_port_ref"></a></h4>
<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 does
<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 has no effect.</p>
<p>If listeners are attached or removed using <code>.on('message')</code>, the port
is <code>ref()</code>ed and <code>unref()</code>ed automatically depending on whether
listeners for the event exist.</p>
<h4><code>port.start()</code><span><a class="mark" href="#all_worker_threads_portstart" id="all_worker_threads_portstart">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_port_start"></a></h4>
<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 is 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
automatically calls <code>.start()</code>, but unsetting it lets messages queue up
until a new handler is set or the port is discarded.</p>
<h4><code>port.unref()</code><span><a class="mark" href="#all_worker_threads_portunref" id="all_worker_threads_portunref">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_port_unref"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<p>Calling <code>unref()</code> on a port allows 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 has no effect.</p>
<p>If listeners are attached or removed using <code>.on('message')</code>, the port is
<code>ref()</code>ed and <code>unref()</code>ed automatically depending on whether
listeners for the event exist.</p>
</section><section><h3>Class: <code>Worker</code><span><a class="mark" href="#all_worker_threads_class-worker" id="all_worker_threads_class-worker">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_class_worker"></a></h3>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<ul>
<li>Extends: <a href="#all_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="#all_process_processstdin"><code>process.stdin</code></a>, <a href="#all_process_processstdout"><code>process.stdout</code></a>, and <a href="#all_process_processstderr"><code>process.stderr</code></a>
streams may be redirected by the parent thread.</li>
<li>The <a href="#all_worker_threads_workerismainthread"><code>require('node:worker_threads').isMainThread</code></a> property is set to <code>false</code>.</li>
<li>The <a href="#all_worker_threads_workerparentport"><code>require('node:worker_threads').parentPort</code></a> message port is available.</li>
<li><a href="#all_process_processexitcode"><code>process.exit()</code></a> does not stop the whole program, just the single thread,
and <a href="#all_process_processabort"><code>process.abort()</code></a> is not available.</li>
<li><a href="#all_process_processchdirdirectory"><code>process.chdir()</code></a> and <code>process</code> methods that set group or user ids
are not available.</li>
<li><a href="#all_process_processenv"><code>process.env</code></a> is a copy of the parent thread's environment variables,
unless otherwise specified. Changes to one copy are not visible in other
threads, and are not visible to native add-ons (unless
<a href="#all_worker_threads_workershare_env"><code>worker.SHARE_ENV</code></a> is passed as the <code>env</code> option to the
<a href="#all_worker_threads_class-worker"><code>Worker</code></a> constructor). On Windows, unlike the main thread, a copy of the
environment variables operates in a case-sensitive manner.</li>
<li><a href="#all_process_processtitle"><code>process.title</code></a> cannot be modified.</li>
<li>Signals are not delivered through <a href="#all_process_signal-events"><code>process.on('...')</code></a>.</li>
<li>Execution may stop at any point as a result of <a href="#all_worker_threads_workerterminate"><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="#all_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>node: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="#all_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="#all_worker_threads_workerpostmessagevalue-transferlist"><code>worker.postMessage()</code></a> and the <a href="#all_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="#all_worker_threads_portpostmessagevalue-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"><span class="hljs-keyword">const</span> assert = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:assert'</span>);
<span class="hljs-keyword">const</span> {
  <span class="hljs-title class_">Worker</span>, <span class="hljs-title class_">MessageChannel</span>, <span class="hljs-title class_">MessagePort</span>, isMainThread, parentPort,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);
<span class="hljs-keyword">if</span> (isMainThread) {
  <span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename);
  <span class="hljs-keyword">const</span> subChannel = <span class="hljs-keyword">new</span> <span class="hljs-title class_">MessageChannel</span>();
  worker.<span class="hljs-title function_">postMessage</span>({ <span class="hljs-attr">hereIsYourPort</span>: subChannel.<span class="hljs-property">port1</span> }, [subChannel.<span class="hljs-property">port1</span>]);
  subChannel.<span class="hljs-property">port2</span>.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">value</span>) =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'received:'</span>, value);
  });
} <span class="hljs-keyword">else</span> {
  parentPort.<span class="hljs-title function_">once</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">value</span>) =></span> {
    <span class="hljs-title function_">assert</span>(value.<span class="hljs-property">hereIsYourPort</span> <span class="hljs-keyword">instanceof</span> <span class="hljs-title class_">MessagePort</span>);
    value.<span class="hljs-property">hereIsYourPort</span>.<span class="hljs-title function_">postMessage</span>(<span class="hljs-string">'the worker is sending this'</span>);
    value.<span class="hljs-property">hereIsYourPort</span>.<span class="hljs-title function_">close</span>();
  });
}</code> <button class="copy-button">copy</button></pre>
<h4><code>new Worker(filename[, options])</code><span><a class="mark" href="#all_worker_threads_new-workerfilename-options" id="all_worker_threads_new-workerfilename-options">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_new_worker_filename_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.8.0</td>
<td><p>Added support for a <code>name</code> option, which allows adding a name to worker title for debugging.</p></td></tr>
<tr><td>v14.9.0</td>
<td><p>The <code>filename</code> parameter can be a WHATWG <code>URL</code> object using <code>data:</code> protocol.</p></td></tr>
<tr><td>v14.9.0</td>
<td><p>The <code>trackUnmanagedFds</code> option was set to <code>true</code> by default.</p></td></tr>
<tr><td>v14.6.0, v12.19.0</td>
<td><p>The <code>trackUnmanagedFds</code> option was introduced.</p></td></tr>
<tr><td>v13.13.0, v12.17.0</td>
<td><p>The <code>transferList</code> option was introduced.</p></td></tr>
<tr><td>v13.12.0, 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>v13.4.0, v12.16.0</td>
<td><p>The <code>argv</code> option was introduced.</p></td></tr>
<tr><td>v13.2.0, v12.16.0</td>
<td><p>The <code>resourceLimits</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="#all_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> or <code>data:</code> protocol.
When using a <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs"><code>data:</code> URL</a>, the data is interpreted based on MIME type using
the <a href="#all_esm_data-imports">ECMAScript module loader</a>.
If <code>options.eval</code> is <code>true</code>, this is a string containing JavaScript code
rather than a path.</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>
<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 are 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="#all_worker_threads_workershare_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 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 is provided
as <a href="#all_process_processexecargv"><code>process.execArgv</code></a> inside the worker. By default, options are
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>
provides a writable stream whose contents 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> is
not automatically 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> is
not automatically 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 is cloned and made
available as <a href="#all_worker_threads_workerworkerdata"><code>require('node:worker_threads').workerData</code></a>. The cloning
occurs 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
is thrown if the object cannot be cloned (e.g. because it contains
<code>function</code>s).</li>
<li><code>trackUnmanagedFds</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 the Worker
tracks raw file descriptors managed through <a href="#all_fs_fsopenpath-flags-mode-callback"><code>fs.open()</code></a> and
<a href="#all_fs_fsclosefd-callback"><code>fs.close()</code></a>, and closes them when the Worker exits, similar to other
resources like network sockets or file descriptors managed through
the <a href="#all_fs_class-filehandle"><code>FileHandle</code></a> API. This option is automatically inherited by all
nested <code>Worker</code>s. <strong>Default:</strong> <code>true</code>.</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="#all_errors_err_missing_message_port_in_transfer_list"><code>ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST</code></a> is thrown.
See <a href="#all_worker_threads_portpostmessagevalue-transferlist"><code>port.postMessage()</code></a> for more information.</li>
<li><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 leads 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.
<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. If the command-line argument <a href="#all_cli_--max-old-space-sizesize-in-mib"><code>--max-old-space-size</code></a> is set, it
overrides this setting.</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. If the command-line argument
<a href="#all_cli_--max-semi-space-sizesize-in-mib"><code>--max-semi-space-size</code></a> is set, it overrides this setting.</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>
<li><code>stackSizeMb</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a> The default maximum stack size for the thread.
Small values may lead to unusable Worker instances. <strong>Default:</strong> <code>4</code>.</li>
</ul>
</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> An optional <code>name</code> to be appended to the worker title
for debugging/identification purposes, making the final title as
<code>[worker ${id}] ${name}</code>. <strong>Default:</strong> <code>''</code>.</li>
</ul>
</li>
</ul>
<h4>Event: <code>'error'</code><span><a class="mark" href="#all_worker_threads_event-error" id="all_worker_threads_event-error">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_event_error"></a></h4>
<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 is terminated.</p>
<h4>Event: <code>'exit'</code><span><a class="mark" href="#all_worker_threads_event-exit" id="all_worker_threads_event-exit">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_event_exit"></a></h4>
<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="#all_process_processexitcode"><code>process.exit()</code></a>, the <code>exitCode</code> parameter is the
passed exit code. If the worker was terminated, the <code>exitCode</code> parameter is
<code>1</code>.</p>
<p>This is the final event emitted by any <code>Worker</code> instance.</p>
<h4>Event: <code>'message'</code><span><a class="mark" href="#all_worker_threads_event-message_1" id="all_worker_threads_event-message_1">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_event_message_1"></a></h4>
<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="#all_worker_threads_workerpostmessagevalue-transferlist"><code>require('node:worker_threads').parentPort.postMessage()</code></a>.
See the <a href="#all_worker_threads_event-message"><code>port.on('message')</code></a> event for more details.</p>
<p>All messages sent from the worker thread are emitted before the
<a href="#all_worker_threads_event-exit"><code>'exit'</code> event</a> is emitted on the <code>Worker</code> object.</p>
<h4>Event: <code>'messageerror'</code><span><a class="mark" href="#all_worker_threads_event-messageerror_1" id="all_worker_threads_event-messageerror_1">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_event_messageerror_1"></a></h4>
<div class="api_metadata">
<span>Added in: v14.5.0, v12.19.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 Error object</li>
</ul>
<p>The <code>'messageerror'</code> event is emitted when deserializing a message failed.</p>
<h4>Event: <code>'online'</code><span><a class="mark" href="#all_worker_threads_event-online" id="all_worker_threads_event-online">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_event_online"></a></h4>
<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>
<h4><code>worker.getHeapSnapshot([options])</code><span><a class="mark" href="#all_worker_threads_workergetheapsnapshotoptions" id="all_worker_threads_workergetheapsnapshotoptions">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_getheapsnapshot_options"></a></h4>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v19.1.0</td>
<td><p>Support options to configure the heap snapshot.</p></td></tr>
<tr><td>v13.9.0, v12.17.0</td>
<td><p><span>Added in: v13.9.0, v12.17.0</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>
<ul>
<li><code>exposeInternals</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If true, expose internals in the heap snapshot.
<strong>Default:</strong> <code>false</code>.</li>
<li><code>exposeNumericValues</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type">&#x3C;boolean></a> If true, expose numeric values in
artificial fields. <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> 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="#all_v8_v8getheapsnapshotoptions"><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="#all_worker_threads_event-exit"><code>'exit'</code> event</a> is emitted, the returned <code>Promise</code> is rejected
immediately with an <a href="#all_errors_err_worker_not_running"><code>ERR_WORKER_NOT_RUNNING</code></a> error.</p>
<h4><code>worker.performance</code><span><a class="mark" href="#all_worker_threads_workerperformance" id="all_worker_threads_workerperformance">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_performance"></a></h4>
<div class="api_metadata">
<span>Added in: v15.1.0, v14.17.0, v12.22.0</span>
</div>
<p>An object that can be used to query performance information from a worker
instance. Similar to <a href="#all_perf_hooks_perf_hooksperformance"><code>perf_hooks.performance</code></a>.</p>
<h5><code>performance.eventLoopUtilization([utilization1[, utilization2]])</code><span><a class="mark" href="#all_worker_threads_performanceeventlooputilizationutilization1-utilization2" id="all_worker_threads_performanceeventlooputilizationutilization1-utilization2">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_performance_eventlooputilization_utilization1_utilization2"></a></h5>
<div class="api_metadata">
<span>Added in: v15.1.0, v14.17.0, v12.22.0</span>
</div>
<ul>
<li><code>utilization1</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> The result of a previous call to
<code>eventLoopUtilization()</code>.</li>
<li><code>utilization2</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a> The result of a previous call to
<code>eventLoopUtilization()</code> prior to <code>utilization1</code>.</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type">&#x3C;Object></a>
<ul>
<li><code>idle</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li><code>active</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;number></a></li>
<li><code>utilization</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>The same call as <a href="#all_perf_hooks_performanceeventlooputilizationutilization1-utilization2"><code>perf_hooks</code> <code>eventLoopUtilization()</code></a>, except the values
of the worker instance are returned.</p>
<p>One difference is that, unlike the main thread, bootstrapping within a worker
is done within the event loop. So the event loop utilization is
immediately available once the worker's script begins execution.</p>
<p>An <code>idle</code> time that does not increase does not indicate that the worker is
stuck in bootstrap. The following examples shows how the worker's entire
lifetime never accumulates any <code>idle</code> time, but is still be able to process
messages.</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { <span class="hljs-title class_">Worker</span>, isMainThread, parentPort } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);

<span class="hljs-keyword">if</span> (isMainThread) {
  <span class="hljs-keyword">const</span> worker = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename);
  <span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =></span> {
    worker.<span class="hljs-title function_">postMessage</span>(<span class="hljs-string">'hi'</span>);
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(worker.<span class="hljs-property">performance</span>.<span class="hljs-title function_">eventLoopUtilization</span>());
  }, <span class="hljs-number">100</span>).<span class="hljs-title function_">unref</span>();
  <span class="hljs-keyword">return</span>;
}

parentPort.<span class="hljs-title function_">on</span>(<span class="hljs-string">'message'</span>, <span class="hljs-function">() =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'msg'</span>)).<span class="hljs-title function_">unref</span>();
(<span class="hljs-keyword">function</span> <span class="hljs-title function_">r</span>(<span class="hljs-params">n</span>) {
  <span class="hljs-keyword">if</span> (--n &#x3C; <span class="hljs-number">0</span>) <span class="hljs-keyword">return</span>;
  <span class="hljs-keyword">const</span> t = <span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>();
  <span class="hljs-keyword">while</span> (<span class="hljs-title class_">Date</span>.<span class="hljs-title function_">now</span>() - t &#x3C; <span class="hljs-number">300</span>);
  <span class="hljs-title function_">setImmediate</span>(r, n);
})(<span class="hljs-number">10</span>);</code> <button class="copy-button">copy</button></pre>
<p>The event loop utilization of a worker is available only after the <a href="#all_worker_threads_event-online"><code>'online'</code>
event</a> emitted, and if called before this, or after the <a href="#all_worker_threads_event-exit"><code>'exit'</code>
event</a>, then all properties have the value of <code>0</code>.</p>
<h4><code>worker.postMessage(value[, transferList])</code><span><a class="mark" href="#all_worker_threads_workerpostmessagevalue-transferlist" id="all_worker_threads_workerpostmessagevalue-transferlist">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_postmessage_value_transferlist"></a></h4>
<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 is received via
<a href="#all_worker_threads_event-message"><code>require('node:worker_threads').parentPort.on('message')</code></a>.
See <a href="#all_worker_threads_portpostmessagevalue-transferlist"><code>port.postMessage()</code></a> for more details.</p>
<h4><code>worker.ref()</code><span><a class="mark" href="#all_worker_threads_workerref" id="all_worker_threads_workerref">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_ref"></a></h4>
<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 does
<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 has
no effect.</p>
<h4><code>worker.resourceLimits</code><span><a class="mark" href="#all_worker_threads_workerresourcelimits_1" id="all_worker_threads_workerresourcelimits_1">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_resourcelimits_1"></a></h4>
<div class="api_metadata">
<span>Added in: v13.2.0, 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>
<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>
<li><code>stackSizeMb</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="#all_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>
<h4><code>worker.stderr</code><span><a class="mark" href="#all_worker_threads_workerstderr" id="all_worker_threads_workerstderr">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_stderr"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<ul>
<li><a href="#all_stream_class-streamreadable" class="type">&#x3C;stream.Readable></a></li>
</ul>
<p>This is a readable stream which contains data written to <a href="#all_process_processstderr"><code>process.stderr</code></a>
inside the worker thread. If <code>stderr: true</code> was not passed to the
<a href="#all_worker_threads_class-worker"><code>Worker</code></a> constructor, then data is piped to the parent thread's
<a href="#all_process_processstderr"><code>process.stderr</code></a> stream.</p>
<h4><code>worker.stdin</code><span><a class="mark" href="#all_worker_threads_workerstdin" id="all_worker_threads_workerstdin">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_stdin"></a></h4>
<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="#all_stream_class-streamwritable" class="type">&#x3C;stream.Writable></a></li>
</ul>
<p>If <code>stdin: true</code> was passed to the <a href="#all_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="#all_process_processstdin"><code>process.stdin</code></a>.</p>
<h4><code>worker.stdout</code><span><a class="mark" href="#all_worker_threads_workerstdout" id="all_worker_threads_workerstdout">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_stdout"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<ul>
<li><a href="#all_stream_class-streamreadable" class="type">&#x3C;stream.Readable></a></li>
</ul>
<p>This is a readable stream which contains data written to <a href="#all_process_processstdout"><code>process.stdout</code></a>
inside the worker thread. If <code>stdout: true</code> was not passed to the
<a href="#all_worker_threads_class-worker"><code>Worker</code></a> constructor, then data is piped to the parent thread's
<a href="#all_process_processstdout"><code>process.stdout</code></a> stream.</p>
<h4><code>worker.terminate()</code><span><a class="mark" href="#all_worker_threads_workerterminate" id="all_worker_threads_workerterminate">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_terminate"></a></h4>
<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="#all_worker_threads_event-exit"><code>'exit'</code> event</a> is emitted.</p>
<h4><code>worker.threadId</code><span><a class="mark" href="#all_worker_threads_workerthreadid_1" id="all_worker_threads_workerthreadid_1">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_threadid_1"></a></h4>
<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="#all_worker_threads_workerthreadid"><code>require('node:worker_threads').threadId</code></a>.
This value is unique for each <code>Worker</code> instance inside a single process.</p>
<h4><code>worker.unref()</code><span><a class="mark" href="#all_worker_threads_workerunref" id="all_worker_threads_workerunref">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_worker_unref"></a></h4>
<div class="api_metadata">
<span>Added in: v10.5.0</span>
</div>
<p>Calling <code>unref()</code> on a worker allows 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 has no effect.</p>
</section><section><h3>Notes<span><a class="mark" href="#all_worker_threads_notes" id="all_worker_threads_notes">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_notes"></a></h3>
<h4>Synchronous blocking of stdio<span><a class="mark" href="#all_worker_threads_synchronous-blocking-of-stdio" id="all_worker_threads_synchronous-blocking-of-stdio">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_synchronous_blocking_of_stdio"></a></h4>
<p><code>Worker</code>s utilize message passing via <a href="#all_worker_threads_class-messageport" class="type">&#x3C;MessagePort></a> to implement interactions
with <code>stdio</code>. This means that <code>stdio</code> output originating from a <code>Worker</code> can
get blocked by synchronous code on the receiving end that is blocking the
Node.js event loop.</p>

<pre class="with-13-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> {
  <span class="hljs-title class_">Worker</span>,
  isMainThread,
} <span class="hljs-keyword">from</span> <span class="hljs-string">'node:worker_threads'</span>;

<span class="hljs-keyword">if</span> (isMainThread) {
  <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(<span class="hljs-keyword">new</span> <span class="hljs-title function_">URL</span>(<span class="hljs-keyword">import</span>.<span class="hljs-property">meta</span>.<span class="hljs-property">url</span>));
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> n = <span class="hljs-number">0</span>; n &#x3C; <span class="hljs-number">1e10</span>; n++) {
    <span class="hljs-comment">// Looping to simulate work.</span>
  }
} <span class="hljs-keyword">else</span> {
  <span class="hljs-comment">// This output will be blocked by the for loop in the main thread.</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'foo'</span>);
}</code><code class="language-js cjs"><span class="hljs-meta">'use strict'</span>;

<span class="hljs-keyword">const</span> {
  <span class="hljs-title class_">Worker</span>,
  isMainThread,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:worker_threads'</span>);

<span class="hljs-keyword">if</span> (isMainThread) {
  <span class="hljs-keyword">new</span> <span class="hljs-title class_">Worker</span>(__filename);
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> n = <span class="hljs-number">0</span>; n &#x3C; <span class="hljs-number">1e10</span>; n++) {
    <span class="hljs-comment">// Looping to simulate work.</span>
  }
} <span class="hljs-keyword">else</span> {
  <span class="hljs-comment">// This output will be blocked by the for loop in the main thread.</span>
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'foo'</span>);
}</code><button class="copy-button">copy</button></pre>
<h4>Launching worker threads from preload scripts<span><a class="mark" href="#all_worker_threads_launching-worker-threads-from-preload-scripts" id="all_worker_threads_launching-worker-threads-from-preload-scripts">#</a></span><a aria-hidden="true" class="legacy" id="worker_threads_launching_worker_threads_from_preload_scripts"></a></h4>
<p>Take care when launching worker threads from preload scripts (scripts loaded
and run using the <code>-r</code> command line flag). Unless the <code>execArgv</code> option is
explicitly set, new Worker threads automatically inherit the command line flags
from the running process and will preload the same preload scripts as the main
thread. If the preload script unconditionally launches a worker thread, every
thread spawned will spawn another until the application crashes.</p></section>
        </section>
<section><h2>Zlib<span><a class="mark" href="#all_zlib_zlib" id="all_zlib_zlib">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib"></a></h2>

<p></p><div class="api_stability api_stability_2"><a href="#all_documentation_stability-index">Stability: 2</a> - Stable</div><p></p>
<p><strong>Source Code:</strong> <a href="https://github.com/nodejs/node/blob/v20.18.0/lib/zlib.js">lib/zlib.js</a></p>
<p>The <code>node:zlib</code> module provides compression functionality implemented using
Gzip, Deflate/Inflate, and Brotli.</p>
<p>To access it:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> zlib = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:zlib'</span>);</code> <button class="copy-button">copy</button></pre>
<p>Compression and decompression are built around the Node.js <a href="stream.html">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"><span class="hljs-keyword">const</span> { createGzip } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:zlib'</span>);
<span class="hljs-keyword">const</span> { pipeline } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);
<span class="hljs-keyword">const</span> {
  createReadStream,
  createWriteStream,
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);

<span class="hljs-keyword">const</span> gzip = <span class="hljs-title function_">createGzip</span>();
<span class="hljs-keyword">const</span> source = <span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'input.txt'</span>);
<span class="hljs-keyword">const</span> destination = <span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'input.txt.gz'</span>);

<span class="hljs-title function_">pipeline</span>(source, gzip, destination, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'An error occurred:'</span>, err);
    process.<span class="hljs-property">exitCode</span> = <span class="hljs-number">1</span>;
  }
});

<span class="hljs-comment">// Or, Promisified</span>

<span class="hljs-keyword">const</span> { promisify } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">const</span> pipe = <span class="hljs-title function_">promisify</span>(pipeline);

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">do_gzip</span>(<span class="hljs-params">input, output</span>) {
  <span class="hljs-keyword">const</span> gzip = <span class="hljs-title function_">createGzip</span>();
  <span class="hljs-keyword">const</span> source = <span class="hljs-title function_">createReadStream</span>(input);
  <span class="hljs-keyword">const</span> destination = <span class="hljs-title function_">createWriteStream</span>(output);
  <span class="hljs-keyword">await</span> <span class="hljs-title function_">pipe</span>(source, gzip, destination);
}

<span class="hljs-title function_">do_gzip</span>(<span class="hljs-string">'input.txt'</span>, <span class="hljs-string">'input.txt.gz'</span>)
  .<span class="hljs-title function_">catch</span>(<span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'An error occurred:'</span>, err);
    process.<span class="hljs-property">exitCode</span> = <span class="hljs-number">1</span>;
  });</code> <button class="copy-button">copy</button></pre>
<p>It is also possible to compress or decompress data in a single step:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> { deflate, unzip } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:zlib'</span>);

<span class="hljs-keyword">const</span> input = <span class="hljs-string">'.................................'</span>;
<span class="hljs-title function_">deflate</span>(input, <span class="hljs-function">(<span class="hljs-params">err, buffer</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'An error occurred:'</span>, err);
    process.<span class="hljs-property">exitCode</span> = <span class="hljs-number">1</span>;
  }
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buffer.<span class="hljs-title function_">toString</span>(<span class="hljs-string">'base64'</span>));
});

<span class="hljs-keyword">const</span> buffer = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'eJzT0yMAAGTvBe8='</span>, <span class="hljs-string">'base64'</span>);
<span class="hljs-title function_">unzip</span>(buffer, <span class="hljs-function">(<span class="hljs-params">err, buffer</span>) =></span> {
  <span class="hljs-keyword">if</span> (err) {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'An error occurred:'</span>, err);
    process.<span class="hljs-property">exitCode</span> = <span class="hljs-number">1</span>;
  }
  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buffer.<span class="hljs-title function_">toString</span>());
});

<span class="hljs-comment">// Or, Promisified</span>

<span class="hljs-keyword">const</span> { promisify } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:util'</span>);
<span class="hljs-keyword">const</span> do_unzip = <span class="hljs-title function_">promisify</span>(unzip);

<span class="hljs-title function_">do_unzip</span>(buffer)
  .<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">buf</span>) =></span> <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buf.<span class="hljs-title function_">toString</span>()))
  .<span class="hljs-title function_">catch</span>(<span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'An error occurred:'</span>, err);
    process.<span class="hljs-property">exitCode</span> = <span class="hljs-number">1</span>;
  });</code> <button class="copy-button">copy</button></pre>
<section><h3>Threadpool usage and performance considerations<span><a class="mark" href="#all_zlib_threadpool-usage-and-performance-considerations" id="all_zlib_threadpool-usage-and-performance-considerations">#</a></span><a aria-hidden="true" class="legacy" id="zlib_threadpool_usage_and_performance_considerations"></a></h3>
<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"><span class="hljs-keyword">const</span> zlib = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:zlib'</span>);

<span class="hljs-keyword">const</span> payload = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'This is some data'</span>);

<span class="hljs-comment">// WARNING: DO NOT DO THIS!</span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &#x3C; <span class="hljs-number">30000</span>; ++i) {
  zlib.<span class="hljs-title function_">deflate</span>(payload, <span class="hljs-function">(<span class="hljs-params">err, buffer</span>) =></span> {});
}</code> <button class="copy-button">copy</button></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 significant memory fragmentation.</p>
<p>It is strongly recommended that the results of compression
operations be cached to avoid duplication of effort.</p>
</section><section><h3>Compressing HTTP requests and responses<span><a class="mark" href="#all_zlib_compressing-http-requests-and-responses" id="all_zlib_compressing-http-requests-and-responses">#</a></span><a aria-hidden="true" class="legacy" id="zlib_compressing_http_requests_and_responses"></a></h3>
<p>The <code>node: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="#all_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"><span class="hljs-comment">// Client request example</span>
<span class="hljs-keyword">const</span> zlib = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:zlib'</span>);
<span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> { pipeline } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);

<span class="hljs-keyword">const</span> request = http.<span class="hljs-title function_">get</span>({ <span class="hljs-attr">host</span>: <span class="hljs-string">'example.com'</span>,
                           <span class="hljs-attr">path</span>: <span class="hljs-string">'/'</span>,
                           <span class="hljs-attr">port</span>: <span class="hljs-number">80</span>,
                           <span class="hljs-attr">headers</span>: { <span class="hljs-string">'Accept-Encoding'</span>: <span class="hljs-string">'br,gzip,deflate'</span> } });
request.<span class="hljs-title function_">on</span>(<span class="hljs-string">'response'</span>, <span class="hljs-function">(<span class="hljs-params">response</span>) =></span> {
  <span class="hljs-keyword">const</span> output = fs.<span class="hljs-title function_">createWriteStream</span>(<span class="hljs-string">'example.com_index.html'</span>);

  <span class="hljs-keyword">const</span> <span class="hljs-title function_">onError</span> = (<span class="hljs-params">err</span>) => {
    <span class="hljs-keyword">if</span> (err) {
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'An error occurred:'</span>, err);
      process.<span class="hljs-property">exitCode</span> = <span class="hljs-number">1</span>;
    }
  };

  <span class="hljs-keyword">switch</span> (response.<span class="hljs-property">headers</span>[<span class="hljs-string">'content-encoding'</span>]) {
    <span class="hljs-keyword">case</span> <span class="hljs-string">'br'</span>:
      <span class="hljs-title function_">pipeline</span>(response, zlib.<span class="hljs-title function_">createBrotliDecompress</span>(), output, onError);
      <span class="hljs-keyword">break</span>;
    <span class="hljs-comment">// Or, just use zlib.createUnzip() to handle both of the following cases:</span>
    <span class="hljs-keyword">case</span> <span class="hljs-string">'gzip'</span>:
      <span class="hljs-title function_">pipeline</span>(response, zlib.<span class="hljs-title function_">createGunzip</span>(), output, onError);
      <span class="hljs-keyword">break</span>;
    <span class="hljs-keyword">case</span> <span class="hljs-string">'deflate'</span>:
      <span class="hljs-title function_">pipeline</span>(response, zlib.<span class="hljs-title function_">createInflate</span>(), output, onError);
      <span class="hljs-keyword">break</span>;
    <span class="hljs-attr">default</span>:
      <span class="hljs-title function_">pipeline</span>(response, output, onError);
      <span class="hljs-keyword">break</span>;
  }
});</code> <button class="copy-button">copy</button></pre>
<pre><code class="language-js"><span class="hljs-comment">// server example</span>
<span class="hljs-comment">// Running a gzip operation on every request is quite expensive.</span>
<span class="hljs-comment">// It would be much more efficient to cache the compressed buffer.</span>
<span class="hljs-keyword">const</span> zlib = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:zlib'</span>);
<span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:fs'</span>);
<span class="hljs-keyword">const</span> { pipeline } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);

http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">request, response</span>) =></span> {
  <span class="hljs-keyword">const</span> raw = fs.<span class="hljs-title function_">createReadStream</span>(<span class="hljs-string">'index.html'</span>);
  <span class="hljs-comment">// Store both a compressed and an uncompressed version of the resource.</span>
  response.<span class="hljs-title function_">setHeader</span>(<span class="hljs-string">'Vary'</span>, <span class="hljs-string">'Accept-Encoding'</span>);
  <span class="hljs-keyword">let</span> acceptEncoding = request.<span class="hljs-property">headers</span>[<span class="hljs-string">'accept-encoding'</span>];
  <span class="hljs-keyword">if</span> (!acceptEncoding) {
    acceptEncoding = <span class="hljs-string">''</span>;
  }

  <span class="hljs-keyword">const</span> <span class="hljs-title function_">onError</span> = (<span class="hljs-params">err</span>) => {
    <span class="hljs-keyword">if</span> (err) {
      <span class="hljs-comment">// If an error occurs, there's not much we can do because</span>
      <span class="hljs-comment">// the server has already sent the 200 response code and</span>
      <span class="hljs-comment">// some amount of data has already been sent to the client.</span>
      <span class="hljs-comment">// The best we can do is terminate the response immediately</span>
      <span class="hljs-comment">// and log the error.</span>
      response.<span class="hljs-title function_">end</span>();
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'An error occurred:'</span>, err);
    }
  };

  <span class="hljs-comment">// Note: This is not a conformant accept-encoding parser.</span>
  <span class="hljs-comment">// See https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3</span>
  <span class="hljs-keyword">if</span> (<span class="hljs-regexp">/\bdeflate\b/</span>.<span class="hljs-title function_">test</span>(acceptEncoding)) {
    response.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Encoding'</span>: <span class="hljs-string">'deflate'</span> });
    <span class="hljs-title function_">pipeline</span>(raw, zlib.<span class="hljs-title function_">createDeflate</span>(), response, onError);
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (<span class="hljs-regexp">/\bgzip\b/</span>.<span class="hljs-title function_">test</span>(acceptEncoding)) {
    response.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Encoding'</span>: <span class="hljs-string">'gzip'</span> });
    <span class="hljs-title function_">pipeline</span>(raw, zlib.<span class="hljs-title function_">createGzip</span>(), response, onError);
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (<span class="hljs-regexp">/\bbr\b/</span>.<span class="hljs-title function_">test</span>(acceptEncoding)) {
    response.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'Content-Encoding'</span>: <span class="hljs-string">'br'</span> });
    <span class="hljs-title function_">pipeline</span>(raw, zlib.<span class="hljs-title function_">createBrotliCompress</span>(), response, onError);
  } <span class="hljs-keyword">else</span> {
    response.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, {});
    <span class="hljs-title function_">pipeline</span>(raw, response, onError);
  }
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">1337</span>);</code> <button class="copy-button">copy</button></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"><span class="hljs-comment">// This is a truncated version of the buffer from the above examples</span>
<span class="hljs-keyword">const</span> buffer = <span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'eJzT0yMA'</span>, <span class="hljs-string">'base64'</span>);

zlib.<span class="hljs-title function_">unzip</span>(
  buffer,
  <span class="hljs-comment">// For Brotli, the equivalent is zlib.constants.BROTLI_OPERATION_FLUSH.</span>
  { <span class="hljs-attr">finishFlush</span>: zlib.<span class="hljs-property">constants</span>.<span class="hljs-property">Z_SYNC_FLUSH</span> },
  <span class="hljs-function">(<span class="hljs-params">err, buffer</span>) =></span> {
    <span class="hljs-keyword">if</span> (err) {
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'An error occurred:'</span>, err);
      process.<span class="hljs-property">exitCode</span> = <span class="hljs-number">1</span>;
    }
    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(buffer.<span class="hljs-title function_">toString</span>());
  });</code> <button class="copy-button">copy</button></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>
</section><section><h3>Memory usage tuning<span><a class="mark" href="#all_zlib_memory-usage-tuning" id="all_zlib_memory-usage-tuning">#</a></span><a aria-hidden="true" class="legacy" id="zlib_memory_usage_tuning"></a></h3>

<h4>For zlib-based streams<span><a class="mark" href="#all_zlib_for-zlib-based-streams" id="all_zlib_for-zlib-based-streams">#</a></span><a aria-hidden="true" class="legacy" id="zlib_for_zlib_based_streams"></a></h4>
<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 @stylistic/js/semi -->
<pre><code class="language-js">(<span class="hljs-number">1</span> &#x3C;&#x3C; (windowBits + <span class="hljs-number">2</span>)) + (<span class="hljs-number">1</span> &#x3C;&#x3C; (memLevel + <span class="hljs-number">9</span>))</code> <button class="copy-button">copy</button></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"><span class="hljs-keyword">const</span> options = { <span class="hljs-attr">windowBits</span>: <span class="hljs-number">14</span>, <span class="hljs-attr">memLevel</span>: <span class="hljs-number">7</span> };</code> <button class="copy-button">copy</button></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>
<h4>For Brotli-based streams<span><a class="mark" href="#all_zlib_for-brotli-based-streams" id="all_zlib_for-brotli-based-streams">#</a></span><a aria-hidden="true" class="legacy" id="zlib_for_brotli_based_streams"></a></h4>
<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="#all_zlib_brotli-constants">below</a> for more details on Brotli-specific options.</p>
</section><section><h3>Flushing<span><a class="mark" href="#all_zlib_flushing" id="all_zlib_flushing">#</a></span><a aria-hidden="true" class="legacy" id="zlib_flushing"></a></h3>
<p>Calling <a href="#all_zlib_zlibflushkind-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"><span class="hljs-keyword">const</span> zlib = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:zlib'</span>);
<span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:http'</span>);
<span class="hljs-keyword">const</span> { pipeline } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:stream'</span>);

http.<span class="hljs-title function_">createServer</span>(<span class="hljs-function">(<span class="hljs-params">request, response</span>) =></span> {
  <span class="hljs-comment">// For the sake of simplicity, the Accept-Encoding checks are omitted.</span>
  response.<span class="hljs-title function_">writeHead</span>(<span class="hljs-number">200</span>, { <span class="hljs-string">'content-encoding'</span>: <span class="hljs-string">'gzip'</span> });
  <span class="hljs-keyword">const</span> output = zlib.<span class="hljs-title function_">createGzip</span>();
  <span class="hljs-keyword">let</span> i;

  <span class="hljs-title function_">pipeline</span>(output, response, <span class="hljs-function">(<span class="hljs-params">err</span>) =></span> {
    <span class="hljs-keyword">if</span> (err) {
      <span class="hljs-comment">// If an error occurs, there's not much we can do because</span>
      <span class="hljs-comment">// the server has already sent the 200 response code and</span>
      <span class="hljs-comment">// some amount of data has already been sent to the client.</span>
      <span class="hljs-comment">// The best we can do is terminate the response immediately</span>
      <span class="hljs-comment">// and log the error.</span>
      <span class="hljs-built_in">clearInterval</span>(i);
      response.<span class="hljs-title function_">end</span>();
      <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(<span class="hljs-string">'An error occurred:'</span>, err);
    }
  });

  i = <span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =></span> {
    output.<span class="hljs-title function_">write</span>(<span class="hljs-string">`The current time is <span class="hljs-subst">${<span class="hljs-built_in">Date</span>()}</span>\n`</span>, <span class="hljs-function">() =></span> {
      <span class="hljs-comment">// The data has been passed to zlib, but the compression algorithm may</span>
      <span class="hljs-comment">// have decided to buffer the data for more efficient compression.</span>
      <span class="hljs-comment">// Calling .flush() will make the data available as soon as the client</span>
      <span class="hljs-comment">// is ready to receive it.</span>
      output.<span class="hljs-title function_">flush</span>();
    });
  }, <span class="hljs-number">1000</span>);
}).<span class="hljs-title function_">listen</span>(<span class="hljs-number">1337</span>);</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Constants<span><a class="mark" href="#all_zlib_constants" id="all_zlib_constants">#</a></span><a aria-hidden="true" class="legacy" id="zlib_constants"></a></h3>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>

<h4>zlib constants<span><a class="mark" href="#all_zlib_zlib-constants" id="all_zlib_zlib-constants">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_constants"></a></h4>
<p>All of the constants defined in <code>zlib.h</code> are also defined on
<code>require('node: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('node: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>
<h4>Brotli constants<span><a class="mark" href="#all_zlib_brotli-constants" id="all_zlib_brotli-constants">#</a></span><a aria-hidden="true" class="legacy" id="zlib_brotli_constants"></a></h4>
<div class="api_metadata">
<span>Added in: v11.7.0, v10.16.0</span>
</div>
<p>There are several options and other constants available for Brotli-based
streams:</p>
<h5>Flush operations<span><a class="mark" href="#all_zlib_flush-operations" id="all_zlib_flush-operations">#</a></span><a aria-hidden="true" class="legacy" id="zlib_flush_operations"></a></h5>
<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><code>zlib.constants.BROTLI_OPERATION_EMIT_METADATA</code>
<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>
<h5>Compressor options<span><a class="mark" href="#all_zlib_compressor-options" id="all_zlib_compressor-options">#</a></span><a aria-hidden="true" class="legacy" id="zlib_compressor_options"></a></h5>
<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><code>BROTLI_PARAM_MODE</code>
<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><code>BROTLI_PARAM_QUALITY</code>
<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><code>BROTLI_PARAM_SIZE_HINT</code>
<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><code>BROTLI_PARAM_LGWIN</code>
<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><code>BROTLI_PARAM_LGBLOCK</code>
<ul>
<li>Ranges from <code>BROTLI_MIN_INPUT_BLOCK_BITS</code> to <code>BROTLI_MAX_INPUT_BLOCK_BITS</code>.</li>
</ul>
</li>
<li><code>BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING</code>
<ul>
<li>Boolean flag that decreases compression ratio in favour of
decompression speed.</li>
</ul>
</li>
<li><code>BROTLI_PARAM_LARGE_WINDOW</code>
<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><code>BROTLI_PARAM_NPOSTFIX</code>
<ul>
<li>Ranges from <code>0</code> to <code>BROTLI_MAX_NPOSTFIX</code>.</li>
</ul>
</li>
<li><code>BROTLI_PARAM_NDIRECT</code>
<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>
<h5>Decompressor options<span><a class="mark" href="#all_zlib_decompressor-options" id="all_zlib_decompressor-options">#</a></span><a aria-hidden="true" class="legacy" id="zlib_decompressor_options"></a></h5>
<p>These advanced options are available for controlling decompression:</p>
<ul>
<li><code>BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION</code>
<ul>
<li>Boolean flag that affects internal memory allocation patterns.</li>
</ul>
</li>
<li><code>BROTLI_DECODER_PARAM_LARGE_WINDOW</code>
<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>
</section><section><h3>Class: <code>Options</code><span><a class="mark" href="#all_zlib_class-options" id="all_zlib_class-options">#</a></span><a aria-hidden="true" class="legacy" id="zlib_class_options"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.5.0, v12.19.0</td>
<td><p>The <code>maxOutputLength</code> option is supported now.</p></td></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="#all_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>
<li><code>maxOutputLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Limits output size when using
<a href="#all_zlib_convenience-methods">convenience methods</a>. <strong>Default:</strong> <a href="#all_buffer_bufferkmaxlength"><code>buffer.kMaxLength</code></a></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>
</section><section><h3>Class: <code>BrotliOptions</code><span><a class="mark" href="#all_zlib_class-brotlioptions" id="all_zlib_class-brotlioptions">#</a></span><a aria-hidden="true" class="legacy" id="zlib_class_brotlioptions"></a></h3>
<div class="api_metadata">
<details class="changelog"><summary>History</summary>
<table>
<tbody><tr><th>Version</th><th>Changes</th></tr>
<tr><td>v14.5.0, v12.19.0</td>
<td><p>The <code>maxOutputLength</code> option is supported now.</p></td></tr>
<tr><td>v11.7.0</td>
<td><p><span>Added in: v11.7.0</span></p></td></tr>
</tbody></table>
</details>
</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="#all_zlib_brotli-constants">Brotli parameters</a>.</li>
<li><code>maxOutputLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> Limits output size when using
<a href="#all_zlib_convenience-methods">convenience methods</a>. <strong>Default:</strong> <a href="#all_buffer_bufferkmaxlength"><code>buffer.kMaxLength</code></a></li>
</ul>
<p>For example:</p>
<pre><code class="language-js"><span class="hljs-keyword">const</span> stream = zlib.<span class="hljs-title function_">createBrotliCompress</span>({
  <span class="hljs-attr">chunkSize</span>: <span class="hljs-number">32</span> * <span class="hljs-number">1024</span>,
  <span class="hljs-attr">params</span>: {
    [zlib.<span class="hljs-property">constants</span>.<span class="hljs-property">BROTLI_PARAM_MODE</span>]: zlib.<span class="hljs-property">constants</span>.<span class="hljs-property">BROTLI_MODE_TEXT</span>,
    [zlib.<span class="hljs-property">constants</span>.<span class="hljs-property">BROTLI_PARAM_QUALITY</span>]: <span class="hljs-number">4</span>,
    [zlib.<span class="hljs-property">constants</span>.<span class="hljs-property">BROTLI_PARAM_SIZE_HINT</span>]: fs.<span class="hljs-title function_">statSync</span>(inputFile).<span class="hljs-property">size</span>,
  },
});</code> <button class="copy-button">copy</button></pre>
</section><section><h3>Class: <code>zlib.BrotliCompress</code><span><a class="mark" href="#all_zlib_class-zlibbrotlicompress" id="all_zlib_class-zlibbrotlicompress">#</a></span><a aria-hidden="true" class="legacy" id="zlib_class_zlib_brotlicompress"></a></h3>
<div class="api_metadata">
<span>Added in: v11.7.0, v10.16.0</span>
</div>
<p>Compress data using the Brotli algorithm.</p>
</section><section><h3>Class: <code>zlib.BrotliDecompress</code><span><a class="mark" href="#all_zlib_class-zlibbrotlidecompress" id="all_zlib_class-zlibbrotlidecompress">#</a></span><a aria-hidden="true" class="legacy" id="zlib_class_zlib_brotlidecompress"></a></h3>
<div class="api_metadata">
<span>Added in: v11.7.0, v10.16.0</span>
</div>
<p>Decompress data using the Brotli algorithm.</p>
</section><section><h3>Class: <code>zlib.Deflate</code><span><a class="mark" href="#all_zlib_class-zlibdeflate" id="all_zlib_class-zlibdeflate">#</a></span><a aria-hidden="true" class="legacy" id="zlib_class_zlib_deflate"></a></h3>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<p>Compress data using deflate.</p>
</section><section><h3>Class: <code>zlib.DeflateRaw</code><span><a class="mark" href="#all_zlib_class-zlibdeflateraw" id="all_zlib_class-zlibdeflateraw">#</a></span><a aria-hidden="true" class="legacy" id="zlib_class_zlib_deflateraw"></a></h3>
<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>
</section><section><h3>Class: <code>zlib.Gunzip</code><span><a class="mark" href="#all_zlib_class-zlibgunzip" id="all_zlib_class-zlibgunzip">#</a></span><a aria-hidden="true" class="legacy" id="zlib_class_zlib_gunzip"></a></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>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>
</section><section><h3>Class: <code>zlib.Gzip</code><span><a class="mark" href="#all_zlib_class-zlibgzip" id="all_zlib_class-zlibgzip">#</a></span><a aria-hidden="true" class="legacy" id="zlib_class_zlib_gzip"></a></h3>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<p>Compress data using gzip.</p>
</section><section><h3>Class: <code>zlib.Inflate</code><span><a class="mark" href="#all_zlib_class-zlibinflate" id="all_zlib_class-zlibinflate">#</a></span><a aria-hidden="true" class="legacy" id="zlib_class_zlib_inflate"></a></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>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>
</section><section><h3>Class: <code>zlib.InflateRaw</code><span><a class="mark" href="#all_zlib_class-zlibinflateraw" id="all_zlib_class-zlibinflateraw">#</a></span><a aria-hidden="true" class="legacy" id="zlib_class_zlib_inflateraw"></a></h3>
<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>
</section><section><h3>Class: <code>zlib.Unzip</code><span><a class="mark" href="#all_zlib_class-zlibunzip" id="all_zlib_class-zlibunzip">#</a></span><a aria-hidden="true" class="legacy" id="zlib_class_zlib_unzip"></a></h3>
<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>
</section><section><h3>Class: <code>zlib.ZlibBase</code><span><a class="mark" href="#all_zlib_class-zlibzlibbase" id="all_zlib_class-zlibzlibbase">#</a></span><a aria-hidden="true" class="legacy" id="zlib_class_zlib_zlibbase"></a></h3>
<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, v10.16.0</td>
<td><p>This class was renamed from <code>Zlib</code> to <code>ZlibBase</code>.</p></td></tr>
<tr><td>v0.5.8</td>
<td><p><span>Added in: v0.5.8</span></p></td></tr>
</tbody></table>
</details>
</div>
<p>Not exported by the <code>node: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="#all_stream_class-streamtransform"><code>stream.Transform</code></a>, allowing <code>node:zlib</code> objects to
be used in pipes and similar stream operations.</p>
<h4><code>zlib.bytesRead</code><span><a class="mark" href="#all_zlib_zlibbytesread" id="all_zlib_zlibbytesread">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_bytesread"></a></h4>
<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="#all_documentation_stability-index">Stability: 0</a> - Deprecated: Use <a href="#all_zlib_zlibbyteswritten"><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="#all_zlib_zlibbyteswritten"><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>
<h4><code>zlib.bytesWritten</code><span><a class="mark" href="#all_zlib_zlibbyteswritten" id="all_zlib_zlibbyteswritten">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_byteswritten"></a></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></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>
<h4><code>zlib.crc32(data[, value])</code><span><a class="mark" href="#all_zlib_zlibcrc32data-value" id="all_zlib_zlibcrc32data-value">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_crc32_data_value"></a></h4>
<div class="api_metadata">
<span>Added in: v20.15.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="#all_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> When <code>data</code> is a string,
it will be encoded as UTF-8 before being used for computation.</li>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type">&#x3C;integer></a> An optional starting value. It must be a 32-bit unsigned
integer. <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> A 32-bit unsigned integer containing the checksum.</li>
</ul>
<p>Computes a 32-bit <a href="https://en.wikipedia.org/wiki/Cyclic_redundancy_check">Cyclic Redundancy Check</a> checksum of <code>data</code>. If
<code>value</code> is specified, it is used as the starting value of the checksum,
otherwise, 0 is used as the starting value.</p>
<p>The CRC algorithm is designed to compute checksums and to detect error
in data transmission. It's not suitable for cryptographic authentication.</p>
<p>To be consistent with other APIs, if the <code>data</code> is a string, it will
be encoded with UTF-8 before being used for computation. If users only
use Node.js to compute and match the checksums, this works well with
other APIs that uses the UTF-8 encoding by default.</p>
<p>Some third-party JavaScript libraries compute the checksum on a
string based on <code>str.charCodeAt()</code> so that it can be run in browsers.
If users want to match the checksum computed with this kind of library
in the browser, it's better to use the same library in Node.js
if it also runs in Node.js. If users have to use <code>zlib.crc32()</code> to
match the checksum produced by such a third-party library:</p>
<ol>
<li>If the library accepts <code>Uint8Array</code> as input, use <code>TextEncoder</code>
in the browser to encode the string into a <code>Uint8Array</code> with UTF-8
encoding, and compute the checksum based on the UTF-8 encoded string
in the browser.</li>
<li>If the library only takes a string and compute the data based on
<code>str.charCodeAt()</code>, on the Node.js side, convert the string into
a buffer using <code>Buffer.from(str, 'utf16le')</code>.</li>
</ol>

<pre class="with-42-chars"><input class="js-flavor-toggle" type="checkbox" checked aria-label="Show modern ES modules syntax"><code class="language-js mjs"><span class="hljs-keyword">import</span> zlib <span class="hljs-keyword">from</span> <span class="hljs-string">'node:zlib'</span>;
<span class="hljs-keyword">import</span> { <span class="hljs-title class_">Buffer</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'node:buffer'</span>;

<span class="hljs-keyword">let</span> crc = zlib.<span class="hljs-title function_">crc32</span>(<span class="hljs-string">'hello'</span>);  <span class="hljs-comment">// 907060870</span>
crc = zlib.<span class="hljs-title function_">crc32</span>(<span class="hljs-string">'world'</span>, crc);  <span class="hljs-comment">// 4192936109</span>

crc = zlib.<span class="hljs-title function_">crc32</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'hello'</span>, <span class="hljs-string">'utf16le'</span>));  <span class="hljs-comment">// 1427272415</span>
crc = zlib.<span class="hljs-title function_">crc32</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'world'</span>, <span class="hljs-string">'utf16le'</span>), crc);  <span class="hljs-comment">// 4150509955</span></code><code class="language-js cjs"><span class="hljs-keyword">const</span> zlib = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:zlib'</span>);
<span class="hljs-keyword">const</span> { <span class="hljs-title class_">Buffer</span> } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'node:buffer'</span>);

<span class="hljs-keyword">let</span> crc = zlib.<span class="hljs-title function_">crc32</span>(<span class="hljs-string">'hello'</span>);  <span class="hljs-comment">// 907060870</span>
crc = zlib.<span class="hljs-title function_">crc32</span>(<span class="hljs-string">'world'</span>, crc);  <span class="hljs-comment">// 4192936109</span>

crc = zlib.<span class="hljs-title function_">crc32</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'hello'</span>, <span class="hljs-string">'utf16le'</span>));  <span class="hljs-comment">// 1427272415</span>
crc = zlib.<span class="hljs-title function_">crc32</span>(<span class="hljs-title class_">Buffer</span>.<span class="hljs-title function_">from</span>(<span class="hljs-string">'world'</span>, <span class="hljs-string">'utf16le'</span>), crc);  <span class="hljs-comment">// 4150509955</span></code><button class="copy-button">copy</button></pre>
<h4><code>zlib.close([callback])</code><span><a class="mark" href="#all_zlib_zlibclosecallback" id="all_zlib_zlibclosecallback">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_close_callback"></a></h4>
<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>
<h4><code>zlib.flush([kind, ]callback)</code><span><a class="mark" href="#all_zlib_zlibflushkind-callback" id="all_zlib_zlibflushkind-callback">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_flush_kind_callback"></a></h4>
<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>
<h4><code>zlib.params(level, strategy, callback)</code><span><a class="mark" href="#all_zlib_zlibparamslevel-strategy-callback" id="all_zlib_zlibparamslevel-strategy-callback">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_params_level_strategy_callback"></a></h4>
<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>
<h4><code>zlib.reset()</code><span><a class="mark" href="#all_zlib_zlibreset" id="all_zlib_zlibreset">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_reset"></a></h4>
<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>
</section><section><h3><code>zlib.constants</code><span><a class="mark" href="#all_zlib_zlibconstants" id="all_zlib_zlibconstants">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_constants_1"></a></h3>
<div class="api_metadata">
<span>Added in: v7.0.0</span>
</div>
<p>Provides an object enumerating Zlib-related constants.</p>
</section><section><h3><code>zlib.createBrotliCompress([options])</code><span><a class="mark" href="#all_zlib_zlibcreatebrotlicompressoptions" id="all_zlib_zlibcreatebrotlicompressoptions">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_createbrotlicompress_options"></a></h3>
<div class="api_metadata">
<span>Added in: v11.7.0, v10.16.0</span>
</div>
<ul>
<li><code>options</code> <a href="#all_zlib_class-brotlioptions" class="type">&#x3C;brotli options></a></li>
</ul>
<p>Creates and returns a new <a href="#all_zlib_class-zlibbrotlicompress"><code>BrotliCompress</code></a> object.</p>
</section><section><h3><code>zlib.createBrotliDecompress([options])</code><span><a class="mark" href="#all_zlib_zlibcreatebrotlidecompressoptions" id="all_zlib_zlibcreatebrotlidecompressoptions">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_createbrotlidecompress_options"></a></h3>
<div class="api_metadata">
<span>Added in: v11.7.0, v10.16.0</span>
</div>
<ul>
<li><code>options</code> <a href="#all_zlib_class-brotlioptions" class="type">&#x3C;brotli options></a></li>
</ul>
<p>Creates and returns a new <a href="#all_zlib_class-zlibbrotlidecompress"><code>BrotliDecompress</code></a> object.</p>
</section><section><h3><code>zlib.createDeflate([options])</code><span><a class="mark" href="#all_zlib_zlibcreatedeflateoptions" id="all_zlib_zlibcreatedeflateoptions">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_createdeflate_options"></a></h3>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<ul>
<li><code>options</code> <a href="#all_zlib_class-options" class="type">&#x3C;zlib options></a></li>
</ul>
<p>Creates and returns a new <a href="#all_zlib_class-zlibdeflate"><code>Deflate</code></a> object.</p>
</section><section><h3><code>zlib.createDeflateRaw([options])</code><span><a class="mark" href="#all_zlib_zlibcreatedeflaterawoptions" id="all_zlib_zlibcreatedeflaterawoptions">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_createdeflateraw_options"></a></h3>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<ul>
<li><code>options</code> <a href="#all_zlib_class-options" class="type">&#x3C;zlib options></a></li>
</ul>
<p>Creates and returns a new <a href="#all_zlib_class-zlibdeflateraw"><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>
</section><section><h3><code>zlib.createGunzip([options])</code><span><a class="mark" href="#all_zlib_zlibcreategunzipoptions" id="all_zlib_zlibcreategunzipoptions">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_creategunzip_options"></a></h3>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<ul>
<li><code>options</code> <a href="#all_zlib_class-options" class="type">&#x3C;zlib options></a></li>
</ul>
<p>Creates and returns a new <a href="#all_zlib_class-zlibgunzip"><code>Gunzip</code></a> object.</p>
</section><section><h3><code>zlib.createGzip([options])</code><span><a class="mark" href="#all_zlib_zlibcreategzipoptions" id="all_zlib_zlibcreategzipoptions">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_creategzip_options"></a></h3>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<ul>
<li><code>options</code> <a href="#all_zlib_class-options" class="type">&#x3C;zlib options></a></li>
</ul>
<p>Creates and returns a new <a href="#all_zlib_class-zlibgzip"><code>Gzip</code></a> object.
See <a href="#all_zlib_zlib">example</a>.</p>
</section><section><h3><code>zlib.createInflate([options])</code><span><a class="mark" href="#all_zlib_zlibcreateinflateoptions" id="all_zlib_zlibcreateinflateoptions">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_createinflate_options"></a></h3>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<ul>
<li><code>options</code> <a href="#all_zlib_class-options" class="type">&#x3C;zlib options></a></li>
</ul>
<p>Creates and returns a new <a href="#all_zlib_class-zlibinflate"><code>Inflate</code></a> object.</p>
</section><section><h3><code>zlib.createInflateRaw([options])</code><span><a class="mark" href="#all_zlib_zlibcreateinflaterawoptions" id="all_zlib_zlibcreateinflaterawoptions">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_createinflateraw_options"></a></h3>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<ul>
<li><code>options</code> <a href="#all_zlib_class-options" class="type">&#x3C;zlib options></a></li>
</ul>
<p>Creates and returns a new <a href="#all_zlib_class-zlibinflateraw"><code>InflateRaw</code></a> object.</p>
</section><section><h3><code>zlib.createUnzip([options])</code><span><a class="mark" href="#all_zlib_zlibcreateunzipoptions" id="all_zlib_zlibcreateunzipoptions">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_createunzip_options"></a></h3>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div>
<ul>
<li><code>options</code> <a href="#all_zlib_class-options" class="type">&#x3C;zlib options></a></li>
</ul>
<p>Creates and returns a new <a href="#all_zlib_class-zlibunzip"><code>Unzip</code></a> object.</p>
</section><section><h3>Convenience methods<span><a class="mark" href="#all_zlib_convenience-methods" id="all_zlib_convenience-methods">#</a></span><a aria-hidden="true" class="legacy" id="zlib_convenience_methods"></a></h3>

<p>All of these take a <a href="#all_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>
<h4><code>zlib.brotliCompress(buffer[, options], callback)</code><span><a class="mark" href="#all_zlib_zlibbrotlicompressbuffer-options-callback" id="all_zlib_zlibbrotlicompressbuffer-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_brotlicompress_buffer_options_callback"></a></h4>
<div class="api_metadata">
<span>Added in: v11.7.0, v10.16.0</span>
</div>
<ul>
<li><code>buffer</code> <a href="#all_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="#all_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>
<h4><code>zlib.brotliCompressSync(buffer[, options])</code><span><a class="mark" href="#all_zlib_zlibbrotlicompresssyncbuffer-options" id="all_zlib_zlibbrotlicompresssyncbuffer-options">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_brotlicompresssync_buffer_options"></a></h4>
<div class="api_metadata">
<span>Added in: v11.7.0, v10.16.0</span>
</div>
<ul>
<li><code>buffer</code> <a href="#all_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="#all_zlib_class-brotlioptions" class="type">&#x3C;brotli options></a></li>
</ul>
<p>Compress a chunk of data with <a href="#all_zlib_class-zlibbrotlicompress"><code>BrotliCompress</code></a>.</p>
<h4><code>zlib.brotliDecompress(buffer[, options], callback)</code><span><a class="mark" href="#all_zlib_zlibbrotlidecompressbuffer-options-callback" id="all_zlib_zlibbrotlidecompressbuffer-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_brotlidecompress_buffer_options_callback"></a></h4>
<div class="api_metadata">
<span>Added in: v11.7.0, v10.16.0</span>
</div>
<ul>
<li><code>buffer</code> <a href="#all_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="#all_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>
<h4><code>zlib.brotliDecompressSync(buffer[, options])</code><span><a class="mark" href="#all_zlib_zlibbrotlidecompresssyncbuffer-options" id="all_zlib_zlibbrotlidecompresssyncbuffer-options">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_brotlidecompresssync_buffer_options"></a></h4>
<div class="api_metadata">
<span>Added in: v11.7.0, v10.16.0</span>
</div>
<ul>
<li><code>buffer</code> <a href="#all_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="#all_zlib_class-brotlioptions" class="type">&#x3C;brotli options></a></li>
</ul>
<p>Decompress a chunk of data with <a href="#all_zlib_class-zlibbrotlidecompress"><code>BrotliDecompress</code></a>.</p>
<h4><code>zlib.deflate(buffer[, options], callback)</code><span><a class="mark" href="#all_zlib_zlibdeflatebuffer-options-callback" id="all_zlib_zlibdeflatebuffer-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_deflate_buffer_options_callback"></a></h4>
<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="#all_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="#all_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>
<h4><code>zlib.deflateSync(buffer[, options])</code><span><a class="mark" href="#all_zlib_zlibdeflatesyncbuffer-options" id="all_zlib_zlibdeflatesyncbuffer-options">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_deflatesync_buffer_options"></a></h4>
<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="#all_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="#all_zlib_class-options" class="type">&#x3C;zlib options></a></li>
</ul>
<p>Compress a chunk of data with <a href="#all_zlib_class-zlibdeflate"><code>Deflate</code></a>.</p>
<h4><code>zlib.deflateRaw(buffer[, options], callback)</code><span><a class="mark" href="#all_zlib_zlibdeflaterawbuffer-options-callback" id="all_zlib_zlibdeflaterawbuffer-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_deflateraw_buffer_options_callback"></a></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>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="#all_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="#all_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>
<h4><code>zlib.deflateRawSync(buffer[, options])</code><span><a class="mark" href="#all_zlib_zlibdeflaterawsyncbuffer-options" id="all_zlib_zlibdeflaterawsyncbuffer-options">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_deflaterawsync_buffer_options"></a></h4>
<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="#all_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="#all_zlib_class-options" class="type">&#x3C;zlib options></a></li>
</ul>
<p>Compress a chunk of data with <a href="#all_zlib_class-zlibdeflateraw"><code>DeflateRaw</code></a>.</p>
<h4><code>zlib.gunzip(buffer[, options], callback)</code><span><a class="mark" href="#all_zlib_zlibgunzipbuffer-options-callback" id="all_zlib_zlibgunzipbuffer-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_gunzip_buffer_options_callback"></a></h4>
<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="#all_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="#all_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>
<h4><code>zlib.gunzipSync(buffer[, options])</code><span><a class="mark" href="#all_zlib_zlibgunzipsyncbuffer-options" id="all_zlib_zlibgunzipsyncbuffer-options">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_gunzipsync_buffer_options"></a></h4>
<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="#all_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="#all_zlib_class-options" class="type">&#x3C;zlib options></a></li>
</ul>
<p>Decompress a chunk of data with <a href="#all_zlib_class-zlibgunzip"><code>Gunzip</code></a>.</p>
<h4><code>zlib.gzip(buffer[, options], callback)</code><span><a class="mark" href="#all_zlib_zlibgzipbuffer-options-callback" id="all_zlib_zlibgzipbuffer-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_gzip_buffer_options_callback"></a></h4>
<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="#all_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="#all_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>
<h4><code>zlib.gzipSync(buffer[, options])</code><span><a class="mark" href="#all_zlib_zlibgzipsyncbuffer-options" id="all_zlib_zlibgzipsyncbuffer-options">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_gzipsync_buffer_options"></a></h4>
<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="#all_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="#all_zlib_class-options" class="type">&#x3C;zlib options></a></li>
</ul>
<p>Compress a chunk of data with <a href="#all_zlib_class-zlibgzip"><code>Gzip</code></a>.</p>
<h4><code>zlib.inflate(buffer[, options], callback)</code><span><a class="mark" href="#all_zlib_zlibinflatebuffer-options-callback" id="all_zlib_zlibinflatebuffer-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_inflate_buffer_options_callback"></a></h4>
<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="#all_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="#all_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>
<h4><code>zlib.inflateSync(buffer[, options])</code><span><a class="mark" href="#all_zlib_zlibinflatesyncbuffer-options" id="all_zlib_zlibinflatesyncbuffer-options">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_inflatesync_buffer_options"></a></h4>
<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="#all_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="#all_zlib_class-options" class="type">&#x3C;zlib options></a></li>
</ul>
<p>Decompress a chunk of data with <a href="#all_zlib_class-zlibinflate"><code>Inflate</code></a>.</p>
<h4><code>zlib.inflateRaw(buffer[, options], callback)</code><span><a class="mark" href="#all_zlib_zlibinflaterawbuffer-options-callback" id="all_zlib_zlibinflaterawbuffer-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_inflateraw_buffer_options_callback"></a></h4>
<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="#all_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="#all_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>
<h4><code>zlib.inflateRawSync(buffer[, options])</code><span><a class="mark" href="#all_zlib_zlibinflaterawsyncbuffer-options" id="all_zlib_zlibinflaterawsyncbuffer-options">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_inflaterawsync_buffer_options"></a></h4>
<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="#all_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="#all_zlib_class-options" class="type">&#x3C;zlib options></a></li>
</ul>
<p>Decompress a chunk of data with <a href="#all_zlib_class-zlibinflateraw"><code>InflateRaw</code></a>.</p>
<h4><code>zlib.unzip(buffer[, options], callback)</code><span><a class="mark" href="#all_zlib_zlibunzipbuffer-options-callback" id="all_zlib_zlibunzipbuffer-options-callback">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_unzip_buffer_options_callback"></a></h4>
<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="#all_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="#all_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>
<h4><code>zlib.unzipSync(buffer[, options])</code><span><a class="mark" href="#all_zlib_zlibunzipsyncbuffer-options" id="all_zlib_zlibunzipsyncbuffer-options">#</a></span><a aria-hidden="true" class="legacy" id="zlib_zlib_unzipsync_buffer_options"></a></h4>
<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="#all_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="#all_zlib_class-options" class="type">&#x3C;zlib options></a></li>
</ul>
<p>Decompress a chunk of data with <a href="#all_zlib_class-zlibunzip"><code>Unzip</code></a>.</p></section>
        </section>
<!-- API END -->
      </div>
    </div>
  </div>
</body>
</html>

Anon7 - 2022
AnonSec Team